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
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"builder-Ycvq3ETg.mjs","names":["depth","v","#create","#update","#filter","#readCreate","#readUpdate","#readFilter","v","vectorDistanceMetricSchema","v","v","v","issue","v","v","v","resolved","v","v","v","v","v","getCreateSchema","getUpdateSchema","v","getCreateSchema","v","depth","v","getUpdateSchema","v","getCreateSchema","v","v","v","v","v","v","v","v","v","v","v","v","interners","v","v","v","interners","v","v","v","operation","operand","issue","v","v","v","refusal","v","v","v","v","v","#cache","#schema","#index","#createSchemasGetter","#buildModelSchemas","modelLabel","issue"],"sources":["../src/schema/relation/clearability.ts","../src/validation/model/core/projection.ts","../src/validation/relations/recurrence.ts","../src/validation/lazy.ts","../src/validation/model/core/orderby.ts","../src/validation/model/args/pagination.ts","../src/validation/model/args/aggregate.ts","../src/validation/model/args/omit.ts","../src/validation/model/args/select-include-exclusivity.ts","../src/validation/model/args/find.ts","../src/validation/model/args/bulk-write-projection.ts","../src/validation/model/args/mutation.ts","../src/validation/model/args/index.ts","../src/validation/model/core/create.ts","../src/validation/model/core/filter.ts","../src/validation/model/core/select.ts","../src/validation/model/core/update.ts","../src/validation/model/core/where.ts","../src/validation/model/core/index.ts","../src/validation/model/index.ts","../src/validation/relations/count-filter.ts","../src/validation/relations/nested-data-projection.ts","../src/validation/relations/to-one-mutation-schema.ts","../src/validation/relations/create.ts","../src/validation/relations/filter.ts","../src/validation/relations/order-by.ts","../src/validation/relations/select-include.ts","../src/validation/relations/to-one-update-form.ts","../src/validation/relations/update.ts","../src/validation/relations/index.ts","../src/validation/relations/polymorphic/types.ts","../src/validation/relations/polymorphic/collection-mutation.ts","../src/validation/relations/polymorphic/tagged-predicate.ts","../src/validation/relations/polymorphic/count-filter.ts","../src/validation/relations/polymorphic/create.ts","../src/validation/relations/polymorphic/create-many.ts","../src/validation/relations/polymorphic/filter.ts","../src/validation/relations/polymorphic/order-by.ts","../src/validation/relations/polymorphic/select-include.ts","../src/validation/relations/polymorphic/update.ts","../src/validation/relations/polymorphic/index.ts","../src/validation/scalars/intern.ts","../src/validation/scalars/negatable-filter.ts","../src/validation/scalars/family.ts","../src/validation/scalars/bigint.ts","../src/validation/scalars/blob.ts","../src/validation/scalars/boolean.ts","../src/validation/scalars/date.ts","../src/validation/scalars/datetime.ts","../src/validation/scalars/decimal.ts","../src/validation/scalars/enum.ts","../src/validation/scalars/int.ts","../src/validation/scalars/json.ts","../src/validation/scalars/number.ts","../src/validation/scalars/point.ts","../src/validation/scalars/string.ts","../src/validation/scalars/time.ts","../src/validation/scalars/vector.ts","../src/validation/scalars/index.ts","../src/validation/builder.ts"],"sourcesContent":["// The TWO facts about EMPTYING a relation — deliberately two.\n//\n// `slotMayBeEmpty` is the PUBLIC shape: may this relation hold nothing? It is\n// what makes `delete` spellable — deleting the related record leaves the slot\n// empty, whatever the storage looks like.\n//\n// `clearableMembership` is PHYSICAL storage: HOW the membership is cleared while\n// both records survive. That is what makes `disconnect` spellable, and it is not\n// a boolean: a junction clears by deleting its membership row, while a row\n// reference clears by nulling an exact ordered subset of its columns — a mixed\n// compound foreign key nulls its nullable members and keeps its required\n// context ones.\n//\n// Both read the RESOLVED edge. Neither rescans the graph, and neither reads a\n// declared `.optional()` flag on a model-target relation — that flag no longer\n// exists, because emptiness follows from the stored tuple's nullability.\n\nimport type { AnyModel } from \"@schema/model\";\nimport type {\n ResolvedRelationEdge,\n ResolvedSlot,\n} from \"@schema/validation/relation-resolution\";\nimport type { RelationSlot } from \"./types\";\n\n/** How a membership is emptied without deleting either record. */\nexport type ClearableMembership =\n | { readonly kind: \"none\" }\n /** Deleting the junction row clears it, whatever the inverse cardinality. */\n | { readonly kind: \"junctionRow\" }\n | {\n readonly kind: \"columns\";\n readonly fields: readonly [string, ...string[]];\n };\n\n// =============================================================================\n// FACT 1 — the public slot\n// =============================================================================\n\n/**\n * May this relation's slot be EMPTY?\n *\n * A to-many slot is empty when its collection is; a foreign-key owner when any\n * local member accepts NULL, because one absent member makes the whole\n * membership absent; a non-owner always, because the membership lives on the\n * other row and may simply be missing; a row-held variant carrier exactly when\n * it was declared `.optional()`, which IS the nullability of its private\n * `(type, id)` pair.\n */\nexport const slotMayBeEmpty = (resolved: ResolvedSlot): boolean => {\n const edge = resolved.edge;\n if (edge.kind === \"junction\" || edge.kind === \"variantJunctionCarrier\") {\n return true;\n }\n if (edge.kind === \"variantRowCarrier\") {\n return isSlot(edge.carrier, resolved.slot)\n ? edge.storage.typeColumn.nullable\n : true;\n }\n return isSlot(edge.owner, resolved.slot)\n ? nullableForeignFields(edge).length > 0\n : true;\n};\n\n// =============================================================================\n// FACT 2 — the physical membership\n// =============================================================================\n\nexport const clearableMembership = (\n resolved: ResolvedSlot\n): ClearableMembership => {\n const edge = resolved.edge;\n if (edge.kind === \"junction\" || edge.kind === \"variantJunctionCarrier\") {\n return { kind: \"junctionRow\" };\n }\n if (edge.kind === \"variantRowCarrier\") {\n return edge.storage.typeColumn.nullable\n ? {\n kind: \"columns\",\n fields: [edge.storage.typeColumn.name, edge.storage.idColumn.name],\n }\n : { kind: \"none\" };\n }\n // ONE answer per edge, asked from either end: the columns that record the\n // membership live on the owner's row, and clearing them is what \"disconnect\"\n // means from the owner slot AND from its inverse (§8.4).\n const [head, ...rest] = nullableForeignFields(edge);\n return head ? { kind: \"columns\", fields: [head, ...rest] } : { kind: \"none\" };\n};\n\n/**\n * Can the membership be cleared at all? The boolean projection of\n * {@link clearableMembership}, for callers that only decide whether to expose\n * `disconnect`.\n */\nexport const membershipCanBeCleared = (resolved: ResolvedSlot): boolean =>\n clearableMembership(resolved).kind !== \"none\";\n\n/** `(model, field)` is the whole contextual identity of a slot. */\nfunction isSlot(one: RelationSlot, other: RelationSlot): boolean {\n return one.source === other.source && one.field === other.field;\n}\n\n/** The ordered subset of the stored tuple whose scalars accept NULL. */\nfunction nullableForeignFields(\n edge: Extract<ResolvedRelationEdge, { kind: \"foreignKey\" }>\n): readonly string[] {\n const scalars: Record<string, AnyModel[\"~\"][\"state\"][\"scalars\"][string]> =\n edge.owner.source[\"~\"].state.scalars;\n return edge.reference.members\n .map((member) => member.foreignField)\n .filter((field) => scalars[field]?.[\"~\"].state.nullable === true);\n}\n","/**\n * PROJECTABLE SCALARS — the one definition of \"which scalars a query may ask\n * for\", shared by `select`, `omit`, and the default projection.\n *\n * Three layers can hide a scalar from a result. They are NOT the same kind of\n * thing, and the difference is the whole precedence story:\n *\n * 1. **Model-level `.omit()`** (`src/schema/model/model.ts`) is SCHEMA TRUTH.\n * It exists so a column like `passwordHash` can be declared once and never\n * leave the database, so it is a HARD exclusion: the field is not in the\n * `select` schema, not in the `omit` schema, and not in the result type.\n * No client option and no query argument can put it back. Asking for it is\n * an \"Unknown key\" parse failure, not a silent empty column.\n * 2. **Client-level `omit`** (`defaultOmit()({ … })`) is a DEFAULT. It\n * drops the field from projections that did not name one, and a query\n * overrides it per field with `omit: { field: false }` or by naming the\n * field in an explicit `select`.\n * 3. **Query-level `omit`** is per call, and wins over the client default.\n *\n * Only layer 1 is visible here — layers 2 and 3 are ordinary values that travel\n * in the args, and the client merges 2 into 3 before validation ever runs\n * (`resolveClientOmit`, `src/client/omit.ts`). That is deliberate: a per-client\n * default must not change what the schema ACCEPTS, or two clients over the same\n * models would disagree about which payloads are valid.\n */\n\nimport type { AnyModel } from \"@schema/model\";\nimport type { StringKeyOf } from \"@schema/model/helper\";\n\ntype ModelStateOf<M extends AnyModel> = M[\"~\"][\"state\"];\n\n/**\n * The keys a model's `.omit()` hides for good. `undefined` (the common case,\n * no `.omit()` at all) contributes nothing.\n */\nexport type ModelOmittedKeys<M extends AnyModel> =\n ModelStateOf<M>[\"omit\"] extends Record<string, true>\n ? StringKeyOf<ModelStateOf<M>[\"omit\"]>\n : never;\n\n/** Every scalar of the model that a query is allowed to project. */\nexport type ProjectableScalarKeys<M extends AnyModel> = Exclude<\n StringKeyOf<ModelStateOf<M>[\"scalars\"]>,\n ModelOmittedKeys<M>\n>;\n\n/**\n * Runtime mirror of {@link ProjectableScalarKeys}. Order follows the model's\n * declaration order, which is the order the default projection emits columns\n * in — callers depend on it for stable SELECT lists.\n */\nexport const projectableScalarNames = (model: AnyModel): string[] => {\n const state = model[\"~\"].state;\n const omitted = state.omit;\n const names = Object.keys(state.scalars);\n if (!omitted) return names;\n return names.filter(\n (name) => !Object.hasOwn(omitted, name) || omitted[name] !== true\n );\n};\n","import { type AnyModel, getModelKeyCatalog } from \"@schema/model\";\nimport type {\n StaticForeignKeyMembership,\n StaticJunctionMembership,\n StaticRecursiveMembership,\n} from \"@schema/relation/static-membership\";\nimport type { RelationState } from \"@schema/relation/types\";\nimport type { ResolvedSlot } from \"@schema/validation/relation-resolution\";\nimport { createSchema, fail, ok } from \"../primitives/helpers\";\nimport { validateInteger } from \"../primitives/number\";\nimport v, { type V } from \"../primitives/v\";\nimport type { ValidationResult, VibSchema } from \"../types\";\nimport { isRecord } from \"../value-guards\";\n\nexport interface NormalizedRecurrence {\n readonly depth: number | false;\n readonly cycles: \"reject\" | \"prevent\" | \"allow\";\n /** A projection's own output budget, when its caller set one. */\n readonly maxOccurrences?: number;\n}\n\n/**\n * How many occurrences one recursive projection decodes under one outer row\n * unless its `recurse.maxOccurrences` says otherwise. An occurrence is one\n * output row: a node reached by several paths is counted once per path, which\n * is why a graph can outgrow it with few stored rows.\n */\nexport const DEFAULT_MAX_OCCURRENCES = 10_000;\n\n/**\n * Whether an occurrence at `level` carries the repeated key — the outer slot's\n * own occurrences are level 1. It does at every level of an exhaustive\n * traversal and at every level before a numeric cutoff; at the cutoff the key\n * is absent. The decoder and the cache walker both read this one rule.\n */\nexport function carriesRepeatedKey(\n depth: number | false,\n level: number\n): boolean {\n return depth === false || level < depth;\n}\n\n/**\n * A foreign-key traversal has no cycle policy to choose: it rejects every\n * cycle it reaches. `preventCycles` is therefore refused by the bag's own type,\n * so no downstream guard has to know which topology a nested bag belongs to.\n */\ntype ForeignKeyFilterRecurse =\n | true\n | {\n readonly depth?: number | false;\n readonly preventCycles?: undefined;\n };\n\ntype GraphFilterRecurse =\n | true\n | { readonly depth?: number; readonly preventCycles?: boolean }\n | { readonly depth: false; readonly preventCycles?: true };\n\n/**\n * A projection's bag adds the output budget. A `where` filter reads the\n * closure as a set and decodes no occurrence, so it has nothing to bound and\n * refuses the key by its own type.\n */\ntype OutputBudget = { readonly maxOccurrences?: number };\n\nexport type ForeignKeyRecurse =\n | true\n | (Exclude<ForeignKeyFilterRecurse, true> & OutputBudget);\n\nexport type GraphRecurse =\n | true\n | (Exclude<GraphFilterRecurse, true> & OutputBudget);\n\nexport type ForeignKeyRecurrenceSchema = V.Schema<\n ForeignKeyRecurse,\n NormalizedRecurrence\n>;\n\nexport type GraphRecurrenceSchema = V.Schema<\n GraphRecurse,\n NormalizedRecurrence\n>;\n\nexport type RecurrenceSchema =\n | ForeignKeyRecurrenceSchema\n | GraphRecurrenceSchema;\n\ntype ForeignKeyFilterRecurrenceSchema = V.Schema<\n ForeignKeyFilterRecurse,\n NormalizedRecurrence\n>;\n\ntype GraphFilterRecurrenceSchema = V.Schema<\n GraphFilterRecurse,\n NormalizedRecurrence\n>;\n\n/** `true`, `{}` and an omitted or undefined nested `depth` mean this depth. */\nconst DEFAULT_DEPTH = 100;\nconst DEPTH_BOUNDS = Object.freeze({ minimum: 1, maximum: 1000 });\n\n// An integer inside 1..1000 is necessarily a positive safe integer.\nconst depth = Object.assign(\n createSchema<number, number>(\"integer\", (value) => {\n const integer = validateInteger(value);\n if (integer.issues) return integer;\n return integer.value >= DEPTH_BOUNDS.minimum &&\n integer.value <= DEPTH_BOUNDS.maximum\n ? ok(integer.value)\n : fail(\n \"recurse.depth must be a positive safe integer between 1 and 1000\"\n );\n }),\n DEPTH_BOUNDS\n);\n\nconst foreignKeyOptions = v.object({\n depth: v.optional(v.union([depth, v.literal(false)])),\n preventCycles: v.optional(\n v.refused(\n \"preventCycles applies only to a junction graph; a foreign-key recursion rejects every cycle it reaches\"\n )\n ),\n});\n\nconst boundedGraphOptions = v.object({\n depth: v.optional(depth),\n preventCycles: v.optional(v.boolean()),\n});\n\nconst exhaustiveGraphOptions = v.object(\n {\n depth: v.literal(false),\n preventCycles: v.optional(v.literal(true)),\n },\n { atLeast: [\"depth\"] }\n);\n\n/**\n * What a projection's bag adds to its filter twin: its own output budget\n * ({@link DEFAULT_MAX_OCCURRENCES}).\n */\nconst OUTPUT_BUDGET = {\n maxOccurrences: v.optional(\n createSchema<number, number>(\"integer\", (value) =>\n typeof value === \"number\" && Number.isSafeInteger(value) && value >= 1\n ? ok(value)\n : fail(\"recurse.maxOccurrences must be a positive safe integer\")\n )\n ),\n};\n\n/** A spelled budget travels with the bag; an unspelled one stays absent. */\nconst withBudget = (\n recurrence: Omit<NormalizedRecurrence, \"maxOccurrences\">,\n budget: number | undefined\n): NormalizedRecurrence =>\n budget === undefined ? recurrence : { ...recurrence, maxOccurrences: budget };\n\n/** The one normalization of a foreign-key bag: it rejects every cycle. */\nconst normalizeForeignKey = (options: {\n readonly depth?: number | false;\n readonly maxOccurrences?: number;\n}): NormalizedRecurrence =>\n withBudget(\n { depth: options.depth ?? DEFAULT_DEPTH, cycles: \"reject\" },\n options.maxOccurrences\n );\n\n/** The one normalization of a graph bag: prevention unless declined. */\nconst normalizeGraph = (options: {\n readonly depth?: number | false;\n readonly preventCycles?: boolean;\n readonly maxOccurrences?: number;\n}): NormalizedRecurrence =>\n withBudget(\n {\n depth: options.depth ?? DEFAULT_DEPTH,\n cycles: options.preventCycles === false ? \"allow\" : \"prevent\",\n },\n options.maxOccurrences\n );\n\n// `true` is the empty bag of its topology, by construction.\nconst TRUE_FOREIGN_KEY = v.coerce(v.literal(true), () =>\n normalizeForeignKey({})\n);\nconst TRUE_GRAPH = v.coerce(v.literal(true), () => normalizeGraph({}));\n\n/**\n * The two placements of one recurrence language. A `select`/`include` node\n * bounds what it decodes; a `where` filter reads the closure as a set, decodes\n * no occurrence, and so takes no budget.\n */\ninterface RecurrenceLanguages {\n readonly projection: {\n readonly foreignKey: ForeignKeyRecurrenceSchema;\n readonly junction: GraphRecurrenceSchema;\n };\n readonly filter: {\n readonly foreignKey: ForeignKeyFilterRecurrenceSchema;\n readonly junction: GraphFilterRecurrenceSchema;\n };\n}\n\nconst LANGUAGES: RecurrenceLanguages = {\n projection: {\n foreignKey: v.union([\n TRUE_FOREIGN_KEY,\n v.coerce(foreignKeyOptions.extend(OUTPUT_BUDGET), normalizeForeignKey),\n ]),\n junction: v.union([\n TRUE_GRAPH,\n v.coerce(\n v.union([\n boundedGraphOptions.extend(OUTPUT_BUDGET),\n exhaustiveGraphOptions.extend(OUTPUT_BUDGET),\n ]),\n normalizeGraph\n ),\n ]),\n },\n filter: {\n foreignKey: v.union([\n TRUE_FOREIGN_KEY,\n v.coerce(foreignKeyOptions, normalizeForeignKey),\n ]),\n junction: v.union([\n TRUE_GRAPH,\n v.coerce(\n v.union([boundedGraphOptions, exhaustiveGraphOptions]),\n normalizeGraph\n ),\n ]),\n },\n};\n\n/**\n * The runtime eligibility reader: the recurrence language a resolved slot\n * admits in its placement, or `undefined` when the slot cannot recurse.\n *\n * It reads three facts, each from its owner. The model's complete primary row\n * key comes from the key catalog. The edge kind comes from the resolved slot:\n * only an ordinary foreign-key or junction edge recurses, never a variant\n * carrier or an inverse bound to variant storage. Self-identity is the edge's\n * two endpoints sharing one model object, which is runtime identity rather\n * than structural agreement.\n *\n * The remaining conditions of the contract are already facts of a resolved\n * ordinary edge, so they are not asked again: only `s.toOne` declares a\n * foreign key, so a collection never owns one; the resolver publishes an\n * edge's `unique` exactly when both endpoints are singular, so a singular\n * inverse is always the proven one-to-one side; and a junction edge is\n * resolved only between two collections.\n */\nexport function recurrenceSchema(\n resolved: ResolvedSlot\n): RecurrenceSchema | undefined;\nexport function recurrenceSchema(\n resolved: ResolvedSlot,\n placement: \"filter\"\n): ForeignKeyFilterRecurrenceSchema | GraphFilterRecurrenceSchema | undefined;\nexport function recurrenceSchema(\n resolved: ResolvedSlot,\n placement: keyof RecurrenceLanguages = \"projection\"\n) {\n const { edge, slot } = resolved;\n if (edge.kind !== \"foreignKey\" && edge.kind !== \"junction\") return undefined;\n const [first, second] = edge.endpoints;\n if (first.source !== second.source) return undefined;\n if (!getModelKeyCatalog(slot.source).rowKey) return undefined;\n return LANGUAGES[placement][edge.kind];\n}\n\n/**\n * The one refusal of `recurse` on a slot that cannot recurse, shared by every\n * placement that spells the key: a `select`/`include` node and a `where`\n * relation filter.\n */\nexport const UNAVAILABLE_RECURRENCE =\n \"recurse is available only on an ordinary self relation (a foreign key or a junction, never variant storage) whose model has a complete primary key\";\n\nexport const unavailableRecurrence = () =>\n v.optional(v.refused(UNAVAILABLE_RECURRENCE));\n\nexport type UnavailableRecurrenceSchema = ReturnType<\n typeof unavailableRecurrence\n>;\n\nexport const unavailableRecursiveClause = (clause: string) =>\n v.optional(v.refused(`${clause} cannot be combined with recurse`));\n\nexport type UnavailableRecursiveClauseSchema = ReturnType<\n typeof unavailableRecursiveClause\n>;\n\n/**\n * The static eligibility reader: the recurrence language a slot admits, or\n * `never` when it cannot recurse, so a recursive form whose `recurse` is\n * required is uninhabitable there.\n */\nexport type RecurrenceFor<\n Source extends AnyModel,\n Key,\n S extends RelationState,\n Placement extends keyof RecurrenceLanguages = \"projection\",\n> = StaticRecursiveMembership<Source, Key, S> extends StaticForeignKeyMembership\n ? RecurrenceLanguages[Placement][\"foreignKey\"]\n : StaticRecursiveMembership<Source, Key, S> extends StaticJunctionMembership\n ? RecurrenceLanguages[Placement][\"junction\"]\n : never;\n\n/**\n * `recurse` and `self` are the recursive form's own words. Spelled `undefined`\n * they are unspelled, as `v.object` reads every undefined key, so a toggle\n * such as `recurse: deep ? true : undefined` meets the ordinary language\n * without them. A spelled `self` stays, for that language to refuse or to read\n * as a target field of the same name.\n */\nconst withoutUnspelledClosure = (value: unknown): unknown => {\n if (\n !(\n isRecord(value) &&\n (\"recurse\" in value || (\"self\" in value && value.self === undefined))\n )\n ) {\n return value;\n }\n const { recurse: _recurse, self, ...rest } = value;\n return self === undefined ? rest : { ...rest, self };\n};\n\n/**\n * The language of a slot that may spell `recurse`. A spelled `recurse` decides\n * the form, so it meets only the recursive member and that member's own\n * refusals, or the shared refusal where the slot has no recursive member;\n * every other value meets the ordinary language exactly as before. JSON Schema\n * still reads the ordinary alternatives and the recursive member as one union.\n */\nexport const withRecursiveNode = (\n ordinary: VibSchema<any, any> & { readonly options?: unknown },\n recursive: VibSchema<any, any> | undefined\n) => {\n const validateOrdinary = ordinary[\"~standard\"].validate;\n const validateRecursive = recursive?.[\"~standard\"].validate;\n const schema = createSchema(\"union\", (value) => {\n if (!isRecord(value) || value.recurse === undefined) {\n return validateOrdinary(\n withoutUnspelledClosure(value)\n ) as ValidationResult<unknown>;\n }\n return validateRecursive\n ? (validateRecursive(value) as ValidationResult<unknown>)\n : fail(UNAVAILABLE_RECURRENCE, [\"recurse\"]);\n });\n // A union lends its alternatives; an object's `options` are its settings,\n // never a list, so the object itself is the one alternative.\n const alternatives: readonly unknown[] = Array.isArray(ordinary.options)\n ? ordinary.options\n : [ordinary];\n return Object.assign(schema, {\n options: [...alternatives, ...(recursive ? [recursive] : [])],\n });\n};\n","// biome-ignore-all lint/complexity/noThisInStatic: Shared accessors intentionally use their dynamic instance receiver.\n/**\n * Lazy record helper for deferred schema construction.\n *\n * Builds a plain object whose properties are memoizing getters: each value is\n * constructed on first read and cached (stable identity) thereafter. Getters\n * are enumerable + configurable, so the object is indistinguishable from an\n * eagerly-built record to consumers (`key in obj`, `Object.keys`, single-key\n * access all behave identically) — the only difference is that a builder that\n * is never read never runs.\n *\n * Used to make model schema construction pay-per-use: a `findUnique` request\n * only builds the whereUnique/select/include schemas it touches, never the\n * create/update/aggregate trees — a large saving on the cold (first-query)\n * path per serverless isolate.\n */\nexport function lazyRecord<T extends object>(\n builders: {\n [K in keyof T]: () => T[K];\n }\n): T {\n const target = {} as T;\n for (const key of Object.keys(builders) as (keyof T)[]) {\n let build: (() => T[keyof T]) | undefined = builders[key];\n let value: T[keyof T];\n Object.defineProperty(target, key, {\n enumerable: true,\n configurable: true,\n get() {\n if (build) {\n value = build();\n build = undefined;\n }\n return value;\n },\n });\n }\n return target;\n}\n\n/**\n * The four variants every scalar field owns.\n *\n * Named for the VARIANTS of one field, not for a model's scalars: the barrel\n * already exports a `ScalarSchemas` from `./model`, which is the scalar schemas\n * of a whole model. The two constrain unrelated shapes, so one name for both\n * would be a duplicate export the day this module joins the barrel, and an\n * auto-import that typechecks by accident until then.\n */\nexport type ScalarVariantSchemas = {\n readonly base: unknown;\n readonly create: unknown;\n readonly update: unknown;\n readonly filter: unknown;\n};\n\ntype ScalarSchemaBuilders<T extends ScalarVariantSchemas> = {\n readonly base: T[\"base\"];\n readonly create: () => T[\"create\"];\n readonly update: () => T[\"update\"];\n readonly filter: () => T[\"filter\"];\n};\n\ntype ScalarSchemaRecord<T extends ScalarVariantSchemas> = Pick<\n T,\n \"base\" | \"create\" | \"update\" | \"filter\"\n>;\n\ntype LazyState<T> = { build: () => T } | { value: T };\n\n/**\n * Compact lazy storage for the four variants owned by every scalar field.\n *\n * The enumerable accessors reuse shared getter functions instead of allocating\n * a closure per property and field. Each resolved variant drops its factory\n * while unresolved siblings remain lazy.\n */\nclass LazyScalarSchemas<T extends ScalarVariantSchemas>\n implements ScalarSchemaRecord<T>\n{\n readonly base: T[\"base\"];\n declare readonly create: T[\"create\"];\n declare readonly update: T[\"update\"];\n declare readonly filter: T[\"filter\"];\n #create: LazyState<T[\"create\"]>;\n #update: LazyState<T[\"update\"]>;\n #filter: LazyState<T[\"filter\"]>;\n\n constructor(builders: ScalarSchemaBuilders<T>) {\n this.base = builders.base;\n this.#create = { build: builders.create };\n this.#update = { build: builders.update };\n this.#filter = { build: builders.filter };\n Object.defineProperties(this, {\n create: {\n enumerable: true,\n configurable: true,\n get: LazyScalarSchemas.#readCreate,\n },\n update: {\n enumerable: true,\n configurable: true,\n get: LazyScalarSchemas.#readUpdate,\n },\n filter: {\n enumerable: true,\n configurable: true,\n get: LazyScalarSchemas.#readFilter,\n },\n });\n }\n\n static #readCreate<T extends ScalarVariantSchemas>(\n this: LazyScalarSchemas<T>\n ): T[\"create\"] {\n if (\"value\" in this.#create) return this.#create.value;\n const value = this.#create.build();\n this.#create = { value };\n return value;\n }\n\n static #readUpdate<T extends ScalarVariantSchemas>(\n this: LazyScalarSchemas<T>\n ): T[\"update\"] {\n if (\"value\" in this.#update) return this.#update.value;\n const value = this.#update.build();\n this.#update = { value };\n return value;\n }\n\n static #readFilter<T extends ScalarVariantSchemas>(\n this: LazyScalarSchemas<T>\n ): T[\"filter\"] {\n if (\"value\" in this.#filter) return this.#filter.value;\n const value = this.#filter.build();\n this.#filter = { value };\n return value;\n }\n}\n\nexport function lazyScalarSchemas<T extends ScalarVariantSchemas>(\n builders: ScalarSchemaBuilders<T>\n): ScalarSchemaRecord<T> {\n return new LazyScalarSchemas(builders);\n}\n","import type { AnyModel } from \"@schema/model\";\nimport type { DecimalListScalarKeys, StringKeyOf } from \"@schema/model/helper\";\nimport type { ScalarState } from \"@schema/scalars\";\nimport { entriesFromObject } from \"../../primitives/from-object\";\nimport { entriesFromKeys } from \"../../primitives/record\";\nimport v, { type V } from \"../../primitives/v\";\nimport type { VibSchema } from \"../../types\";\nimport type { ScalarSchemas } from \"../index\";\n\nconst orderEnum = v.enum([\"asc\", \"desc\"]);\nconst vectorDistanceMetricSchema = v.enum([\"l2\", \"cosine\"]);\nconst forbiddenOrderByKeySchema = (key: string): VibSchema<never, never> =>\n v.refused(`OrderBy key '${key}' is not valid here.`);\n\nexport const sortOrderSchema = v.union([\n orderEnum,\n v.object(\n {\n sort: orderEnum,\n nulls: v.enum([\"first\", \"last\"]),\n _distance: forbiddenOrderByKeySchema(\"_distance\"),\n },\n { atLeast: [\"sort\"] }\n ),\n]);\nexport type SortOrderSchema = typeof sortOrderSchema;\n\nexport const vectorDistanceOrderSchema = v.object(\n {\n _distance: v.object(\n {\n to: v.array(v.number()),\n metric: vectorDistanceMetricSchema,\n sort: orderEnum,\n },\n { atLeast: [\"to\", \"metric\"] }\n ),\n sort: forbiddenOrderByKeySchema(\"sort\"),\n nulls: forbiddenOrderByKeySchema(\"nulls\"),\n },\n { atLeast: [\"_distance\"] }\n);\n\nexport const pointDistanceOrderSchema = v.object(\n {\n _distance: v.object(\n {\n to: v.point(),\n sort: orderEnum,\n },\n { partial: false }\n ),\n sort: forbiddenOrderByKeySchema(\"sort\"),\n nulls: forbiddenOrderByKeySchema(\"nulls\"),\n },\n { atLeast: [\"_distance\"] }\n);\nexport type PointDistanceOrderSchema = typeof pointDistanceOrderSchema;\n\nexport const vectorSortOrderSchema = v.union([\n sortOrderSchema,\n vectorDistanceOrderSchema,\n]);\nexport type VectorSortOrderSchema = typeof vectorSortOrderSchema;\n\n/**\n * Build orderBy schema - sort direction for each scalar field and nested relation ordering\n */\ntype ModelStateOf<M extends AnyModel> = M[\"~\"][\"state\"];\ntype ModelScalars<M extends AnyModel> = ModelStateOf<M>[\"scalars\"];\ntype ModelScalarKey<M extends AnyModel> = StringKeyOf<ModelScalars<M>>;\ntype ScalarStateOf<F> = F extends { \"~\": { state: infer S } }\n ? S extends ScalarState\n ? S\n : never\n : never;\ntype ModelDecimalListScalarKeys<M extends AnyModel> = Extract<\n DecimalListScalarKeys<ModelScalars<M>>,\n ModelScalarKey<M>\n>;\nexport type OrderableScalarKeys<M extends AnyModel> = Exclude<\n ModelScalarKey<M>,\n ModelDecimalListScalarKeys<M> | PointScalarKeys<M>\n>;\ntype VectorScalarKeys<M extends AnyModel> = {\n [K in keyof ModelScalars<M>]: ScalarStateOf<\n ModelScalars<M>[K]\n >[\"type\"] extends \"vector\"\n ? K extends string\n ? K\n : never\n : never;\n}[keyof ModelScalars<M>];\ntype PointScalarKeys<M extends AnyModel> = {\n [K in keyof ModelScalars<M>]: ScalarStateOf<\n ModelScalars<M>[K]\n >[\"type\"] extends \"point\"\n ? K extends string\n ? K\n : never\n : never;\n}[keyof ModelScalars<M>];\ntype NonVectorScalarKeys<M extends AnyModel> = Exclude<\n OrderableScalarKeys<M>,\n VectorScalarKeys<M>\n>;\n\n/** A decimal list has equality semantics, but no portable numeric ordering. */\nexport const isOrderableScalarState = (state: ScalarState): boolean =>\n state.type !== \"point\" && (state.type !== \"decimal\" || state.array !== true);\n\nexport const decimalListOrderByRefusalSchema = v.refused(\n \"A decimal list cannot be used for numeric ordering.\"\n);\nexport type DecimalListOrderByRefusalSchema =\n typeof decimalListOrderByRefusalSchema;\n\nexport function isDecimalListScalarKey<M extends AnyModel>(\n model: M,\n fieldName: ModelScalarKey<M>\n): fieldName is ModelDecimalListScalarKeys<M> {\n const state = model[\"~\"].state.scalars[fieldName][\"~\"].state;\n return state.type === \"decimal\" && state.array === true;\n}\n\n/**\n * A polymorphic slot is orderable exactly as far as its cardinality allows: a\n * COLLECTION offers `{ _count }` like any list relation, a to-one slot offers a\n * named refusal (there is no single column to sort by when the target model is\n * chosen per row). Both entries exist, because the family key set is identical\n * across cardinalities — see `relations/polymorphic/index.ts` for why.\n */\nexport type OrderBySchema<\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n> = V.Object<\n V.FromKeys<NonVectorScalarKeys<M>[], SortOrderSchema>[\"entries\"] &\n V.FromKeys<VectorScalarKeys<M>[], VectorSortOrderSchema>[\"entries\"] &\n V.FromKeys<PointScalarKeys<M>[], PointDistanceOrderSchema>[\"entries\"] &\n V.FromKeys<\n ModelDecimalListScalarKeys<M>[],\n DecimalListOrderByRefusalSchema\n >[\"entries\"] &\n V.FromObject<F[\"relations\"], \"orderBy\">[\"entries\"] &\n V.FromObject<F[\"polymorphic\"], \"orderBy\">[\"entries\"]\n>;\nexport const getOrderBySchema = <\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n>(\n model: M,\n fieldSchemas: F\n): OrderBySchema<M, F> => {\n const vectorScalarKeys: VectorScalarKeys<M>[] = [];\n const pointScalarKeys: PointScalarKeys<M>[] = [];\n const nonVectorScalarKeys: NonVectorScalarKeys<M>[] = [];\n const decimalListScalarKeys: ModelDecimalListScalarKeys<M>[] = [];\n\n const scalarKeys = Object.keys(\n model[\"~\"].state.scalars\n ) as ModelScalarKey<M>[];\n\n for (const fieldName of scalarKeys) {\n if (isDecimalListScalarKey(model, fieldName)) {\n decimalListScalarKeys.push(fieldName);\n continue;\n }\n const scalar = model[\"~\"].state.scalars[fieldName];\n const state = scalar[\"~\"].state;\n if (state.type === \"vector\") {\n vectorScalarKeys.push(fieldName as VectorScalarKeys<M>);\n continue;\n }\n if (state.type === \"point\") {\n pointScalarKeys.push(fieldName as PointScalarKeys<M>);\n continue;\n }\n nonVectorScalarKeys.push(fieldName as NonVectorScalarKeys<M>);\n }\n\n const scalarEntries = entriesFromKeys<\n NonVectorScalarKeys<M>[],\n typeof sortOrderSchema\n >(nonVectorScalarKeys, sortOrderSchema);\n const vectorEntries = entriesFromKeys<\n VectorScalarKeys<M>[],\n typeof vectorSortOrderSchema\n >(vectorScalarKeys, vectorSortOrderSchema);\n const pointEntries = entriesFromKeys<\n PointScalarKeys<M>[],\n PointDistanceOrderSchema\n >(pointScalarKeys, pointDistanceOrderSchema);\n const decimalListEntries = entriesFromKeys<\n ModelDecimalListScalarKeys<M>[],\n DecimalListOrderByRefusalSchema\n >(decimalListScalarKeys, decimalListOrderByRefusalSchema);\n\n const relationEntries = entriesFromObject<F[\"relations\"], \"orderBy\">(\n fieldSchemas.relations,\n \"orderBy\"\n );\n const polymorphicEntries = entriesFromObject<F[\"polymorphic\"], \"orderBy\">(\n fieldSchemas.polymorphic,\n \"orderBy\"\n );\n\n const schema = v.object({\n ...scalarEntries,\n ...vectorEntries,\n ...pointEntries,\n ...decimalListEntries,\n ...relationEntries,\n ...polymorphicEntries,\n });\n // This fresh model-owned object retains entries/extend; only its validation\n // closes the unsupported expression boundary before enum/union matching.\n const closed = v.noOperandExpression(schema, \"'orderBy'\");\n Reflect.set(schema[\"~standard\"], \"validate\", closed[\"~standard\"].validate);\n return schema;\n};\n","import { createSchema, fail } from \"../../primitives/helpers\";\nimport { validateInteger } from \"../../primitives/number\";\nimport v, { type V } from \"../../primitives/v\";\n\nexport type PaginationTakeSchema = V.Integer;\nexport type PaginationSkipSchema = V.Schema<number, number>;\n\nexport const paginationTake = (): PaginationTakeSchema => v.integer();\n\nfunction nonNegativeInteger(message: string): V.Schema<number, number> {\n return createSchema<number, number>(\"integer\", (value) => {\n const result = validateInteger(value);\n if (result.issues) return result;\n return result.value < 0 ? fail(message) : result;\n });\n}\n\nexport const paginationSkip = (): PaginationSkipSchema =>\n nonNegativeInteger(\"skip must be greater than or equal to 0\");\n\nexport type BulkWriteLimitSchema = V.Schema<number, number>;\n\n/**\n * `limit` on `updateMany` / `deleteMany` (Prisma 6.x): a cap on how MANY rows\n * the bulk write may affect, taken first by primary key. Non-negative — unlike\n * `take`, a negative value has no \"from the other end\" meaning here, because a\n * bulk write has no `orderBy` to reverse. `0` is legal and means \"affect\n * nothing\".\n */\nexport const bulkWriteLimit = (): BulkWriteLimitSchema =>\n nonNegativeInteger(\"limit must be greater than or equal to 0\");\n","// Aggregate operation args schema factories\n\nimport type { AnyModel } from \"@schema/model\";\nimport type {\n DecimalListScalarKeys,\n NonPointScalarKeys,\n NumericScalarKeys,\n PointScalarKeys,\n ScalarKeys,\n} from \"@schema/model/helper\";\nimport type { ScalarState } from \"@schema/scalars/common\";\nimport type { DecimalDescriptor } from \"@validation/primitives/decimal-codec\";\nimport { scopeOperands } from \"@validation/primitives/operand\";\nimport v, { type V } from \"../../primitives/v\";\nimport type {\n InferInput,\n InferOutput,\n ValidationIssue,\n VibSchema,\n} from \"../../types\";\nimport { isRecord } from \"../../value-guards\";\nimport type { CoreSchemas } from \"../core\";\nimport {\n type DecimalListOrderByRefusalSchema,\n decimalListOrderByRefusalSchema,\n isOrderableScalarState,\n type OrderableScalarKeys,\n type SortOrderSchema,\n sortOrderSchema,\n} from \"../core/orderby\";\nimport type { ScalarSchemas } from \"../index\";\nimport {\n type PaginationSkipSchema,\n type PaginationTakeSchema,\n paginationSkip,\n paginationTake,\n} from \"./pagination\";\n\n// =============================================================================\n// AGGREGATE SCALAR SCHEMAS\n// =============================================================================\n\n/**\n * Build aggregate scalar schemas (for _count, _avg, _sum, _min, _max)\n * Following Prisma's API:\n * - _count: can be `true` or object with `_all` + all scalar names\n * - _avg, _sum: only numeric scalars (int, number, decimal, bigint)\n * - _min, _max: scalar columns, never list containers\n */\ntype OptionalBoolean = V.Boolean<{ optional: true }>;\ntype AggregateValueRefusalSchema = VibSchema<never, never>;\n\nconst SUMMABLE_SCALAR_TYPES = [\"int\", \"number\", \"decimal\", \"bigint\"];\n\n/**\n * Whether `_sum` and `_avg` mean anything for this scalar.\n *\n * Numeric KIND is not enough on its own: a `s.decimal({...}).array()` is a\n * container — one JSON document per row on every provider that has one at all —\n * and there is no column-wide addition of documents to ask for. Plan 5.3 names\n * the shape: \"the current aggregate/order builders must exclude list states\n * rather than sorting JSON or admitting `_sum` by scalar kind alone\". Admitting\n * it by kind is what left a decimal list offering `_sum` with a `v.number()`\n * operand — the one operand shape this scalar exists to remove.\n *\n * `_count` remains available because a count of non-null containers is a row\n * count like any other. Value aggregates never order or combine list\n * containers.\n */\nconst isSummableScalar = (state: ScalarState): boolean =>\n state.array !== true && SUMMABLE_SCALAR_TYPES.includes(state.type);\n\n/**\n * Count keys include \"_all\" plus all scalar names\n */\ntype ModelStateOf<M extends AnyModel> = M[\"~\"][\"state\"];\n\ntype AggregateScalarKeys<M extends AnyModel> = Exclude<\n NonPointScalarKeys<ModelStateOf<M>[\"scalars\"]>,\n ListScalarKeys<M>\n>;\n\nexport type CountScalarKeys<M extends AnyModel> =\n | \"_all\"\n | ScalarKeys<ModelStateOf<M>[\"scalars\"]>;\n\ntype ListAggregateEntries<M extends AnyModel> = V.FromKeys<\n ListScalarKeys<M>[],\n AggregateValueRefusalSchema\n>[\"entries\"];\n\ntype PointAggregateEntries<M extends AnyModel> = V.FromKeys<\n PointScalarKeys<ModelStateOf<M>[\"scalars\"]>[],\n AggregateValueRefusalSchema\n>[\"entries\"];\n\ntype AggregateValueSchema<M extends AnyModel, K extends string> = V.Object<\n V.FromKeys<K[], OptionalBoolean>[\"entries\"] &\n ListAggregateEntries<M> &\n PointAggregateEntries<M>\n>;\n\n/**\n * Aggregate scalar schemas with proper typing\n */\nexport type AggregateScalarSchemas<M extends AnyModel> = {\n /** Count can include _all and any scalar */\n count: V.FromKeys<CountScalarKeys<M>[], OptionalBoolean>;\n /** Avg only works on numeric scalars */\n avg: AggregateValueSchema<M, NumericScalarKeys<ModelStateOf<M>[\"scalars\"]>>;\n /** Sum only works on numeric scalars */\n sum: AggregateValueSchema<M, NumericScalarKeys<ModelStateOf<M>[\"scalars\"]>>;\n /** Min works on scalar columns, not list containers */\n min: AggregateValueSchema<M, AggregateScalarKeys<M>>;\n /** Max works on scalar columns, not list containers */\n max: AggregateValueSchema<M, AggregateScalarKeys<M>>;\n};\n\nexport const getAggregateScalarSchemas = <M extends AnyModel>(\n model: M\n): AggregateScalarSchemas<M> => {\n const state = model[\"~\"].state;\n const countKeys: string[] = [\"_all\"];\n const numericKeys: string[] = [];\n const minMaxKeys: string[] = [];\n const listKeys: string[] = [];\n const pointKeys: string[] = [];\n\n for (const name of Object.keys(state.scalars)) {\n const scalar = state.scalars[name]!;\n\n // Count can include all scalars\n countKeys.push(name);\n\n // Avg/Sum only for numeric types\n if (isSummableScalar(scalar[\"~\"].state)) {\n numericKeys.push(name);\n }\n\n // Value aggregates never compare list containers.\n if (\n scalar[\"~\"].state.array !== true &&\n scalar[\"~\"].state.type !== \"point\"\n ) {\n minMaxKeys.push(name);\n }\n if (scalar[\"~\"].state.array === true) listKeys.push(name);\n if (scalar[\"~\"].state.type === \"point\") pointKeys.push(name);\n }\n\n const booleanOptional = v.boolean({ optional: true });\n const projection = (aggregate: \"_avg\" | \"_sum\" | \"_min\" | \"_max\") =>\n v.fromKeys(\n listKeys,\n v.refused(\n `A list cannot be projected by '${aggregate}'; only '_count' is supported.`\n )\n );\n const pointProjection = (aggregate: \"_avg\" | \"_sum\" | \"_min\" | \"_max\") =>\n v.fromKeys(\n pointKeys,\n v.refused(\n `A GeoPoint cannot be projected by '${aggregate}'; use a distance projection or '_count'.`\n )\n );\n\n return {\n count: v.fromKeys(countKeys, booleanOptional),\n avg: v.object({\n ...v.fromKeys(numericKeys, booleanOptional).entries,\n ...projection(\"_avg\").entries,\n ...pointProjection(\"_avg\").entries,\n }),\n sum: v.object({\n ...v.fromKeys(numericKeys, booleanOptional).entries,\n ...projection(\"_sum\").entries,\n ...pointProjection(\"_sum\").entries,\n }),\n min: v.object({\n ...v.fromKeys(minMaxKeys, booleanOptional).entries,\n ...projection(\"_min\").entries,\n ...pointProjection(\"_min\").entries,\n }),\n max: v.object({\n ...v.fromKeys(minMaxKeys, booleanOptional).entries,\n ...projection(\"_max\").entries,\n ...pointProjection(\"_max\").entries,\n }),\n } as AggregateScalarSchemas<M>;\n};\n\n// =============================================================================\n// COUNT ARGS\n// =============================================================================\n\n/**\n * Count args following Prisma's API:\n * - where: filter records before counting\n * - orderBy: order records before cursor/take/skip pagination\n * - cursor: cursor-based pagination\n * - take: limit number of records\n * - skip: skip number of records\n * - select: which scalars to count (including _all for total count)\n */\nexport type CountArgs<\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n> = V.Object<\n {\n where: CoreSchemas<M, F>[\"where\"];\n orderBy: V.Union<\n readonly [\n CoreSchemas<M, F>[\"orderBy\"],\n V.Array<CoreSchemas<M, F>[\"orderBy\"]>,\n ]\n >;\n cursor: CoreSchemas<M, F>[\"whereUnique\"];\n take: PaginationTakeSchema;\n skip: PaginationSkipSchema;\n select: AggregateScalarSchemas<M>[\"count\"];\n },\n { optional: true }\n>;\n\nexport const getCountArgs = <M extends AnyModel, F extends ScalarSchemas<M>>(\n model: M,\n core: CoreSchemas<M, F>\n): CountArgs<M, F> => {\n const aggSchemas = getAggregateScalarSchemas(model);\n\n return v.object(\n {\n where: v.lazyRef(() => core.where),\n orderBy: v.lazyRef(() => v.union([core.orderBy, v.array(core.orderBy)])),\n cursor: v.lazyRef(() => core.whereUnique),\n take: paginationTake(),\n skip: paginationSkip(),\n select: aggSchemas.count,\n },\n { optional: true }\n ) as CountArgs<M, F>;\n};\n\n// =============================================================================\n// EXIST ARGS\n// =============================================================================\n\n/** Existence asks only whether any row matches one optional filter. */\nexport type ExistArgs<\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n> = V.Object<{ where: CoreSchemas<M, F>[\"where\"] }, { optional: true }>;\n\nexport const getExistArgs = <M extends AnyModel, F extends ScalarSchemas<M>>(\n core: CoreSchemas<M, F>\n): ExistArgs<M, F> =>\n v.object(\n {\n where: v.lazyRef(() => core.where),\n },\n { optional: true }\n );\n\n// =============================================================================\n// AGGREGATE ARGS\n// =============================================================================\n\n/**\n * Aggregate args: { where?, orderBy?, cursor?, take?, skip?, _count?, _avg?, _sum?, _min?, _max? }\n */\n\nexport type AggregateArgs<\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n> = V.Object<{\n where: CoreSchemas<M, F>[\"where\"];\n orderBy: V.Union<\n readonly [\n CoreSchemas<M, F>[\"orderBy\"],\n V.Array<CoreSchemas<M, F>[\"orderBy\"]>,\n ]\n >;\n cursor: CoreSchemas<M, F>[\"whereUnique\"];\n take: PaginationTakeSchema;\n skip: PaginationSkipSchema;\n _count: V.Union<\n readonly [V.Literal<true>, AggregateScalarSchemas<M>[\"count\"]]\n >;\n _avg: AggregateScalarSchemas<M>[\"avg\"];\n _sum: AggregateScalarSchemas<M>[\"sum\"];\n _min: AggregateScalarSchemas<M>[\"min\"];\n _max: AggregateScalarSchemas<M>[\"max\"];\n}>;\nexport const getAggregateArgs = <\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n C extends CoreSchemas<M, F> = CoreSchemas<M, F>,\n>(\n model: M,\n core: C\n): AggregateArgs<M, F> => {\n const aggSchemas = getAggregateScalarSchemas(model);\n\n return v.object({\n where: v.lazyRef(() => core.where),\n orderBy: v.lazyRef(() => v.union([core.orderBy, v.array(core.orderBy)])),\n cursor: v.lazyRef(() => core.whereUnique),\n take: paginationTake(),\n skip: paginationSkip(),\n _count: v.union([v.literal(true), aggSchemas.count]),\n _avg: aggSchemas.avg,\n _sum: aggSchemas.sum,\n _min: aggSchemas.min,\n _max: aggSchemas.max,\n }) as AggregateArgs<M, F>;\n};\n\n// =============================================================================\n// GROUP BY HAVING SCHEMA\n// =============================================================================\n\n/**\n * Having schema for groupBy follows Prisma's pattern.\n *\n * Allows filtering on:\n * - Direct scalar filters (for scalars in `by`): { country: \"USA\" } / { country: { in: [\"USA\", \"UK\"] } }\n * - Aggregate values: { profileViews: { _avg: { gt: 100 } }, id: { _count: { gte: 5 } } }\n *\n * For each scalar key, we accept either:\n * - the scalar's regular filter schema (same as WHERE), OR\n * - an aggregate filter object with _count/_avg/_sum/_min/_max.\n */\n/**\n * One aggregate's comparison operators, over whatever operand the aggregate\n * answers in. `equals`/`not` accept null so aggregates over all-null groups\n * (e.g. `_min`) can be filtered with IS NULL / IS NOT NULL semantics.\n */\ntype AggregateFilterOps<O extends V.Schema, N extends V.Schema> = V.Object<\n {\n equals: N;\n in: V.Array<O>;\n notIn: V.Array<O>;\n gt: O;\n gte: O;\n lt: O;\n lte: O;\n not: N;\n },\n { optional: true }\n>;\n\ntype NumericFilterOps = AggregateFilterOps<\n V.Number,\n V.Number<{\n nullable: true;\n }>\n>;\n\ntype AggregateNullFilter = V.Object<\n { equals: V.Literal<null>; not: V.Literal<null> },\n { optional: true }\n>;\n\n/**\n * A decimal aggregate's operands are DECIMALS, not doubles.\n *\n * `having: { amount: { _sum: { gt: x } } }` compares against a value the\n * database computed exactly; typing `x` as a JavaScript number puts the\n * comparison back through 53 bits of mantissa, which is the one thing this\n * scalar exists to avoid. The descriptor each operand is validated against is a\n * runtime fact (the field's own, widened for `_sum`); at the type level a\n * decimal operand is the same accepted family everywhere.\n */\ntype DecimalFilterOps = AggregateFilterOps<\n V.Decimal,\n V.Decimal<{\n nullable: true;\n }>\n>;\n\n/**\n * `_count` is a ROW COUNT on every scalar — an integer that has nothing to do\n * with the column's domain — so it keeps the numeric operand while the four\n * value aggregates take the column's own.\n */\nexport type HavingAggregateScalarSchema<\n Ops extends V.Schema = NumericFilterOps,\n ValueOps extends V.Schema = Ops,\n> = V.Object<\n {\n _count: NumericFilterOps;\n _avg: Ops;\n _sum: Ops;\n _min: ValueOps;\n _max: ValueOps;\n },\n { optional: true }\n>;\n\ntype ListHavingAggregateScalarSchema = V.Object<\n {\n _count: NumericFilterOps;\n _avg: AggregateValueRefusalSchema;\n _sum: AggregateValueRefusalSchema;\n _min: AggregateValueRefusalSchema;\n _max: AggregateValueRefusalSchema;\n },\n { optional: true }\n>;\n\ntype ListScalarKeys<M extends AnyModel> = {\n [K in keyof ModelStateOf<M>[\"scalars\"]]: ModelStateOf<M>[\"scalars\"][K] extends {\n \"~\": { state: { array: true } };\n }\n ? K\n : never;\n}[keyof ModelStateOf<M>[\"scalars\"]] &\n string;\n\n/** The scalar keys of `M` whose declared type is `decimal`. */\ntype DecimalScalarKeys<M extends AnyModel> = {\n [K in keyof ModelStateOf<M>[\"scalars\"]]: ModelStateOf<M>[\"scalars\"][K] extends {\n \"~\": { state: { type: \"decimal\" } };\n }\n ? K\n : never;\n}[keyof ModelStateOf<M>[\"scalars\"]];\n\ntype HavingAggregateOf<\n M extends AnyModel,\n K,\n S extends V.Schema,\n> = K extends DecimalScalarKeys<M>\n ? HavingAggregateScalarSchema<DecimalFilterOps>\n : HavingAggregateScalarSchema<\n K extends NumericScalarKeys<ModelStateOf<M>[\"scalars\"]>\n ? NumericFilterOps\n : AggregateValueRefusalSchema,\n V.Union<readonly [S, AggregateNullFilter]>\n >;\n\ntype ScalarFilterBundle = {\n scalars: Record<string, { filter: V.Schema }>;\n};\n\ntype ScalarFilterEntries<F extends ScalarFilterBundle> = V.FromObject<\n F[\"scalars\"],\n \"filter\"\n>[\"entries\"];\n\n/**\n * A list has one having object arm. Its shorthand array stays untouched; its\n * filter-object member receives the aggregate entries directly. A separate\n * union arm would let a forbidden aggregate key escape beside a real filter\n * key from the other arm.\n */\ntype WithListHavingAggregates<Value, Aggregates> =\n Value extends readonly unknown[]\n ? Value\n : Value extends object\n ? Value & Aggregates\n : Value;\n\ntype ListHavingFilterSchema<S extends V.Schema> = VibSchema<\n WithListHavingAggregates<\n InferInput<S>,\n InferInput<ListHavingAggregateScalarSchema>\n >,\n WithListHavingAggregates<\n InferOutput<S>,\n InferOutput<ListHavingAggregateScalarSchema>\n >\n>;\n\ntype HavingScalarSchema<\n M extends AnyModel,\n K,\n S extends V.Schema,\n> = K extends ListScalarKeys<M>\n ? ListHavingFilterSchema<S>\n : V.Union<readonly [HavingAggregateOf<M, K, S>, S]>;\n\nexport type HavingSchemaEntries<\n M extends AnyModel,\n F extends ScalarFilterBundle,\n> = {\n [K in keyof ScalarFilterEntries<F>]: K extends PointScalarKeys<\n ModelStateOf<M>[\"scalars\"]\n >\n ? AggregateValueRefusalSchema\n : ScalarFilterEntries<F>[K] extends infer S extends V.Schema\n ? HavingScalarSchema<M, K, S>\n : never;\n};\n\n/**\n * Boolean combinators, mirroring Prisma's `<Model>ScalarWhereWithAggregatesInput`\n * and viborm's own `WhereSchema`: `AND`/`NOT` take an object or an array, `OR`\n * takes an array. Thunks defer the self-reference (same recursion device the\n * where schema uses).\n */\nexport type HavingLogicalEntries<\n M extends AnyModel,\n F extends ScalarFilterBundle,\n> = {\n AND: () => V.Optional<\n V.Union<readonly [HavingSchema<M, F>, V.Array<HavingSchema<M, F>>]>\n >;\n OR: () => V.Optional<V.Array<HavingSchema<M, F>>>;\n NOT: () => V.Optional<\n V.Union<readonly [HavingSchema<M, F>, V.Array<HavingSchema<M, F>>]>\n >;\n};\n\nexport type HavingSchema<\n M extends AnyModel,\n F extends ScalarFilterBundle,\n> = V.Object<\n HavingLogicalEntries<M, F> & HavingSchemaEntries<M, F>,\n { optional: true }\n>;\n\nconst buildAggregateFilterOps = (\n operand: () => V.Schema,\n nullableOperand: () => V.Schema\n) =>\n v.object(\n {\n // equals/not accept null so aggregates over all-null groups (e.g. _min)\n // can be filtered with IS NULL / IS NOT NULL semantics\n equals: nullableOperand(),\n in: v.array(operand()),\n notIn: v.array(operand()),\n gt: operand(),\n gte: operand(),\n lt: operand(),\n lte: operand(),\n not: nullableOperand(),\n },\n { optional: true }\n );\n\nconst numericFilterOps = buildAggregateFilterOps(\n () => v.number(),\n () => v.number({ nullable: true })\n);\n\nconst aggregateNullFilter = v.object(\n { equals: v.literal(null), not: v.literal(null) },\n { optional: true }\n);\n\ntype RuntimeListFilterSchema = V.Union<\n readonly [V.Schema, V.Object<Record<string, V.Schema>>]\n>;\n\nconst isRuntimeListFilterSchema = (\n schema: V.Schema\n): schema is RuntimeListFilterSchema => {\n if (schema.type !== \"union\") return false;\n const options = Reflect.get(schema, \"options\");\n if (!Array.isArray(options) || options.length !== 2) return false;\n const filter = options[1];\n return (\n typeof filter === \"object\" &&\n filter !== null &&\n Reflect.get(filter, \"type\") === \"object\"\n );\n};\n\nconst listHavingSchema = (filter: V.Schema): V.Schema => {\n const refusal = (aggregate: \"_avg\" | \"_sum\" | \"_min\" | \"_max\") =>\n v.refused(\n `A list cannot use '${aggregate}' in having; only '_count' is supported.`\n );\n const aggregateEntries = {\n _count: numericFilterOps,\n _avg: refusal(\"_avg\"),\n _sum: refusal(\"_sum\"),\n _min: refusal(\"_min\"),\n _max: refusal(\"_max\"),\n };\n\n if (!isRuntimeListFilterSchema(filter)) {\n return v.refused(\n \"The list filter schema cannot be used in having because its trusted shape is unavailable.\"\n );\n }\n\n return v.noOperandExpression(\n v.union([filter.options[0], filter.options[1].extend(aggregateEntries)]),\n \"'having'\"\n );\n};\n\n/**\n * The domain a `_sum` operand is VALIDATED in: the field's SCALE and the\n * definition grammar's widest legal precision.\n *\n * A sum of a `precision: 10` column over a million rows is a legitimate answer\n * sixteen digits wide, so an operand compared against it cannot be held to one\n * row's precision — that is the plan's \"`_sum` is not incorrectly rejected for\n * exceeding the field's storage precision\", asked from the operand side. The\n * scale is NOT widened: every summed value carries the field's scale, so an\n * operand at a different one is a different number on a coefficient dialect.\n *\n * Provider-independent HERE and provider-bounded at the bind, deliberately:\n * which provider this model will be bound to is not knowable when its schemas\n * are built, and the practical ceiling is a provider fact. This descriptor\n * still obeys the one public descriptor invariant; the tighter domain — and\n * the refusal for an operand past it — has one owner,\n * the adapter's aggregate operand admission, reached by the query engine with\n * the exact coefficient in hand. This states the shape of the operand; that\n * states what a database can answer about.\n */\nconst sumOperandDomain = (\n descriptor: DecimalDescriptor\n): DecimalDescriptor => ({\n precision: Number.MAX_SAFE_INTEGER,\n scale: descriptor.scale,\n});\n\n/**\n * The aggregate filter object for ONE scalar, in that scalar's own domain.\n *\n * Min/max keep the field's filter domain. Numeric aggregates use their result\n * domain, including the widened exact decimal domain for sums.\n */\nconst havingAggregateSchema = (\n state: ScalarState | undefined,\n filter: V.Schema\n) => {\n const descriptor = state?.type === \"decimal\" ? state.decimal : undefined;\n if (!descriptor) {\n return v.object(\n {\n _count: numericFilterOps,\n _avg:\n state && isSummableScalar(state)\n ? numericFilterOps\n : v.refused(\"Only numeric scalars support '_avg' in having.\"),\n _sum:\n state && isSummableScalar(state)\n ? numericFilterOps\n : v.refused(\"Only numeric scalars support '_sum' in having.\"),\n _min: v.union([filter, aggregateNullFilter]),\n _max: v.union([filter, aggregateNullFilter]),\n },\n { optional: true }\n );\n }\n const fieldOps = buildAggregateFilterOps(\n () => v.decimal({ decimal: descriptor }),\n () => v.decimal({ decimal: descriptor, nullable: true })\n );\n const widened = sumOperandDomain(descriptor);\n return v.object(\n {\n _count: numericFilterOps,\n _avg: fieldOps,\n _sum: buildAggregateFilterOps(\n () => v.decimal({ decimal: widened }),\n () => v.decimal({ decimal: widened, nullable: true })\n ),\n _min: fieldOps,\n _max: fieldOps,\n },\n { optional: true }\n );\n};\n\nexport function getHavingSchema<\n M extends AnyModel,\n F extends ScalarFilterBundle,\n>(model: M, scalarSchemas: F): HavingSchema<M, F>;\nexport function getHavingSchema(\n model: AnyModel,\n scalarSchemas: ScalarFilterBundle\n): V.Schema {\n const entries: Record<string, V.Schema> = {};\n\n for (const [name, schemas] of Object.entries(scalarSchemas.scalars)) {\n // `having` reuses the model's own (shared, interned) scalar filter, which\n // accepts a field reference, an SQL fragment and the callback that returns\n // one in comparison positions. Prisma excludes field references from\n // having/groupBy — a HAVING operand is an aggregate over a group, not a\n // column of one row — and a fragment is out for the same reason, so re-close\n // the reused schema here instead of inheriting the operand by accident.\n const state = model[\"~\"].state.scalars[name]?.[\"~\"].state;\n if (state?.type === \"point\") {\n entries[name] = v.refused(\"A GeoPoint cannot be used in 'having'.\");\n continue;\n }\n entries[name] =\n state?.array === true\n ? listHavingSchema(schemas.filter)\n : v.noOperandExpression(\n v.union([\n havingAggregateSchema(state, schemas.filter),\n schemas.filter,\n ]),\n \"'having'\"\n );\n }\n\n // AND/OR/NOT recurse into the same schema through thunks — `.extend` returns\n // a NEW schema, so the thunks must close over the FINAL `havingSchema` const\n // (identical device to `getWhereSchema`, scalar entries last so a scalar\n // literally named `AND` still wins, exactly as it does in `where`). The engine\n // already builds all three combinators (`groupby-having.ts:17-36`); these\n // entries are what makes them reachable instead of dying on the strict-object\n // \"Unknown key: OR\".\n const havingSchema: V.Schema = v\n .object(\n {\n AND: () => v.optional(v.union([havingSchema, v.array(havingSchema)])),\n OR: () => v.optional(v.array(havingSchema)),\n NOT: () => v.optional(v.union([havingSchema, v.array(havingSchema)])),\n },\n { optional: true }\n )\n .extend(entries);\n\n // Scoped to the model like a `where` is, so an operand CALLBACK resolves here\n // too and is then refused by name (\"… is not supported in 'having'\") instead\n // of by the generic out-of-scope message. Acceptance is unchanged: what the\n // callback returns is exactly what the closure above rejects.\n return scopeOperands(havingSchema, model);\n}\n\n// =============================================================================\n// GROUP BY ORDER BY\n// =============================================================================\n\n/**\n * GroupBy orderBy follows Prisma's shape: grouped scalar fields (membership\n * in `by` is enforced at query time) plus aggregate orderings like\n * { _count: { field: \"desc\" } }, with `_all` supported for _count.\n */\ntype OrderDirectionSchema = V.Enum<[\"asc\", \"desc\"]>;\n\ntype GroupAggregateOrderSchema<M extends AnyModel, K extends string> = V.Object<\n V.FromKeys<K[], OrderDirectionSchema>[\"entries\"] &\n ListAggregateEntries<M> &\n PointAggregateEntries<M>\n>;\n\nexport type GroupByOrderBySchema<M extends AnyModel> = V.Object<\n V.FromKeys<OrderableScalarKeys<M>[], SortOrderSchema>[\"entries\"] &\n V.FromKeys<\n DecimalListScalarKeys<ModelStateOf<M>[\"scalars\"]>[],\n DecimalListOrderByRefusalSchema\n >[\"entries\"] & {\n _count: V.FromKeys<CountScalarKeys<M>[], OrderDirectionSchema>;\n _avg: GroupAggregateOrderSchema<\n M,\n NumericScalarKeys<ModelStateOf<M>[\"scalars\"]>\n >;\n _sum: GroupAggregateOrderSchema<\n M,\n NumericScalarKeys<ModelStateOf<M>[\"scalars\"]>\n >;\n _min: GroupAggregateOrderSchema<M, AggregateScalarKeys<M>>;\n _max: GroupAggregateOrderSchema<M, AggregateScalarKeys<M>>;\n }\n>;\n\nconst orderDirection = v.enum([\"asc\", \"desc\"]);\n\nexport const getGroupByOrderBySchema = <M extends AnyModel>(\n model: M\n): GroupByOrderBySchema<M> => {\n const state = model[\"~\"].state;\n const allScalarKeys: string[] = [];\n const scalarKeys: string[] = [];\n const decimalListKeys: string[] = [];\n const listKeys: string[] = [];\n const numericKeys: string[] = [];\n const aggregateKeys: string[] = [];\n const pointKeys: string[] = [];\n\n for (const name of Object.keys(state.scalars)) {\n const scalar = state.scalars[name]!;\n allScalarKeys.push(name);\n if (scalar[\"~\"].state.array === true) listKeys.push(name);\n if (scalar[\"~\"].state.type === \"point\") {\n pointKeys.push(name);\n } else if (isOrderableScalarState(scalar[\"~\"].state)) {\n scalarKeys.push(name);\n } else {\n decimalListKeys.push(name);\n }\n if (isSummableScalar(scalar[\"~\"].state)) {\n numericKeys.push(name);\n }\n if (\n scalar[\"~\"].state.array !== true &&\n scalar[\"~\"].state.type !== \"point\"\n ) {\n aggregateKeys.push(name);\n }\n }\n\n const aggregateOrder = (\n aggregate: \"_avg\" | \"_sum\" | \"_min\" | \"_max\",\n keys: string[]\n ) =>\n v.object({\n ...v.fromKeys(keys, orderDirection).entries,\n ...v.fromKeys(\n listKeys,\n v.refused(\n `A list cannot be ordered by '${aggregate}'; only '_count' is supported.`\n )\n ).entries,\n ...v.fromKeys(\n pointKeys,\n v.refused(\n `A GeoPoint cannot be ordered by '${aggregate}'; use '_distance' or '_count'.`\n )\n ).entries,\n });\n\n return v.object({\n ...v.fromKeys(scalarKeys, sortOrderSchema).entries,\n ...v.fromKeys(decimalListKeys, decimalListOrderByRefusalSchema).entries,\n _count: v.fromKeys([\"_all\", ...allScalarKeys], orderDirection),\n _avg: aggregateOrder(\"_avg\", numericKeys),\n _sum: aggregateOrder(\"_sum\", numericKeys),\n _min: aggregateOrder(\"_min\", aggregateKeys),\n _max: aggregateOrder(\"_max\", aggregateKeys),\n }) as GroupByOrderBySchema<M>;\n};\n\n// =============================================================================\n// GROUP BY ARGS\n// =============================================================================\n\n/**\n * GroupBy args: { by, where?, having?, orderBy?, take?, skip?, _count?, _avg?, _sum?, _min?, _max? }\n */\ntype GroupByScalarKeys<M extends AnyModel> = NonPointScalarKeys<\n ModelStateOf<M>[\"scalars\"]\n>;\n\ntype EnumOfScalarMap<M extends AnyModel> = V.Enum<GroupByScalarKeys<M>[]>;\n\nexport type GroupByArgs<\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n> = V.Object<\n {\n by: V.Union<\n readonly [\n V.Array<EnumOfScalarMap<M>>,\n V.ShorthandArray<EnumOfScalarMap<M>>,\n ]\n >;\n where: CoreSchemas<M, F>[\"where\"];\n having: HavingSchema<M, F>;\n orderBy: V.Union<\n readonly [GroupByOrderBySchema<M>, V.Array<GroupByOrderBySchema<M>>]\n >;\n take: PaginationTakeSchema;\n skip: PaginationSkipSchema;\n _count: V.Union<\n readonly [V.Literal<true>, AggregateScalarSchemas<M>[\"count\"]]\n >;\n _avg: AggregateScalarSchemas<M>[\"avg\"];\n _sum: AggregateScalarSchemas<M>[\"sum\"];\n _min: AggregateScalarSchemas<M>[\"min\"];\n _max: AggregateScalarSchemas<M>[\"max\"];\n },\n {\n atLeast: [\"by\"];\n }\n>;\n\n/**\n * The two grouped-column collisions, refused where `by` is admitted.\n *\n * A duplicate `by` member and a grouped scalar named like a selected\n * aggregate both produce ONE output column for TWO requested facts: the\n * second aliases over the first and the caller reads a silently wrong answer\n * (the aggregate wins). Neither is a lowering question — both are complete\n * facts about the admitted arguments. `_count` is not listed: schema\n * validation refuses a member of that name (F010), so no grouped scalar has it.\n */\nconst GROUP_AGGREGATE_KEYS = [\"_avg\", \"_sum\", \"_min\", \"_max\"] as const;\n\nconst groupByCollisions = (\n value: Record<string, unknown>\n): string | undefined => {\n // `by` is an `atLeast` key over `v.union([v.array(…), v.shorthandArray(…)])`,\n // so the object schema has already refused a missing `by` and normalised a\n // single column into a list before this runs: what arrives is a column set.\n const grouped = value.by as string[];\n if (new Set(grouped).size !== grouped.length) {\n return \"GroupBy operation does not allow duplicate fields in 'by'\";\n }\n for (const aggregate of GROUP_AGGREGATE_KEYS) {\n if (value[aggregate] !== undefined && grouped.includes(aggregate)) {\n return `Aggregate '${aggregate}' cannot be selected together with a model field named '${aggregate}'.`;\n }\n }\n return undefined;\n};\n\n/** What a grouped read may order by or compare besides a grouped field. */\nconst GROUPED_AGGREGATES: ReadonlySet<string> = new Set([\n \"_count\",\n ...GROUP_AGGREGATE_KEYS,\n]);\n\nconst HAVING_COMBINATORS: ReadonlySet<string> = new Set([\"AND\", \"OR\", \"NOT\"]);\n\n/**\n * The path, under `having`, of the first field-keyed condition on a field\n * outside `by`: it names ONE row's column, which a grouped row has only for a\n * grouped field. An aggregate condition is always legitimate; a combinator is\n * walked unless a declared field owns its name (that field wins the key).\n */\nconst ungroupedHavingPath = (\n having: unknown,\n by: readonly string[],\n scalars: Readonly<Record<string, unknown>>\n): PropertyKey[] | undefined => {\n for (const [key, value] of Object.entries(having ?? {})) {\n if (value === undefined || by.includes(key)) continue;\n if (HAVING_COMBINATORS.has(key) && !Object.hasOwn(scalars, key)) {\n const arms: unknown[] = Array.isArray(value) ? value : [value];\n for (const [index, arm] of arms.entries()) {\n const path = ungroupedHavingPath(arm, by, scalars);\n if (path)\n return Array.isArray(value) ? [key, index, ...path] : [key, ...path];\n }\n continue;\n }\n const aggregated =\n isRecord(value) &&\n Object.entries(value).some(\n ([name, operand]) =>\n operand !== undefined && GROUPED_AGGREGATES.has(name)\n );\n if (!aggregated) return [key];\n }\n return undefined;\n};\n\n/**\n * The refusals that read `by` against the rest of the payload, reported at the\n * key that is wrong. An empty `by` groups nothing (the database answered with\n * a syntax error); a `having` condition or an `orderBy` field outside `by`\n * names a column no grouped row has.\n */\nconst groupedMembershipIssue = (\n {\n by,\n having,\n orderBy,\n }: {\n readonly by: readonly string[];\n readonly having?: unknown;\n readonly orderBy?: unknown;\n },\n scalars: Readonly<Record<string, unknown>>\n): ValidationIssue | undefined => {\n if (by.length === 0)\n return {\n message: \"groupBy needs at least one field in 'by'.\",\n path: [\"by\"],\n };\n const ungrouped = ungroupedHavingPath(having, by, scalars);\n if (ungrouped)\n return {\n message: `Scalar '${String(ungrouped.at(-1))}' used in 'having' must be included in 'by'.`,\n path: [\"having\", ...ungrouped],\n };\n const terms: unknown[] = Array.isArray(orderBy) ? orderBy : [orderBy];\n for (const [index, term] of terms.entries())\n for (const [field, direction] of Object.entries(term ?? {})) {\n if (direction === undefined || by.includes(field)) continue;\n if (GROUPED_AGGREGATES.has(field)) continue;\n return {\n message: `GroupBy orderBy field '${field}' must be included in 'by' or be an aggregate (_count, _avg, _sum, _min, _max).`,\n path: Array.isArray(orderBy)\n ? [\"orderBy\", index, field]\n : [\"orderBy\", field],\n };\n }\n return undefined;\n};\n\nexport const getGroupByArgs = <M extends AnyModel, F extends ScalarSchemas<M>>(\n model: M,\n fieldSchemas: F,\n core: CoreSchemas<M, F>\n): GroupByArgs<M, F> => {\n const state = model[\"~\"].state;\n // Build \"by\" schema - array of scalar names or single scalar\n const scalarKeys = Object.keys(state.scalars).filter(\n (field) => state.scalars[field]![\"~\"].state.type !== \"point\"\n ) as GroupByScalarKeys<M>[];\n\n // Use enum for scalar names for proper type inference\n const scalarSchema = v.enum(scalarKeys);\n\n const aggSchemas = getAggregateScalarSchemas(model);\n const havingSchema = getHavingSchema(model, fieldSchemas);\n const orderBySchema = getGroupByOrderBySchema(model);\n\n return v.object(\n {\n // ONE admitted shape downstream: `by: \"category\"` and\n // `by: [\"category\"]` are the same grouped column set, normalised here\n // so no preparer asks the question again (or calls `.map` on a string).\n by: v.union([v.array(scalarSchema), v.shorthandArray(scalarSchema)]),\n where: v.lazyRef(() => core.where),\n having: havingSchema,\n orderBy: v.union([orderBySchema, v.array(orderBySchema)]),\n take: paginationTake(),\n skip: paginationSkip(),\n _count: v.union([v.literal(true), aggSchemas.count]),\n _avg: aggSchemas.avg,\n _sum: aggSchemas.sum,\n _min: aggSchemas.min,\n _max: aggSchemas.max,\n },\n {\n atLeast: [\"by\"],\n refuse: (value) =>\n groupByCollisions(value) ??\n groupedMembershipIssue(\n value as { readonly by: readonly string[] },\n state.scalars\n ),\n }\n ) as GroupByArgs<M, F>;\n};\n","/**\n * `omit` — the inverse of `select`.\n *\n * `omit: { passwordHash: true }` returns every projectable scalar EXCEPT the\n * named ones. It composes with `include` (relations ride alongside the reduced\n * scalar set) and with `select`: `select` names the candidate fields, then\n * `omit` subtracts selected scalars flagged `true`.\n *\n * DESUGARING. `omit` never reaches the query engine. This wrapper rewrites it\n * into the explicit `select` it denotes, immediately after the payload\n * validates, so exactly one projection vocabulary exists downstream — the same\n * trick the relation `include` nodes have always used\n * (`buildSelectionFromState`, `src/validation/relations/select-include.ts`).\n * The engine's default-projection branch is therefore untouched, and so is\n * `include`: the resulting args carry a scalar-only `select` NEXT TO the\n * original `include`, which is the exact shape the V2 write operations already\n * hand the read builder (`defaultSelect` + `parsedInclude` in\n * `CreateOperation` / `DeleteOperation`).\n *\n * EMPTY PROJECTIONS FAIL CLOSED. An `omit` that removes every default scalar,\n * or every truthy field of an explicit `select`, denotes `select: {}`. Answering\n * it with the default projection would return fields the caller asked to hide,\n * so it is refused here at the parse boundary.\n */\n\nimport type { AnyModel } from \"@schema/model\";\nimport type {\n ObjectOptions,\n ObjectSchema,\n} from \"@validation/primitives/object\";\nimport { isRecord } from \"@validation/value-guards\";\nimport v, { type V } from \"../../primitives/v\";\nimport type { CoreSchemas } from \"../core\";\nimport {\n type ProjectableScalarKeys,\n projectableScalarNames,\n} from \"../core/projection\";\nimport type { ScalarSchemas } from \"../index\";\n\nconst omitFlagSchema = v.boolean({ optional: true });\n\n/**\n * Keyed on {@link ProjectableScalarKeys}: a model-level `.omit()`-ed scalar has\n * no entry, so `omit: { passwordHash: false }` cannot re-include it (it is an\n * \"Unknown key\" failure). Client-level `omit` is a default and IS overridable —\n * but it is merged into this same value before validation runs, so `false` here\n * always means \"keep it\", never \"re-open the schema\".\n */\nexport type OmitSchema<M extends AnyModel> = V.Object<\n V.FromKeys<ProjectableScalarKeys<M>[], typeof omitFlagSchema>[\"entries\"],\n { optional: true }\n>;\n\nexport const getOmitSchema = <M extends AnyModel>(model: M): OmitSchema<M> =>\n v.object(\n v.fromKeys<ProjectableScalarKeys<M>[], typeof omitFlagSchema>(\n projectableScalarNames(model) as ProjectableScalarKeys<M>[],\n omitFlagSchema\n ).entries,\n { optional: true }\n ) as OmitSchema<M>;\n\n// ---------------------------------------------------------------------------\n// Desugaring wrapper\n// ---------------------------------------------------------------------------\n\nconst issue = (message: string) => ({ issues: [{ message }] });\n\nconst modelLabel = (model: AnyModel): string =>\n model[\"~\"].names.ts ?? model[\"~\"].state.tableName ?? \"model\";\n\n/**\n * The projection an `omit` denotes: every projectable scalar the value did not\n * flag `true`. `undefined` means \"nothing left\", which the caller refuses.\n */\nexport const buildOmitSelection = (\n model: AnyModel,\n omitValue: Record<string, unknown>\n): Record<string, true> | undefined => {\n const selection: Record<string, true> = {};\n for (const field of projectableScalarNames(model)) {\n if (omitValue[field] === true) continue;\n selection[field] = true;\n }\n return Object.keys(selection).length > 0 ? selection : undefined;\n};\n\nexport const emptyOmitProjectionMessage = (\n model: AnyModel,\n operation: string\n): string =>\n `'omit' on '${operation}' excluded every readable field of model '${modelLabel(model)}'. At least one field must remain in the result: drop a field from 'omit', or use 'select' to name what you want.`;\n\nexport const emptySelectedOmitProjectionMessage = (\n model: AnyModel,\n operation: string\n): string =>\n `'omit' on '${operation}' excluded every selected field of model '${modelLabel(model)}'. At least one field must remain in the result: remove a field from 'omit' or add another field to 'select'.`;\n\nconst hasProjectedValue = (selection: Record<string, unknown>): boolean => {\n for (const field in selection) {\n const selected = selection[field];\n if (selected !== false && selected !== undefined) return true;\n }\n return false;\n};\n\n/** Subtract local omit flags from an already-validated explicit selection. */\nconst subtractOmitFromSelection = (\n selection: Record<string, unknown>,\n omitValue: Record<string, unknown>\n): Record<string, unknown> => {\n const reduced: Record<string, unknown> = {};\n for (const field of Object.keys(selection)) {\n if (omitValue[field] === true) continue;\n reduced[field] = selection[field];\n }\n return reduced;\n};\n\n/**\n * Desugar `omit` into the one downstream projection vocabulary. With an\n * explicit `select`, subtract from that validated selection. Without one,\n * build the default scalar complement. Applied outside the other projection\n * guards so the rewrite happens after those guards validate the raw payload.\n */\nexport const withOmitProjection = <\n TEntries,\n TOpts extends ObjectOptions | undefined,\n>(\n schema: ObjectSchema<TEntries, TOpts>,\n model: AnyModel,\n operation: string\n): ObjectSchema<TEntries, TOpts> => {\n const standard = schema[\"~standard\"];\n\n const validate: typeof standard.validate = (value) => {\n const hasOmit = isRecord(value) && value.omit !== undefined;\n const result = standard.validate(value) as Exclude<\n ReturnType<typeof standard.validate>,\n PromiseLike<unknown>\n >;\n if (!hasOmit || result.issues) return result;\n return projectOmit(result, model, operation) as typeof result;\n };\n\n return {\n ...schema,\n parse: validate,\n \"~standard\": {\n version: standard.version,\n vendor: standard.vendor,\n validate,\n get types() {\n return standard.types;\n },\n get jsonSchema() {\n return standard.jsonSchema;\n },\n },\n };\n};\n\n/**\n * `omit` desugared into the `select` it means, apart from the per-call\n * validator so that arguments without `omit` never compile it.\n */\nfunction projectOmit(\n result: { readonly value: unknown },\n model: AnyModel,\n operation: string\n) {\n\n const validated = result.value as Record<string, unknown>;\n const omitValue = validated.omit as Record<string, unknown>;\n const explicitSelection = isRecord(validated.select)\n ? validated.select\n : undefined;\n const selection = explicitSelection\n ? subtractOmitFromSelection(explicitSelection, omitValue)\n : buildOmitSelection(model, omitValue);\n if (!selection) return issue(emptyOmitProjectionMessage(model, operation));\n if (\n explicitSelection &&\n hasProjectedValue(explicitSelection) &&\n !hasProjectedValue(selection)\n ) {\n return issue(emptySelectedOmitProjectionMessage(model, operation));\n }\n\n // The rewrite drops a key the schema declares and adds one it also declares,\n // so the OUTPUT type is unchanged in kind but not provably so to the checker\n // (`TEntries` is opaque here). Widening through `unknown` keeps the assertion\n // to the one place that performs the substitution.\n const { omit: _omit, ...rest } = validated;\n const rewritten: unknown = { ...rest, select: selection };\n return { value: rewritten as Record<string, unknown> };\n}\n\n// ---------------------------------------------------------------------------\n// Upsert's projection\n// ---------------------------------------------------------------------------\n\n/**\n * `upsert` is the one write with NO whole-args parse — its create/update arms\n * are delegated to sub-operations that must receive the RAW payload, and the\n * untaken arm must not be validated at all (see `UpsertOperation`). Its\n * projection therefore gets its own small schema, so `omit` still desugars\n * through the ONE wrapper above instead of growing a second implementation\n * inside the engine.\n */\nexport type UpsertProjectionSchema<\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n> = V.Object<{\n select: CoreSchemas<M, F>[\"select\"];\n include: CoreSchemas<M, F>[\"include\"];\n omit: OmitSchema<M>;\n}>;\n\nexport const getUpsertProjectionSchema = <\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n>(\n model: M,\n core: CoreSchemas<M, F>\n): UpsertProjectionSchema<M, F> =>\n withOmitProjection(\n v.object({\n select: v.lazyRef(() => core.select),\n include: v.lazyRef(() => core.include),\n omit: v.lazyRef(() => core.omit),\n }),\n model,\n \"upsert\"\n );\n","import type {\n ObjectOptions,\n ObjectSchema,\n} from \"@validation/primitives/object\";\nimport { isRecord } from \"@validation/value-guards\";\n\nconst SELECT_INCLUDE_EXCLUSIVITY_ERROR = {\n issues: [\n {\n message:\n \"Mutually exclusive fields cannot be used together: select, include\",\n },\n ],\n};\n\n/**\n * Both projections are present only when both carry a VALUE.\n *\n * Reading key PRESENCE instead refused the spread-an-optional idiom the whole\n * client surface is documented to accept — `{ ...(sel && { select: sel }),\n * ...(inc && { include: inc }) }` spelled out, or a helper forwarding two\n * optional props (`{ select: args.select, include: args.include }`) — because an\n * explicitly-`undefined` key is an ABSENT key at the parse boundary\n * (`src/validation/primitives/object.ts`). `withOmitProjection` uses the same\n * value-based presence rule when it decides whether an explicit select exists,\n * so a payload whose second projection is `undefined` names exactly one\n * projection and must be accepted.\n */\nconst hasSelectAndInclude = (value: unknown): boolean => {\n return (\n isRecord(value) && value.select !== undefined && value.include !== undefined\n );\n};\n\nexport const rejectSelectInclude = <\n TEntries,\n TOpts extends ObjectOptions | undefined,\n>(\n schema: ObjectSchema<TEntries, TOpts>\n): ObjectSchema<TEntries, TOpts> => {\n const standard = schema[\"~standard\"];\n const validate: typeof standard.validate = (value) => {\n if (hasSelectAndInclude(value)) {\n return SELECT_INCLUDE_EXCLUSIVITY_ERROR;\n }\n return standard.validate(value);\n };\n\n const wrappedSchema: ObjectSchema<TEntries, TOpts> = {\n ...schema,\n parse: validate,\n \"~standard\": {\n version: standard.version,\n vendor: standard.vendor,\n validate,\n get types() {\n return standard.types;\n },\n get jsonSchema() {\n return standard.jsonSchema;\n },\n },\n };\n\n return wrappedSchema;\n};\n","import type { AnyModel } from \"@schema/model\";\nimport type { NonPointScalarKeys } from \"@schema/model/helper\";\nimport v, { type V } from \"../../primitives/v\";\nimport type { CoreSchemas } from \"../core\";\nimport type { ScalarSchemas } from \"../index\";\nimport { type OmitSchema, withOmitProjection } from \"./omit\";\nimport {\n type PaginationSkipSchema,\n type PaginationTakeSchema,\n paginationSkip,\n paginationTake,\n} from \"./pagination\";\nimport { rejectSelectInclude } from \"./select-include-exclusivity\";\n\n/**\n * FindUnique args: { where: whereUniqueExtended, select?, include? }\n *\n * `where` is the EXTENDED unique selector (Prisma >= 4.5): at least one unique\n * discriminator, plus any non-unique scalar filters / AND / OR / NOT. `cursor`\n * below keeps the STRICT `whereUnique` — a cursor is an exact row address, not a\n * filtered lookup.\n */\n\ntype ModelStateOf<M extends AnyModel> = M[\"~\"][\"state\"];\n\n/**\n * `distinct` accepts a single scalar name or an array of them; the bare string\n * is coerced to a one-element array so the engine only ever sees `string[]`.\n * Prisma allows the shorthand on both `findMany` and `findFirst`.\n */\ntype DistinctSchema<M extends AnyModel> = V.SingleOrArray<\n V.Enum<NonPointScalarKeys<ModelStateOf<M>[\"scalars\"]>[]>\n>;\n\nconst getDistinctSchema = <M extends AnyModel>(model: M): DistinctSchema<M> => {\n const fieldNames = Object.keys(model[\"~\"].state.scalars).filter(\n (field) => model[\"~\"].state.scalars[field]![\"~\"].state.type !== \"point\"\n ) as NonPointScalarKeys<ModelStateOf<M>[\"scalars\"]>[];\n return v.singleOrArray(v.enum(fieldNames)) as DistinctSchema<M>;\n};\n\nexport type FindUniqueArgs<\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n> = V.Object<\n {\n where: CoreSchemas<M, F>[\"whereUniqueExtended\"];\n select: CoreSchemas<M, F>[\"select\"];\n include: CoreSchemas<M, F>[\"include\"];\n omit: OmitSchema<M>;\n },\n { atLeast: [\"where\"] }\n>;\n\nexport const getFindUniqueArgs = <\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n>(\n model: M,\n core: CoreSchemas<M, F>\n): FindUniqueArgs<M, F> => {\n return withOmitProjection(\n rejectSelectInclude(\n v.object(\n {\n where: v.lazyRef(() => core.whereUniqueExtended),\n select: v.lazyRef(() => core.select),\n include: v.lazyRef(() => core.include),\n omit: v.lazyRef(() => core.omit),\n },\n { atLeast: [\"where\"] }\n )\n ),\n model,\n \"findUnique\"\n );\n};\n\n/**\n * FindFirst args: { where?, orderBy?, take?, skip?, cursor?, select?, include?, distinct? }\n */\nexport type FindFirstArgs<\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n> = V.Object<\n {\n where: CoreSchemas<M, F>[\"where\"];\n orderBy: V.Union<\n readonly [\n CoreSchemas<M, F>[\"orderBy\"],\n V.Array<CoreSchemas<M, F>[\"orderBy\"]>,\n ]\n >;\n take: PaginationTakeSchema;\n skip: PaginationSkipSchema;\n cursor: CoreSchemas<M, F>[\"whereUnique\"];\n select: CoreSchemas<M, F>[\"select\"];\n include: CoreSchemas<M, F>[\"include\"];\n omit: OmitSchema<M>;\n distinct: DistinctSchema<M>;\n },\n { optional: true }\n>;\n\nexport const getFindFirstArgs = <\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n>(\n model: M,\n core: CoreSchemas<M, F>\n): FindFirstArgs<M, F> => {\n return withOmitProjection(\n rejectSelectInclude(\n v.object(\n {\n where: v.lazyRef(() => core.where),\n orderBy: v.lazyRef(() =>\n v.union([core.orderBy, v.array(core.orderBy)])\n ),\n take: paginationTake(),\n skip: paginationSkip(),\n cursor: v.lazyRef(() => core.whereUnique),\n select: v.lazyRef(() => core.select),\n include: v.lazyRef(() => core.include),\n omit: v.lazyRef(() => core.omit),\n // Prisma has distinct on findFirst too; it compiles through the same\n // findMany-with-limit path (ReadOperation), so nothing else changes.\n distinct: v.lazyRef(() => getDistinctSchema(model)),\n },\n {\n optional: true,\n }\n )\n ),\n model,\n \"findFirst\"\n );\n};\n\n// =============================================================================\n// FIND MANY ARGS\n// =============================================================================\n\n/**\n * FindMany args: { where?, orderBy?, take?, skip?, cursor?, select?, include?, distinct? }\n */\nexport type FindManyArgs<\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n> = V.Object<\n {\n where: CoreSchemas<M, F>[\"where\"];\n orderBy: V.Union<\n readonly [\n CoreSchemas<M, F>[\"orderBy\"],\n V.Array<CoreSchemas<M, F>[\"orderBy\"]>,\n ]\n >;\n take: PaginationTakeSchema;\n skip: PaginationSkipSchema;\n cursor: CoreSchemas<M, F>[\"whereUnique\"];\n select: CoreSchemas<M, F>[\"select\"];\n include: CoreSchemas<M, F>[\"include\"];\n omit: OmitSchema<M>;\n distinct: DistinctSchema<M>;\n },\n { optional: true }\n>;\nexport const getFindManyArgs = <M extends AnyModel, F extends ScalarSchemas<M>>(\n model: M,\n core: CoreSchemas<M, F>\n): FindManyArgs<M, F> => {\n return withOmitProjection(\n rejectSelectInclude(\n v.object(\n {\n where: v.lazyRef(() => core.where),\n orderBy: v.lazyRef(() =>\n v.union([core.orderBy, v.array(core.orderBy)])\n ),\n take: paginationTake(),\n skip: paginationSkip(),\n cursor: v.lazyRef(() => core.whereUnique),\n select: v.lazyRef(() => core.select),\n include: v.lazyRef(() => core.include),\n omit: v.lazyRef(() => core.omit),\n distinct: v.lazyRef(() => getDistinctSchema(model)),\n },\n { optional: true }\n )\n ),\n model,\n \"findMany\"\n );\n};\n","import type { AnyModel } from \"@schema/model\";\nimport type {\n ObjectOptions,\n ObjectSchema,\n} from \"@validation/primitives/object\";\nimport { isRecord } from \"@validation/value-guards\";\n\n/**\n * A bulk write projects SCALARS.\n *\n * `createMany` / `updateMany` / `deleteMany` return their affected rows straight\n * out of the write statement — `RETURNING` on a capable driver, capture-and-\n * refetch on a non-returning one — and viborm does not project relations into\n * that row set. Both spellings of \"give me a relation too\" are refused here, at\n * the parse boundary, with a message that names the alternative:\n *\n * - `include`, which has no place on the surface at all; and\n * - a relation key (or `_count`) inside `select`, which the scalar-only\n * `core.scalarSelect` schema would otherwise reject as a bare\n * \"Unknown key: <relation>\".\n *\n * The second refusal is the load-bearing one, and it replaces SILENTLY WRONG\n * DATA. A relation subquery embedded in a `RETURNING` list has no table alias to\n * correlate against, so its outer column reference binds by name and is captured\n * by the inner table whenever both tables have a column of that name. Observed\n * on PGlite before this refusal existed, with `findMany` as the control:\n *\n * warehouse.updateMany({ …, select: { id: true, inventory: … } })\n * -> [{ id: \"w1\", inventory: [] }] // every to-many, always empty\n * node.createMany({ data: [{ id: \"n2\", parentId: \"n1\" }],\n * select: { id: true, parent: … } })\n * -> [{ id: \"n2\", parent: null }] // self-relation to-one\n * node.findMany({ where: { id: \"n2\" }, select: { id: true, parent: … } })\n * -> [{ id: \"n2\", parent: { id: \"n1\" } }] // the truth\n *\n * A to-one hop between differently-named tables happened to work, which is what\n * made the hole look like a feature. Fail closed instead: read relations in a\n * separate query.\n *\n * Prisma divergence, deliberate: Prisma's `createManyAndReturn` /\n * `updateManyAndReturn` DO accept relations in `select`/`include` (its generator\n * emits `<Model>SelectCreateManyAndReturn` / `<Model>IncludeCreateManyAndReturn`).\n * viborm refuses rather than ship a projection that answers wrongly.\n */\nexport const restrictToScalarProjection = <\n TEntries,\n TOpts extends ObjectOptions | undefined,\n>(\n schema: ObjectSchema<TEntries, TOpts>,\n model: AnyModel,\n operation: string\n): ObjectSchema<TEntries, TOpts> => {\n const relationKeys = new Set(Object.keys(model[\"~\"].state.relations));\n const standard = schema[\"~standard\"];\n\n const validate: typeof standard.validate = (value) => {\n if (hasOwnKey(value, \"include\")) {\n return issue(\n `'include' is not supported on '${operation}': a bulk write returns the rows its write statement produced, and viborm does not project relations into them. Select the scalar fields you need and read relations in a separate query.`\n );\n }\n const relationKey = findProjectedRelation(value, relationKeys);\n if (relationKey !== undefined) {\n return issue(\n `'select.${relationKey}' is not supported on '${operation}': a bulk write projects scalar fields only. Read the relation in a separate query.`\n );\n }\n return standard.validate(value);\n };\n\n return {\n ...schema,\n parse: validate,\n \"~standard\": {\n version: standard.version,\n vendor: standard.vendor,\n validate,\n get types() {\n return standard.types;\n },\n get jsonSchema() {\n return standard.jsonSchema;\n },\n },\n };\n};\n\nconst issue = (message: string) => ({ issues: [{ message }] });\n\nconst hasOwnKey = (value: unknown, key: string): boolean =>\n isRecord(value) && Object.hasOwn(value, key);\n\n/**\n * The first relation-shaped key in the payload's `select`, or `undefined`.\n * `_count` counts as one: it is a relation-derived projection built by the same\n * correlated-subquery machinery.\n */\nconst findProjectedRelation = (\n value: unknown,\n relationKeys: ReadonlySet<string>\n): string | undefined => {\n if (!isRecord(value)) return undefined;\n const select = value.select;\n if (!isRecord(select)) return undefined;\n for (const key of Object.keys(select)) {\n if (select[key] === undefined) continue;\n if (key === \"_count\" || relationKeys.has(key)) return key;\n }\n return undefined;\n};\n","// Mutation operation args schema factories\n\nimport type { AnyModel } from \"@schema/model\";\nimport { isRecord } from \"@validation/value-guards\";\nimport v, { type V } from \"../../primitives/v\";\nimport type { CoreSchemas } from \"../core\";\nimport type { ScalarSchemas } from \"../index\";\nimport { restrictToScalarProjection } from \"./bulk-write-projection\";\nimport { type OmitSchema, withOmitProjection } from \"./omit\";\nimport { type BulkWriteLimitSchema, bulkWriteLimit } from \"./pagination\";\nimport { rejectSelectInclude } from \"./select-include-exclusivity\";\n// =============================================================================\n// CREATE ARGS\n// =============================================================================\n\n/**\n * Create args: { data: create, select?, include? }\n */\nexport type CreateArgs<\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n> = V.Object<\n {\n data: CoreSchemas<M, F>[\"create\"];\n select: CoreSchemas<M, F>[\"select\"];\n include: CoreSchemas<M, F>[\"include\"];\n omit: OmitSchema<M>;\n },\n { atLeast: [\"data\"] }\n>;\nexport const getCreateArgs = <M extends AnyModel, F extends ScalarSchemas<M>>(\n model: M,\n core: CoreSchemas<M, F>\n): CreateArgs<M, F> => {\n return withOmitProjection(\n rejectSelectInclude(\n v.object(\n {\n data: v.lazyRef(() => core.create),\n select: v.lazyRef(() => core.select),\n include: v.lazyRef(() => core.include),\n omit: v.lazyRef(() => core.omit),\n },\n { atLeast: [\"data\"] }\n )\n ),\n model,\n \"create\"\n );\n};\n\n// =============================================================================\n// CREATE MANY ARGS\n// =============================================================================\n\n/**\n * The ONE owner of \"a default-only row cannot be skipped\".\n *\n * `skipDuplicates` needs a conflict target to suppress on, and a row with no\n * explicit value has nothing to name: no dialect has a portable\n * `INSERT … DEFAULT VALUES ON CONFLICT DO NOTHING` shape. The fact is a fact\n * about the ADMITTED payload, so it is asked wherever the verb appears — the\n * root args below, a nested `createMany` inside a `create` or an `update`, and\n * a polymorphic collection group — rather than at the set-oriented physical\n * owner, which a nested `createMany` never reaches (it is expanded row by row\n * into `create` records long before).\n */\nexport const refuseDefaultOnlySkipDuplicates = (\n value: Record<string, unknown>\n): string | undefined => {\n if (value.skipDuplicates !== true) return undefined;\n // Every registration of this refusal spells `data` as an `atLeast` key over\n // `v.array(...)`, so the object schema has already refused a missing or\n // non-array `data` before this runs.\n const rows = value.data as unknown[];\n const defaultOnly = rows.some(\n (row) =>\n isRecord(row) &&\n Object.values(row).every((member) => member === undefined)\n );\n return defaultOnly\n ? \"createMany with skipDuplicates cannot include a row with no explicit scalar values; no portable duplicate-only DEFAULT VALUES primitive exists.\"\n : undefined;\n};\n\n/**\n * CreateMany args: { data: create[], skipDuplicates?, select? }\n *\n * IMPLICIT RETURNING (the replacement for the removed `createManyAndReturn`):\n * `select` is optional, and its PRESENCE is what makes the operation return the\n * created rows instead of `{ count }`.\n *\n * That `select` is SCALAR-ONLY (`core.scalarSelect`), and `include` is refused\n * outright: viborm does not project relations into a bulk write's returned rows.\n * See `restrictToScalarProjection` for why — it replaces a projection that\n * returned silently wrong values — and for the message both refusals carry.\n */\ntype AvailableCreateManyArgs<\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n> = V.Object<\n {\n data: V.Array<CoreSchemas<M, F>[\"bulkCreate\"]>;\n skipDuplicates: V.Boolean<{ optional: true }>;\n select: CoreSchemas<M, F>[\"scalarSelect\"];\n omit: OmitSchema<M>;\n },\n { atLeast: [\"data\"] }\n>;\nexport type CreateManyArgs<\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n> = AvailableCreateManyArgs<M, F>;\nexport const getCreateManyArgs = <\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n>(\n model: M,\n core: CoreSchemas<M, F>\n): CreateManyArgs<M, F> => {\n const availableSchema = withOmitProjection(\n restrictToScalarProjection(\n v.object(\n {\n data: v.lazyRef(() => v.array(core.bulkCreate)),\n skipDuplicates: v.boolean({ optional: true }),\n select: v.lazyRef(() => core.scalarSelect),\n omit: v.lazyRef(() => core.omit),\n },\n { atLeast: [\"data\"], refuse: refuseDefaultOnlySkipDuplicates }\n ),\n model,\n \"createMany\"\n ),\n model,\n \"createMany\"\n );\n return availableSchema as CreateManyArgs<M, F>;\n};\n\n// =============================================================================\n// UPDATE ARGS\n// =============================================================================\n\n/**\n * Update args: { where: whereUniqueExtended, data: update, select?, include? }\n *\n * `where` is the EXTENDED unique selector (Prisma >= 4.5): at least one unique\n * discriminator, plus any non-unique scalar filters / AND / OR / NOT. A unique\n * key that matches while an extra filter excludes the row is a NOT-FOUND, not a\n * silent no-op — see `docs/content/docs/client/`.\n */\nexport type UpdateArgs<\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n> = V.Object<\n {\n where: CoreSchemas<M, F>[\"whereUniqueExtended\"];\n data: CoreSchemas<M, F>[\"update\"];\n select: CoreSchemas<M, F>[\"select\"];\n include: CoreSchemas<M, F>[\"include\"];\n omit: OmitSchema<M>;\n },\n { atLeast: [\"where\", \"data\"] }\n>;\n\nexport const getUpdateArgs = <M extends AnyModel, F extends ScalarSchemas<M>>(\n model: M,\n core: CoreSchemas<M, F>\n): UpdateArgs<M, F> => {\n return withOmitProjection(\n rejectSelectInclude(\n v.object(\n {\n where: v.lazyRef(() => core.whereUniqueExtended),\n data: v.lazyRef(() => core.update),\n select: v.lazyRef(() => core.select),\n include: v.lazyRef(() => core.include),\n omit: v.lazyRef(() => core.omit),\n },\n { atLeast: [\"where\", \"data\"] }\n )\n ),\n model,\n \"update\"\n );\n};\n\n// =============================================================================\n// UPDATE MANY ARGS\n// =============================================================================\n\n/**\n * UpdateMany args: { where?, data: update, select? }\n *\n * `data` binds to the model's ORDINARY update schema — the SAME instance\n * `getUpdateArgs` binds (`core.update`, memoized once per model in the registry),\n * so relation and polymorphic keys mean here exactly what they mean on a single\n * `update` and cannot drift into a second dialect of the same surface. It is the\n * ordinary update schema rather than a scalar-only one: a relation-bearing `data`\n * routes to a record series that applies one ordinary selected-record update per\n * captured root.\n *\n * WHAT THE SCHEMA DELIBERATELY DOES NOT DECIDE. Which of those shapes the ENGINE\n * can apply to N roots at once is not a parse-boundary question: \"this child-held\n * `connect` names one child, and N roots cannot each own it\" depends on the\n * captured root count, which no schema can see. That refusal lives in\n * `UpdateManyRecordSeries`, pre-write, naming the observed N — and the existing\n * nested-relation-inside-`updateMany`-data legality stays with its engine owner\n * too (`relation-key-legality.ts`). The schema's job here is only that the key\n * EXISTS and its payload is well-formed.\n *\n * `core.update` carries no `atLeast` and no `requiresOneOfKeySets` (unlike\n * `create`), so nothing about the envelope's own `atLeast: [\"data\"]` changes.\n *\n * IMPLICIT RETURNING (the replacement for the removed `updateManyAndReturn`):\n * `select` is optional, and its PRESENCE is what makes the operation return the\n * updated rows instead of `{ count }`. That `select` stays SCALAR-ONLY and\n * `include` is refused, exactly as on `createMany` (see\n * `restrictToScalarProjection`) — a deliberate asymmetry with `data`, which now\n * accepts relations: what a bulk write may WRITE and what it may PROJECT are\n * different questions, and the projection one is answered by whether a relation\n * subquery in a `RETURNING` list can correlate (it cannot).\n *\n * `limit` (Prisma 6.x) caps how many rows the UPDATE affects — including on the\n * returning arm, where exactly the capped rows come back. The engine takes the\n * first matching rows by primary key, ascending; a bulk write takes no\n * `orderBy`.\n */\nexport type UpdateManyArgs<\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n> = V.Object<\n {\n where: CoreSchemas<M, F>[\"where\"];\n data: CoreSchemas<M, F>[\"update\"];\n select: CoreSchemas<M, F>[\"scalarSelect\"];\n omit: OmitSchema<M>;\n limit: BulkWriteLimitSchema;\n },\n { atLeast: [\"data\"] }\n>;\nexport const getUpdateManyArgs = <\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n>(\n model: M,\n core: CoreSchemas<M, F>\n): UpdateManyArgs<M, F> => {\n return withOmitProjection(\n restrictToScalarProjection(\n v.object(\n {\n where: v.lazyRef(() => core.where),\n data: v.lazyRef(() => core.update),\n select: v.lazyRef(() => core.scalarSelect),\n omit: v.lazyRef(() => core.omit),\n limit: bulkWriteLimit(),\n },\n { atLeast: [\"data\"] }\n ),\n model,\n \"updateMany\"\n ),\n model,\n \"updateMany\"\n );\n};\n\n// =============================================================================\n// DELETE ARGS\n// =============================================================================\n\n/**\n * Delete args: { where: whereUniqueExtended, select?, include? }\n *\n * `where` is the EXTENDED unique selector (Prisma >= 4.5) — see UpdateArgs.\n */\nexport type DeleteArgs<\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n> = V.Object<\n {\n where: CoreSchemas<M, F>[\"whereUniqueExtended\"];\n select: CoreSchemas<M, F>[\"select\"];\n include: CoreSchemas<M, F>[\"include\"];\n omit: OmitSchema<M>;\n },\n { atLeast: [\"where\"] }\n>;\nexport const getDeleteArgs = <M extends AnyModel, F extends ScalarSchemas<M>>(\n model: M,\n core: CoreSchemas<M, F>\n): DeleteArgs<M, F> => {\n return withOmitProjection(\n rejectSelectInclude(\n v.object(\n {\n where: v.lazyRef(() => core.whereUniqueExtended),\n select: v.lazyRef(() => core.select),\n include: v.lazyRef(() => core.include),\n omit: v.lazyRef(() => core.omit),\n },\n { atLeast: [\"where\"] }\n )\n ),\n model,\n \"delete\"\n );\n};\n\n// =============================================================================\n// DELETE MANY ARGS\n// =============================================================================\n\n/**\n * DeleteMany args: { where?, select? }\n *\n * IMPLICIT RETURNING, extended past Prisma (which has no returning `deleteMany`\n * at all): `select` is optional, and its PRESENCE makes the operation return the\n * deleted rows instead of `{ count }`. That `select` is SCALAR-ONLY and\n * `include` is refused, for the same reason as the other bulk writes (see\n * `restrictToScalarProjection`).\n *\n * `limit` (Prisma 6.x) caps how many rows the DELETE removes, the first\n * matching rows by primary key — see `UpdateManyArgs`.\n */\nexport type DeleteManyArgs<\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n> = V.Object<\n {\n where: CoreSchemas<M, F>[\"where\"];\n select: CoreSchemas<M, F>[\"scalarSelect\"];\n omit: OmitSchema<M>;\n limit: BulkWriteLimitSchema;\n },\n { optional: true }\n>;\nexport const getDeleteManyArgs = <\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n>(\n model: M,\n core: CoreSchemas<M, F>\n): DeleteManyArgs<M, F> => {\n return withOmitProjection(\n restrictToScalarProjection(\n v.object(\n {\n where: v.lazyRef(() => core.where),\n select: v.lazyRef(() => core.scalarSelect),\n omit: v.lazyRef(() => core.omit),\n limit: bulkWriteLimit(),\n },\n { optional: true }\n ),\n model,\n \"deleteMany\"\n ),\n model,\n \"deleteMany\"\n );\n};\n\n// =============================================================================\n// UPSERT ARGS\n// =============================================================================\n\n/**\n * Upsert args: { where: whereUniqueExtended, create, update, select?, include?, targetWhere?, setWhere? }\n *\n * targetWhere and setWhere are additional predicates on an existing row.\n * Both must match for the update; a non-matching row is returned unchanged.\n * An absent row follows the create arm, independently of these guards.\n */\nexport type UpsertArgs<\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n> = V.Object<\n {\n where: CoreSchemas<M, F>[\"whereUniqueExtended\"];\n create: CoreSchemas<M, F>[\"create\"];\n update: CoreSchemas<M, F>[\"update\"];\n select: CoreSchemas<M, F>[\"select\"];\n include: CoreSchemas<M, F>[\"include\"];\n omit: OmitSchema<M>;\n /** Additional predicate on the existing row, combined with setWhere. */\n targetWhere: CoreSchemas<M, F>[\"where\"];\n /** Additional predicate on the existing row, combined with targetWhere. */\n setWhere: CoreSchemas<M, F>[\"where\"];\n },\n { atLeast: [\"where\", \"create\", \"update\"] }\n>;\n\nexport const getUpsertArgs = <M extends AnyModel, F extends ScalarSchemas<M>>(\n model: M,\n core: CoreSchemas<M, F>\n): UpsertArgs<M, F> => {\n return withOmitProjection(\n rejectSelectInclude(\n v.object(\n {\n where: v.lazyRef(() => core.whereUniqueExtended),\n create: v.lazyRef(() => core.create),\n update: v.lazyRef(() => core.update),\n select: v.lazyRef(() => core.select),\n include: v.lazyRef(() => core.include),\n omit: v.lazyRef(() => core.omit),\n targetWhere: v.lazyRef(() => core.where),\n setWhere: v.lazyRef(() => core.where),\n },\n { atLeast: [\"where\", \"create\", \"update\"] }\n )\n ),\n model,\n \"upsert\"\n );\n};\n","// Args schema factories - re-exports\n\nimport type { AnyModel } from \"@schema/model\";\nimport { lazyRecord } from \"../../lazy\";\nimport type { CoreSchemas } from \"../core\";\nimport type { ScalarSchemas } from \"../index\";\nimport {\n type AggregateArgs,\n type CountArgs,\n type ExistArgs,\n type GroupByArgs,\n getAggregateArgs,\n getCountArgs,\n getExistArgs,\n getGroupByArgs,\n} from \"./aggregate\";\nimport {\n type FindFirstArgs,\n type FindManyArgs,\n type FindUniqueArgs,\n getFindFirstArgs,\n getFindManyArgs,\n getFindUniqueArgs,\n} from \"./find\";\nimport type {\n CreateArgs,\n CreateManyArgs,\n DeleteArgs,\n DeleteManyArgs,\n UpdateArgs,\n UpdateManyArgs,\n UpsertArgs,\n} from \"./mutation\";\nimport {\n getCreateArgs,\n getCreateManyArgs,\n getDeleteArgs,\n getDeleteManyArgs,\n getUpdateArgs,\n getUpdateManyArgs,\n getUpsertArgs,\n} from \"./mutation\";\n\n// Aggregate exports\nexport {\n getAggregateArgs,\n getAggregateScalarSchemas,\n getCountArgs,\n getExistArgs,\n getGroupByArgs,\n} from \"./aggregate\";\n// Find exports\nexport { getFindFirstArgs, getFindManyArgs, getFindUniqueArgs } from \"./find\";\n// Mutation exports\nexport {\n getCreateArgs,\n getCreateManyArgs,\n getDeleteArgs,\n getDeleteManyArgs,\n getUpdateArgs,\n getUpdateManyArgs,\n getUpsertArgs,\n} from \"./mutation\";\n\nexport type ArgsSchemas<M extends AnyModel, F extends ScalarSchemas<M>> = {\n findUnique: FindUniqueArgs<M, F>;\n findFirst: FindFirstArgs<M, F>;\n findMany: FindManyArgs<M, F>;\n create: CreateArgs<M, F>;\n createMany: CreateManyArgs<M, F>;\n update: UpdateArgs<M, F>;\n updateMany: UpdateManyArgs<M, F>;\n delete: DeleteArgs<M, F>;\n deleteMany: DeleteManyArgs<M, F>;\n upsert: UpsertArgs<M, F>;\n count: CountArgs<M, F>;\n exist: ExistArgs<M, F>;\n aggregate: AggregateArgs<M, F>;\n groupBy: GroupByArgs<M, F>;\n};\n\nexport const getArgsSchemas = <M extends AnyModel, F extends ScalarSchemas<M>>(\n model: M,\n _fieldSchemas: F,\n core: CoreSchemas<M, F>\n): ArgsSchemas<M, F> => {\n // Each operation's arg schema is built on first access and memoized. The\n // validator only reads a single `args[operation]` per query, so unused\n // operations are never constructed — and because each builder pulls from the\n // lazy `core` object, only the core schemas that operation needs get built.\n return lazyRecord<ArgsSchemas<M, F>>({\n findUnique: () => getFindUniqueArgs(model, core),\n findFirst: () => getFindFirstArgs(model, core),\n findMany: () => getFindManyArgs(model, core),\n create: () => getCreateArgs(model, core),\n createMany: () => getCreateManyArgs(model, core),\n update: () => getUpdateArgs(model, core),\n updateMany: () => getUpdateManyArgs(model, core),\n delete: () => getDeleteArgs(model, core),\n deleteMany: () => getDeleteManyArgs(model, core),\n upsert: () => getUpsertArgs(model, core),\n count: () => getCountArgs(model, core),\n exist: () => getExistArgs(core),\n aggregate: () => getAggregateArgs(model, core),\n groupBy: () => getGroupByArgs(model, _fieldSchemas, core),\n });\n};\n","import type { AnyModel, ModelState } from \"@schema/model\";\nimport type { RequiredScalarKeys as ModelRequiredScalarKeys } from \"@schema/model/helper\";\nimport { slotMayBeEmpty } from \"@schema/relation/clearability\";\nimport type {\n Cardinality,\n SlotMayBeEmpty,\n} from \"@schema/relation/static-membership\";\nimport type { RelationState } from \"@schema/relation/types\";\nimport type { Scalar } from \"@schema/scalars\";\nimport type { ResolvedSlot } from \"@schema/validation/relation-resolution\";\nimport type { ObjectSchema } from \"../../primitives/object\";\nimport v, { type V } from \"../../primitives/v\";\nimport type { ScalarSchemas } from \"../index\";\n\n// =============================================================================\n// SCALAR CREATE\n// =============================================================================\n\n/**\n * Build scalar create schema - all scalar fields for create input\n */\n\ntype ModelStateOf<M extends AnyModel> = M[\"~\"][\"state\"];\ntype ModelRelations<M extends AnyModel> = ModelStateOf<M>[\"relations\"];\n\n/** The local half of every foreign key this model's own relations store. */\ntype ForeignKeyScalarKeys<M extends AnyModel> = {\n [K in keyof ModelRelations<M>]: ModelRelations<M>[K][\"~\"][\"state\"] extends {\n readonly foreignKey: {\n readonly fields: readonly (infer ScalarKey extends string)[];\n };\n }\n ? ScalarKey\n : never;\n}[keyof ModelRelations<M>];\n\ntype RequiredForeignKeyMembers<\n M extends AnyModel,\n Members extends string,\n> = Extract<Members, RequiredModelScalarKeys<M>>;\n\n/**\n * One singular stored reference, as the key sets a create payload may satisfy\n * its non-produced columns with. An empty slot still needs every non-null member;\n * a nonempty slot needs the whole tuple. A column-producing relation input is the\n * other alternative in both cases.\n */\ntype CreateRequirementGroup<M extends AnyModel> = {\n [K in keyof ModelRelations<M>]: Cardinality<\n ModelRelations<M>[K]\n > extends \"one\"\n ? ModelRelations<M>[K][\"~\"][\"state\"] extends {\n readonly foreignKey: {\n readonly fields: readonly (infer ScalarKey extends string)[];\n };\n }\n ? [RequiredForeignKeyMembers<M, ScalarKey>] extends [never]\n ? never\n : readonly [\n readonly (SlotMayBeEmpty<M, K, ModelRelations<M>[K]> extends false\n ? ScalarKey\n : RequiredForeignKeyMembers<M, ScalarKey>)[],\n readonly [Extract<K, string>],\n ]\n : SlotMayBeEmpty<M, K, ModelRelations<M>[K]> extends false\n ? readonly [readonly [Extract<K, string>]]\n : never\n : never;\n}[keyof ModelRelations<M>];\ntype OmittedRequiredKeyUnion<TKeys extends readonly string[] | undefined> =\n TKeys extends readonly (infer Key extends string)[] ? Key : never;\ntype ScalarCreateEntries<F extends { scalars: Record<string, unknown> }> =\n V.FromObject<F[\"scalars\"], \"create\">[\"entries\"];\ntype ScalarCreateInputShape<F extends { scalars: Record<string, unknown> }> = {\n [K in keyof ScalarCreateEntries<F>]: V.Input<ScalarCreateEntries<F>[K]>;\n};\ntype RequireScalarKeys<T, K extends string> = {\n [P in keyof T as P extends K ? never : P]?: T[P];\n} & {\n [P in keyof T as P extends K ? P : never]-?: T[P];\n};\ntype RequiredModelScalarKeys<M extends AnyModel> = {\n [K in keyof ModelStateOf<M>[\"scalars\"]]: ModelStateOf<M>[\"scalars\"][K][\"~\"][\"state\"][\"optional\"] extends true\n ? never\n : Extract<K, string>;\n}[keyof ModelStateOf<M>[\"scalars\"]];\ntype RequiredScalarCreateKeys<\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n OmittedRequiredKeys extends string = never,\n> = Extract<\n Exclude<RequiredModelScalarKeys<M>, OmittedRequiredKeys>,\n keyof ScalarCreateEntries<F>\n>;\ntype NestedScalarCreateInput<\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n OmittedRequiredKeys extends string,\n> = RequireScalarKeys<\n ScalarCreateInputShape<F>,\n RequiredScalarCreateKeys<M, F, OmittedRequiredKeys>\n>;\n\ntype NestedRequiredScalarKeys<\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n> = RequiredScalarCreateKeys<M, F, ForeignKeyScalarKeys<M>>;\n\nexport type ScalarCreateSchema<\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n> = V.FromObject<\n F[\"scalars\"],\n \"create\",\n {\n atLeast: ModelRequiredScalarKeys<ModelStateOf<M>[\"shape\"]>[];\n }\n>;\nexport const getScalarCreate = <M extends AnyModel, F extends ScalarSchemas<M>>(\n model: M,\n scalarSchemas: F\n): ScalarCreateSchema<M, F> => {\n const state = model[\"~\"].state;\n const requiredScalars = Object.keys(state.scalars).filter((key) => {\n const scalar = state.shape[key] as Scalar;\n if (scalar[\"~\"][\"state\"][\"optional\"]) {\n return false;\n }\n return true;\n }) as ModelRequiredScalarKeys<ModelStateOf<M>[\"shape\"]>[];\n // `provides` shapes no input type, so it stays out of the options type below.\n const options = { atLeast: requiredScalars, provides: model[\"~\"].names.ts };\n return v.fromObject<\n F[\"scalars\"],\n \"create\",\n {\n atLeast: ModelRequiredScalarKeys<ModelStateOf<M>[\"shape\"]>[];\n }\n >(scalarSchemas.scalars, \"create\", options);\n};\n\n/**\n * Root `createMany` rows: the ORDINARY create data shape (plan §6 J1), minus the\n * one exclusion root `createMany` keeps.\n *\n * The entries are the create schema's, key for key, with ONE substitution — and\n * that substitution is now CARDINALITY-DISPATCHED, inside the `\"createMany\"`\n * family itself (`relations/polymorphic/index.ts`), not here:\n *\n * - a direct polymorphic TO-ONE membership stays at the connect-only union\n * (`relations/polymorphic/create-many.ts`). That is not a leftover. A row\n * whose ONLY relation work is a direct polymorphic `connect` is still\n * bulk-compatible, and the engine groups those connects into one probe per\n * (relation, variant) across the whole payload\n * (`bulk-polymorphic-connect.ts`); plan §5.1 keeps that route's SQL.\n * Widening it to the full `\"create\"` union would make such a row\n * relation-BEARING and route it to the record series a row at a time, which\n * the plan does not ask for.\n * - a polymorphic COLLECTION membership mounts the SAME family its `create`\n * context does (plan §9.6). Its memberships are per-variant member junction\n * rows that cannot exist before the owner row does, so the grouped INSERT\n * could never express them; `routing.ts`'s `relationBearingRow` reads the\n * collection half of the polymorphic set and routes the whole call to the\n * relation-bearing record series.\n *\n * `getBulkCreate` itself is unchanged by that dispatch: it still asks\n * `v.fromObject(fieldSchemas.polymorphic, \"createMany\")` and the family key set\n * is still eight, so this function stays byte-identical across the change.\n *\n * Everything else is `getCreateSchema` verbatim, including WHY: foreign-key\n * columns become optional (a row may spell the edge as a relation instead), and\n * `requiresOneOfKeySets` — the one owner of \"an edge required on create must\n * arrive one way or the other\" — replaces the blunt required-scalar list. The\n * required-polymorphic keys move into that same derivation, so a row that omits\n * one now fails with the create family's sentence rather than a second spelling\n * of it.\n */\nexport type BulkCreateSchema<\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n> = V.Object<\n V.FromObject<F[\"scalars\"], \"create\">[\"entries\"] &\n V.FromObject<F[\"relations\"], \"create\">[\"entries\"] &\n V.FromObject<F[\"polymorphic\"], \"createMany\">[\"entries\"],\n {\n atLeast: NestedRequiredScalarKeys<M, F>[];\n requiresOneOfKeySets: readonly CreateRequirementGroup<M>[];\n }\n>;\n\nexport function getBulkCreate<M extends AnyModel, F extends ScalarSchemas<M>>(\n model: M,\n fieldSchemas: F,\n slots: ReadonlyMap<string, ResolvedSlot>\n): BulkCreateSchema<M, F> {\n const state = model[\"~\"].state;\n const fkFields = getFkFields(state);\n const fkRequirementKeySets = getFkRequirementKeySets(state, slots);\n const requiredScalars = getRequiredCreateScalars(state, fkFields);\n const scalarCreate = v.fromObject<F[\"scalars\"], \"create\">(\n fieldSchemas.scalars,\n \"create\"\n );\n const relationCreate = v.fromObject<F[\"relations\"], \"create\">(\n fieldSchemas.relations,\n \"create\"\n );\n const polymorphicCreateMany = v.fromObject<F[\"polymorphic\"], \"createMany\">(\n fieldSchemas.polymorphic,\n \"createMany\"\n );\n return v.object(\n {\n ...scalarCreate.entries,\n ...relationCreate.entries,\n ...polymorphicCreateMany.entries,\n },\n {\n atLeast: requiredScalars,\n requiresOneOfKeySets: fkRequirementKeySets,\n provides: model[\"~\"].names.ts,\n }\n ) as unknown as BulkCreateSchema<M, F>;\n}\n\n/**\n * Build relation create schema - combines all relation create inputs\n */\nexport type RelationCreateSchema<\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n> = V.FromObject<F[\"relations\"], \"create\">;\nexport const getRelationCreate = <\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n>(\n fieldSchemas: F\n): RelationCreateSchema<M, F> => {\n return v.fromObject<F[\"relations\"], \"create\">(\n fieldSchemas.relations,\n \"create\"\n );\n};\n\n/**\n * The scalar keys this model's own relations store: the local half of every\n * foreign key it owns. A create payload may spell them directly or supply the\n * relation instead, which is what {@link getFkRequirementKeySets} arbitrates.\n */\nfunction getFkFields(state: ModelState): Set<string> {\n const fkFields = new Set<string>();\n for (const relation of Object.values(state.relations)) {\n const foreignKey = relation[\"~\"].state.foreignKey;\n if (!foreignKey) continue;\n for (const fk of foreignKey.fields) {\n fkFields.add(fk);\n }\n }\n return fkFields;\n}\n\n/**\n * The scalar keys a create payload must carry ITSELF: every scalar that is neither\n * optional, nor defaulted, nor an FK column (an FK may arrive through its relation\n * instead, which is what `requiresOneOfKeySets` then arbitrates).\n *\n * ONE derivation with two readers — {@link getCreateSchema} and {@link getBulkCreate}.\n * A root `createMany` row IS the ordinary create data shape, and \"the entries are the\n * create schema's, key for key\" is only true if the two families cannot drift on which\n * scalars are required; a second copy of this filter is exactly how they would.\n */\nfunction getRequiredCreateScalars(\n state: ModelState,\n fkFields: Set<string>\n): string[] {\n return Object.keys(state.scalars).filter(\n (key) => !fkFields.has(key) && mustBeSuppliedOnCreate(state, key)\n );\n}\n\n/**\n * Must a create payload CARRY this scalar? Only when the row cannot produce it:\n * a default (and `.nullable()` installs one) means the statement supplies it.\n *\n * ONE predicate with two readers — the required-scalar list above and the\n * foreign-key requirement groups below. Both name a declared scalar of this\n * model: the first iterates `state.scalars` itself, and FK001 refuses a schema\n * whose `.fields(...)` names anything that is not one, so the lookup cannot\n * miss. Re-checking it here would make this a second owner of that invariant.\n */\nfunction mustBeSuppliedOnCreate(state: ModelState, key: string): boolean {\n const scalarState = state.scalars[key]![\"~\"].state;\n return !(scalarState.hasDefault || scalarState.optional);\n}\n\n/**\n * \"An edge required on create must arrive one way or the other.\"\n *\n * A stored reference contributes a group whenever at least one of its columns\n * must be supplied: an empty relation slot does not make a non-null compound\n * member optional. The payload may still supply that member through the relation\n * key, so the group keeps both alternatives. A carrier without columns contributes\n * a group only when the resolved slot may not be empty.\n *\n * A stored reference whose every local member is defaulted contributes NO\n * group: the statement produces the columns by itself, so there is nothing the\n * payload has to arrive with, and re-adding a requirement the FK exclusion\n * above only removed for convenience would refuse a legal row. A variant\n * singular slot has no spellable columns at all, so its own relation key is\n * the only way it can arrive.\n */\nfunction getFkRequirementKeySets(\n state: ModelState,\n slots: ReadonlyMap<string, ResolvedSlot>\n): readonly (readonly (readonly string[])[])[] {\n const groups: (readonly (readonly string[])[])[] = [];\n\n for (const [relationName, relation] of Object.entries(state.relations)) {\n const relState: RelationState = relation[\"~\"].state;\n if (relState.cardinality !== \"one\") continue;\n const foreignKey = relState.foreignKey;\n if (foreignKey) {\n const requiredMembers = foreignKey.fields.filter((key) =>\n mustBeSuppliedOnCreate(state, key)\n );\n if (requiredMembers.length > 0) {\n const resolved = slots.get(relationName);\n const requiredKeySet =\n resolved && !slotMayBeEmpty(resolved)\n ? foreignKey.fields\n : requiredMembers;\n groups.push([requiredKeySet, [relationName]]);\n }\n continue;\n }\n const resolved = slots.get(relationName);\n if (resolved && !slotMayBeEmpty(resolved)) {\n groups.push([[relationName]]);\n }\n }\n\n return groups;\n}\n\nexport type NestedScalarCreateWithOmittedRequiredKeys<\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n OmittedRequiredKeys extends readonly string[] | undefined,\n> = ObjectSchema<\n ScalarCreateEntries<F>,\n {\n atLeast: RequiredScalarCreateKeys<\n M,\n F,\n OmittedRequiredKeyUnion<OmittedRequiredKeys>\n >[];\n },\n NestedScalarCreateInput<M, F, OmittedRequiredKeyUnion<OmittedRequiredKeys>>\n>;\n\nexport const getNestedScalarCreateWithOmittedRequiredKeys = <\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n const OmittedRequiredKeys extends readonly string[] | undefined,\n>(\n model: M,\n fieldSchemas: F,\n omittedRequiredKeys: OmittedRequiredKeys\n): NestedScalarCreateWithOmittedRequiredKeys<M, F, OmittedRequiredKeys> => {\n const state = model[\"~\"].state;\n const omittedRequiredKeySet = new Set(omittedRequiredKeys ?? []);\n\n // Get required scalar field names, excluding only caller-derived keys.\n const requiredScalars = Object.keys(state.scalars).filter((key) => {\n if (omittedRequiredKeySet.has(key)) return false;\n // Check if scalar has default or is optional\n const scalarState = state.scalars[key]![\"~\"].state;\n return !(scalarState.hasDefault || scalarState.optional);\n }) as RequiredScalarCreateKeys<\n M,\n F,\n OmittedRequiredKeyUnion<OmittedRequiredKeys>\n >[];\n\n const scalarCreate = v.fromObject<F[\"scalars\"], \"create\">(\n fieldSchemas.scalars,\n \"create\"\n );\n\n return v.object(\n {\n ...scalarCreate.entries,\n },\n {\n atLeast: requiredScalars,\n }\n ) as unknown as NestedScalarCreateWithOmittedRequiredKeys<\n M,\n F,\n OmittedRequiredKeys\n >;\n};\n\n/**\n * Build full create schema - scalar + relation creates\n *\n * FK fields (like authorId) are optional because they can be derived from\n * nested relation operations (connect, create).\n */\nexport type CreateSchema<\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n> = V.Object<\n V.FromObject<F[\"scalars\"], \"create\">[\"entries\"] &\n V.FromObject<F[\"relations\"], \"create\">[\"entries\"] &\n V.FromObject<F[\"polymorphic\"], \"create\">[\"entries\"],\n {\n atLeast: NestedRequiredScalarKeys<M, F>[];\n requiresOneOfKeySets: readonly CreateRequirementGroup<M>[];\n }\n>;\nexport const getCreateSchema = <M extends AnyModel, F extends ScalarSchemas<M>>(\n model: M,\n fieldSchemas: F,\n slots: ReadonlyMap<string, ResolvedSlot>\n): CreateSchema<M, F> => {\n const state = model[\"~\"].state;\n // Identify FK fields - these should be optional when using connect/create\n const fkFields = getFkFields(state);\n const fkRequirementKeySets = getFkRequirementKeySets(state, slots);\n\n // Get required scalar field names (non-FK fields without defaults or optional)\n const requiredScalars = getRequiredCreateScalars(\n state,\n fkFields\n ) as ModelRequiredScalarKeys<ModelStateOf<M>[\"shape\"]>[];\n\n // Build scalar schema with FK fields as optional\n const scalarCreate = v.fromObject<F[\"scalars\"], \"create\">(\n fieldSchemas.scalars,\n \"create\"\n );\n\n // Relation create is optional (you don't have to use connect/create)\n const relationCreate = v.fromObject<F[\"relations\"], \"create\">(\n fieldSchemas.relations,\n \"create\"\n );\n const polymorphicCreate = v.fromObject<F[\"polymorphic\"], \"create\">(\n fieldSchemas.polymorphic,\n \"create\"\n );\n\n return v.object(\n {\n ...scalarCreate.entries,\n ...relationCreate.entries,\n ...polymorphicCreate.entries,\n },\n {\n atLeast: requiredScalars as NestedRequiredScalarKeys<M, F>[],\n requiresOneOfKeySets:\n fkRequirementKeySets as unknown as readonly CreateRequirementGroup<M>[],\n provides: model[\"~\"].names.ts,\n }\n );\n};\n","import type { AnyModel } from \"@schema/model\";\nimport type { ObjectSchema } from \"@validation/primitives/object\";\nimport v, { type V } from \"../../primitives/v\";\nimport type { ScalarSchemas } from \"../index\";\n\ntype ModelStateOf<M extends AnyModel> = M[\"~\"][\"state\"];\ntype UniqueScalarSchemas<M extends AnyModel, F extends ScalarSchemas<M>> = Pick<\n F[\"scalars\"],\n Extract<keyof F[\"scalars\"], keyof ModelStateOf<M>[\"uniques\"]>\n>;\n\nconst getUniqueScalarSchemas = <M extends AnyModel, F extends ScalarSchemas<M>>(\n model: M,\n fieldSchemas: F\n): UniqueScalarSchemas<M, F> => {\n const uniqueSchemas: Record<PropertyKey, unknown> = {};\n for (const key of Object.keys(model[\"~\"].state.uniques) as Array<\n keyof F[\"scalars\"]\n >) {\n const schema = fieldSchemas.scalars[key];\n if (schema) {\n uniqueSchemas[key] = schema;\n }\n }\n return uniqueSchemas as unknown as UniqueScalarSchemas<M, F>;\n};\n\nexport type ScalarFilterSchema<\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n> = V.FromObject<F[\"scalars\"], \"filter\">;\nexport const getScalarFilter = <M extends AnyModel, F extends ScalarSchemas<M>>(\n fieldSchemas: F\n): ScalarFilterSchema<M, F> => {\n return v.fromObject(fieldSchemas.scalars, \"filter\");\n};\n\nexport type UniqueFilterSchema<\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n> = V.FromObject<UniqueScalarSchemas<M, F>, \"base\">;\nexport const getUniqueFilter = <M extends AnyModel, F extends ScalarSchemas<M>>(\n model: M,\n fieldSchemas: F\n): UniqueFilterSchema<M, F> => {\n return v.fromObject(getUniqueScalarSchemas(model, fieldSchemas), \"base\");\n};\n\nexport type RelationFilterSchema<\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n> = V.FromObject<F[\"relations\"], \"filter\">;\n\nexport const getRelationFilter = <\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n>(\n fieldSchemas: F\n): RelationFilterSchema<M, F> => {\n return v.fromObject(fieldSchemas.relations, \"filter\");\n};\n\n/**\n * Build compound constraint filter schema\n * Creates an object schema where each compound key maps to an optional object of field base schemas\n */\n\ntype CompoundConstraintEntries<M extends AnyModel> =\n (ModelStateOf<M>[\"compoundId\"] extends Record<string, ObjectSchema<any>>\n ? ModelStateOf<M>[\"compoundId\"]\n : Record<never, never>) &\n (ModelStateOf<M>[\"compoundUniques\"] extends Record<\n string,\n ObjectSchema<any>\n >\n ? ModelStateOf<M>[\"compoundUniques\"]\n : Record<never, never>);\n\nexport type CompoundConstraintFilterSchema<M extends AnyModel> = ObjectSchema<\n CompoundConstraintEntries<M>\n>;\n\n/**\n * One compound selector, with each member taken from the FIELD's own schema.\n *\n * `Model.id([...])` / `.unique([...])` snapshot `state.base` at declaration\n * time, which is the PRE-DOMAIN schema: a `.uuid()` member was validated as a\n * plain string there, so an out-of-domain value crossed the args boundary and\n * an alias was never folded — one row addressed by two cache keys. The member\n * names and their order are the declaration's; what each member ADMITS is the\n * field's, which is where an identifier domain (declared or derived) lives.\n */\n/** The per-field schemas a compound member is rebuilt from. */\ntype CompoundMemberSources = Readonly<\n Record<string, { readonly base: V.Schema } | undefined>\n>;\n\n/** One rebuilt selector: the same shape `Model.id([...])` stored, member for member. */\ntype CompoundSelectorSchema = V.Object<\n Record<string, V.Schema>,\n { readonly partial: false }\n>;\n\nconst compoundSelector = (\n declared: ObjectSchema<Record<string, V.Schema>>,\n scalars: CompoundMemberSources\n): CompoundSelectorSchema => {\n const members: Record<string, V.Schema> = {};\n for (const field of Object.keys(declared.entries)) {\n // Every member IS a model scalar: `Model.id([...])` refuses a name that is\n // not one, and the registry builds one schema per model scalar. There is\n // no absent case to fall back for.\n members[field] = scalars[field]!.base;\n }\n return v.object(members, { partial: false });\n};\n\nconst compoundSelectors = (\n declared: Record<string, ObjectSchema<Record<string, V.Schema>>> | undefined,\n scalars: CompoundMemberSources\n): Record<string, CompoundSelectorSchema> => {\n const selectors: Record<string, CompoundSelectorSchema> = {};\n for (const [name, entry] of Object.entries(declared ?? {})) {\n selectors[name] = compoundSelector(entry, scalars);\n }\n return selectors;\n};\n\nexport const getCompoundConstraintFilter = <\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n>(\n model: M,\n fieldSchemas: F\n): CompoundConstraintFilterSchema<M> => {\n const state = model[\"~\"].state;\n if (!(state.compoundUniques || state.compoundId)) {\n return v.object({}) as CompoundConstraintFilterSchema<M>;\n }\n const scalars = fieldSchemas.scalars as CompoundMemberSources;\n return v.object({\n ...compoundSelectors(state.compoundUniques, scalars),\n ...compoundSelectors(state.compoundId, scalars),\n }) as CompoundConstraintFilterSchema<M>;\n};\n\nexport type CompoundIdFilterSchema<M extends AnyModel> = V.Object<\n ModelStateOf<M>[\"compoundId\"]\n>;\nexport const getCompoundIdFilter = <\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n>(\n model: M,\n fieldSchemas: F\n): CompoundIdFilterSchema<M> => {\n const state = model[\"~\"].state;\n if (!state.compoundId) {\n return v.object({});\n }\n return v.object(\n compoundSelectors(state.compoundId, fieldSchemas.scalars)\n ) as CompoundIdFilterSchema<M>;\n};\n","// Select and include schema factories\n\nimport type { AnyModel } from \"@schema/model\";\nimport type { StringKeyOf } from \"@schema/model/helper\";\nimport type { AnyRelation } from \"@schema/relation\";\nimport type { ScalarState } from \"@schema/scalars\";\nimport v, { type V } from \"../../primitives/v\";\nimport { isRecord } from \"../../value-guards\";\nimport type { ScalarSchemas } from \"../index\";\nimport {\n type ProjectableScalarKeys,\n projectableScalarNames,\n} from \"./projection\";\n\n// =============================================================================\n// SELECT SCHEMA\n// =============================================================================\n\n/**\n * Build select schema - boolean selection for each scalar field, nested select for relations\n */\ntype ModelStateOf<M extends AnyModel> = M[\"~\"][\"state\"];\ntype ModelScalars<M extends AnyModel> = ModelStateOf<M>[\"scalars\"];\ntype ModelScalarKey<M extends AnyModel> = StringKeyOf<ModelScalars<M>>;\ntype ScalarStateOf<F> = F extends { \"~\": { state: infer S } }\n ? S extends ScalarState\n ? S\n : never\n : never;\ntype AnyVectorScalarKeys<M extends AnyModel> = {\n [K in keyof ModelScalars<M>]: ScalarStateOf<\n ModelScalars<M>[K]\n >[\"type\"] extends \"vector\"\n ? K extends string\n ? K\n : never\n : never;\n}[keyof ModelScalars<M>];\ntype AnyPointScalarKeys<M extends AnyModel> = {\n [K in keyof ModelScalars<M>]: ScalarStateOf<\n ModelScalars<M>[K]\n >[\"type\"] extends \"point\"\n ? K extends string\n ? K\n : never\n : never;\n}[keyof ModelScalars<M>];\n/**\n * Both halves of the select schema are keyed on {@link ProjectableScalarKeys},\n * so a model-level `.omit()`-ed scalar has no `select` entry at all: naming it\n * is an \"Unknown key\" parse failure rather than a way around the schema's own\n * exclusion. See `projection.ts` for why that layer is hard and the other two\n * are not.\n */\ntype VectorScalarKeys<M extends AnyModel> = Extract<\n ProjectableScalarKeys<M>,\n AnyVectorScalarKeys<M>\n>;\ntype PointScalarKeys<M extends AnyModel> = Extract<\n ProjectableScalarKeys<M>,\n AnyPointScalarKeys<M>\n>;\ntype PlainScalarKeys<M extends AnyModel> = Exclude<\n ProjectableScalarKeys<M>,\n AnyVectorScalarKeys<M> | AnyPointScalarKeys<M>\n>;\n\nconst scalarSelectSchema = v.boolean({ optional: true });\nconst vectorDistanceMetricSchema = v.enum([\"l2\", \"cosine\"]);\n\n// =============================================================================\n// _count SCHEMA (object form + Prisma's `_count: true` shorthand)\n// =============================================================================\n\n/** The desugared shorthand: one `true` entry per counted relation. */\ntype CountAllSelection = Record<string, true>;\n\n/** Both relation namespaces a `_count` (and an `include`) reaches across. */\ntype RelationSchemaBundle = {\n relations: Record<string, any>;\n polymorphic: Record<string, any>;\n};\n\n/**\n * `_count` accepts either Prisma's shorthand `true` or the explicit\n * `{ select: { <relation>: true | { where } } }` object. The shorthand is\n * desugared here, so everything downstream (query engine, result parser) only\n * ever sees the object form.\n */\nexport type CountSchema<F extends RelationSchemaBundle> = V.Union<\n readonly [\n V.Coerce<V.Literal<true>, { select: CountAllSelection }>,\n V.Object<\n {\n select: V.Object<\n V.FromObject<\n F[\"relations\"],\n \"countFilter\",\n { optional: true }\n >[\"entries\"] &\n V.FromObject<\n F[\"polymorphic\"],\n \"countFilter\",\n { optional: true }\n >[\"entries\"],\n { optional: true }\n >;\n },\n { optional: true }\n >,\n ]\n>;\n\n/**\n * Prisma's `_count: true` means \"count every LIST relation of this model\": the\n * generated `<Model>CountOutputType` contains only to-many (collection) fields\n * — a to-one relation never appears there. viborm's\n * explicit object form is a deliberate superset (name a to-one relation and it\n * will be counted), but the shorthand mirrors Prisma's rule exactly.\n *\n * A model with no to-many relations expands to `{ select: {} }` — exactly what\n * the explicit empty object form does today (no relation-count key in the\n * result). Prisma generates no `_count` at all for such a model, so there is no\n * Prisma behavior to mirror; the pinned contract is that equivalence.\n */\nconst toManyRelationNames = (model: AnyModel): string[] => {\n const relations: Record<string, AnyRelation> = model[\"~\"].state.relations;\n const names: string[] = [];\n // ONE cardinality read across both target domains. A variant COLLECTION is a\n // list relation by every reading that matters here — it holds many rows and\n // it has a count — and a singular slot of either domain is excluded for the\n // same reason: Prisma's rule is about lists, not about how the far side is\n // addressed.\n for (const name of Object.keys(relations)) {\n if (relations[name]![\"~\"].state.cardinality === \"many\") {\n names.push(name);\n }\n }\n return names;\n};\n\nconst getCountSchema = <F extends RelationSchemaBundle>(\n model: AnyModel,\n schemas: F\n): CountSchema<F> => {\n const countAllNames = toManyRelationNames(model);\n const relationEntries = v.fromObject<\n F[\"relations\"],\n \"countFilter\",\n { optional: true }\n >(schemas.relations, \"countFilter\", { optional: true });\n const polymorphicEntries = v.fromObject<\n F[\"polymorphic\"],\n \"countFilter\",\n { optional: true }\n >(schemas.polymorphic, \"countFilter\", { optional: true });\n\n return v.union([\n // A fresh object per parse — the desugared value is handed to the engine\n // and must never alias a schema-level singleton.\n v.coerce(v.literal(true), (): { select: CountAllSelection } => {\n const select: CountAllSelection = {};\n for (const name of countAllNames) {\n select[name] = true;\n }\n return { select };\n }),\n v.object(\n {\n select: v.object(\n { ...relationEntries.entries, ...polymorphicEntries.entries },\n { optional: true }\n ),\n },\n { optional: true }\n ),\n ]) as CountSchema<F>;\n};\n\nexport const vectorDistanceSelectSchema = v.object(\n {\n _distance: v.object(\n {\n to: v.array(v.number()),\n metric: vectorDistanceMetricSchema,\n },\n { partial: false }\n ),\n },\n { partial: false }\n);\n\nexport const pointDistanceSelectSchema = v.object(\n {\n _distance: v.object(\n {\n to: v.point(),\n },\n { partial: false }\n ),\n },\n { partial: false }\n);\n\nconst vectorScalarSelectSchema = v.union([\n scalarSelectSchema,\n vectorDistanceSelectSchema,\n]);\ntype VectorScalarSelectSchema = typeof vectorScalarSelectSchema;\nconst pointScalarSelectSchema = v.union([\n scalarSelectSchema,\n pointDistanceSelectSchema,\n]);\ntype PointScalarSelectSchema = typeof pointScalarSelectSchema;\n\nconst selects = (value: unknown): boolean =>\n value !== undefined && value !== false;\n\n/**\n * A written `select` names what the row carries, so one that names nothing\n * (`{}`, only `false`, or a `_count` that counts no relation, as `_count: true`\n * does on a model with no to-many relation) is a caller mistake, refused at its\n * own path. Leaving `select` out is how a caller asks for the default row.\n */\nconst requireSelectedField = (\n select: Record<string, unknown>\n): string | undefined =>\n Object.entries(select).some(([key, value]) =>\n key === \"_count\"\n ? isRecord(value) && Object.values(new Object(value.select)).some(selects)\n : selects(value)\n )\n ? undefined\n : \"select needs at least one truthy value; leave it out to return the default row.\";\n\n/** The refusal every written `select` carries ({@link requireSelectedField}). */\ntype SelectRefusal = { readonly refuse: typeof requireSelectedField };\n\nexport type SelectSchema<\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n> = V.Object<\n V.FromKeys<PlainScalarKeys<M>[], typeof scalarSelectSchema>[\"entries\"] &\n V.FromKeys<VectorScalarKeys<M>[], VectorScalarSelectSchema>[\"entries\"] &\n V.FromKeys<PointScalarKeys<M>[], PointScalarSelectSchema>[\"entries\"] &\n V.FromObject<F[\"relations\"], \"select\">[\"entries\"] &\n V.FromObject<F[\"polymorphic\"], \"select\">[\"entries\"] & {\n _count: CountSchema<F>;\n },\n SelectRefusal\n>;\n\n/** The scalar half of a select schema, shared by both factories below. */\nconst getScalarSelectEntries = <M extends AnyModel>(model: M) => {\n // Scalar fields: boolean selection, plus vector-only computed distance select\n const vectorScalarKeys: VectorScalarKeys<M>[] = [];\n const pointScalarKeys: PointScalarKeys<M>[] = [];\n const plainScalarKeys: PlainScalarKeys<M>[] = [];\n\n const scalarKeys = projectableScalarNames(model) as ModelScalarKey<M>[];\n for (const fieldName of scalarKeys) {\n const scalar = model[\"~\"].state.scalars[fieldName];\n if (scalar[\"~\"].state.type === \"vector\") {\n vectorScalarKeys.push(fieldName as VectorScalarKeys<M>);\n continue;\n }\n if (scalar[\"~\"].state.type === \"point\") {\n pointScalarKeys.push(fieldName as PointScalarKeys<M>);\n continue;\n }\n plainScalarKeys.push(fieldName as PlainScalarKeys<M>);\n }\n\n const scalarEntries = v.fromKeys<\n PlainScalarKeys<M>[],\n typeof scalarSelectSchema\n >(plainScalarKeys, scalarSelectSchema);\n const vectorEntries = v.fromKeys<\n VectorScalarKeys<M>[],\n typeof vectorScalarSelectSchema\n >(vectorScalarKeys, vectorScalarSelectSchema);\n\n const pointEntries = v.fromKeys<\n PointScalarKeys<M>[],\n typeof pointScalarSelectSchema\n >(pointScalarKeys, pointScalarSelectSchema);\n\n return {\n ...scalarEntries.entries,\n ...vectorEntries.entries,\n ...pointEntries.entries,\n };\n};\n\n/**\n * The SCALAR-ONLY projection: {@link SelectSchema} without relation keys and\n * without `_count`.\n *\n * This is the projection of a bulk write (`createMany` / `updateMany` /\n * `deleteMany` with a `select`). Those rows come out of the write statement's\n * `RETURNING` clause — an expression list with no table alias to correlate\n * against — so a relation subquery embedded there binds its outer column\n * reference by NAME and is silently captured by the inner table whenever the two\n * share a column name. The observable result was wrong data, not an error: a\n * to-many relation always came back `[]`, and a self-referencing to-one came\n * back `null`, while the identical projection through `findMany` returned the\n * real rows. Refusing the key is the fail-closed answer; read relations in a\n * separate query, which is what the underlying implementation would have to do\n * anyway.\n *\n * Prisma divergence, deliberate: Prisma's `createManyAndReturn` /\n * `updateManyAndReturn` DO accept relations here — its generator emits dedicated\n * `<Model>SelectCreateManyAndReturn` / `<Model>IncludeCreateManyAndReturn` types\n * (prisma 6.8.2, `prisma-client/generator-build`, `Model.argsTypes`).\n */\nexport type ScalarSelectSchema<M extends AnyModel> = V.Object<\n V.FromKeys<PlainScalarKeys<M>[], typeof scalarSelectSchema>[\"entries\"] &\n V.FromKeys<VectorScalarKeys<M>[], VectorScalarSelectSchema>[\"entries\"] &\n V.FromKeys<PointScalarKeys<M>[], PointScalarSelectSchema>[\"entries\"],\n SelectRefusal\n>;\n\nexport const getScalarSelectSchema = <M extends AnyModel>(\n model: M\n): ScalarSelectSchema<M> =>\n v.object(getScalarSelectEntries(model), { refuse: requireSelectedField });\n\nexport const getSelectSchema = <M extends AnyModel, F extends ScalarSchemas<M>>(\n model: M,\n fieldSchemas: F\n): SelectSchema<M, F> => {\n const scalarEntries = getScalarSelectEntries(model);\n\n // Relations: use relation's select schema (supports boolean or nested)\n const relationEntries = v.fromObject<F[\"relations\"], \"select\">(\n fieldSchemas.relations,\n \"select\"\n );\n const polymorphicEntries = v.fromObject<F[\"polymorphic\"], \"select\">(\n fieldSchemas.polymorphic,\n \"select\"\n );\n\n return v.object(\n {\n ...scalarEntries,\n ...relationEntries.entries,\n ...polymorphicEntries.entries,\n // Accepts `true` (count every to-many relation) or the explicit\n // { select: { <relation>: true | { where } } } object.\n _count: getCountSchema(model, fieldSchemas),\n },\n { refuse: requireSelectedField }\n );\n};\n\n// =============================================================================\n// INCLUDE SCHEMA\n// =============================================================================\n\n/**\n * Build include schema - nested include for each relation\n */\n\nexport type IncludeSchema<F extends RelationSchemaBundle> = V.Object<\n V.FromObject<F[\"relations\"], \"include\", { optional: true }>[\"entries\"] & {\n _count: CountSchema<F>;\n } & V.FromObject<F[\"polymorphic\"], \"include\", { optional: true }>[\"entries\"]\n>;\n\nexport const getIncludeSchema = <F extends RelationSchemaBundle>(\n model: AnyModel,\n schemas: F\n): IncludeSchema<F> => {\n // Relations: use relation's include schema (supports boolean or nested with where/orderBy/etc.)\n const relationEntries = v.fromObject<\n F[\"relations\"],\n \"include\",\n { optional: true }\n >(schemas.relations, \"include\", {\n optional: true,\n });\n const polymorphicEntries = v.fromObject<\n F[\"polymorphic\"],\n \"include\",\n { optional: true }\n >(schemas.polymorphic, \"include\", {\n optional: true,\n });\n\n return v.object({\n ...relationEntries.entries,\n ...polymorphicEntries.entries,\n // Prisma supports `_count` under include as well as select — both the\n // `true` shorthand and the explicit object; mirror the select-schema entry\n // (the query engine already builds _count in include position).\n _count: getCountSchema(model, schemas),\n });\n};\n","// Update schema factories\n\nimport type { AnyModel } from \"@schema/model\";\nimport v, { type V } from \"../../primitives/v\";\nimport type { ScalarSchemas } from \"../index\";\n\n// =============================================================================\n// SCALAR UPDATE\n// =============================================================================\n\n/**\n * Scalar update input: every scalar that HAS an update schema (all optional).\n *\n * The one reader of `fieldSchemas.scalars` for update input — `getUpdateSchema`\n * and every nested update surface (they project `core.update`) extend it. A\n * `.now()` creation timestamp has no update schema (`getScalarsSchemas`), so\n * `fromObject` gives it no runtime entry, the strict object refuses the key as\n * `Unknown key` however it is spelled — `undefined` included — and its\n * type-level entry is `never`, which refuses the key in a non-fresh payload too.\n */\nexport type ScalarUpdateSchema<\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n> = V.FromObject<F[\"scalars\"], \"update\">;\nexport const getScalarUpdate = <M extends AnyModel, F extends ScalarSchemas<M>>(\n fieldSchemas: F\n): ScalarUpdateSchema<M, F> => {\n return v.fromObject<F[\"scalars\"], \"update\">(fieldSchemas.scalars, \"update\");\n};\n\n// =============================================================================\n// RELATION UPDATE\n// =============================================================================\n\n/**\n * Build relation update schema - combines all relation update inputs\n */\nexport type RelationUpdateSchema<\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n> = V.FromObject<F[\"relations\"], \"update\">;\nexport const getRelationUpdate = <\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n>(\n fieldSchemas: F\n): RelationUpdateSchema<M, F> => {\n return v.fromObject<F[\"relations\"], \"update\">(\n fieldSchemas.relations,\n \"update\"\n );\n};\n\n// =============================================================================\n// FULL UPDATE SCHEMA\n// =============================================================================\n\n/**\n * Build full update schema - scalar + relation updates (all optional)\n */\nexport type UpdateSchema<\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n> = V.Object<\n ScalarUpdateSchema<M, F>[\"entries\"] &\n RelationUpdateSchema<M, F>[\"entries\"] &\n V.FromObject<F[\"polymorphic\"], \"update\">[\"entries\"]\n>;\nexport const getUpdateSchema = <M extends AnyModel, F extends ScalarSchemas<M>>(\n fieldSchemas: F\n): UpdateSchema<M, F> => {\n const relationUpdate = v.fromObject<F[\"relations\"], \"update\">(\n fieldSchemas.relations,\n \"update\"\n );\n const polymorphicUpdate = v.fromObject<F[\"polymorphic\"], \"update\">(\n fieldSchemas.polymorphic,\n \"update\"\n );\n return getScalarUpdate<M, F>(fieldSchemas)\n .extend(relationUpdate.entries)\n .extend(polymorphicUpdate.entries);\n};\n","import type { AnyModel } from \"@schema/model\";\nimport type { DecimalListScalarKeys } from \"@schema/model/helper\";\nimport { entriesFromObject } from \"@validation/primitives/from-object\";\nimport { scopeOperands } from \"@validation/primitives/operand\";\nimport v, { type V } from \"../../primitives/v\";\nimport type { ScalarSchemas } from \"../index\";\nimport {\n type CompoundConstraintFilterSchema,\n getCompoundConstraintFilter,\n getUniqueFilter,\n type UniqueFilterSchema,\n} from \"./filter\";\n\n// =============================================================================\n// WHERE SCHEMA\n// =============================================================================\n\n/**\n * Build full where schema - scalar + relation filters + AND/OR/NOT\n * Uses thunks for recursive self-references\n */\nexport type WhereSchemaBase<\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n> = V.Object<\n V.FromObject<F[\"scalars\"], \"filter\">[\"entries\"] &\n V.FromObject<F[\"relations\"], \"filter\">[\"entries\"] &\n V.FromObject<F[\"polymorphic\"], \"filter\">[\"entries\"]\n>;\n\nexport type WhereSchema<\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n> = V.Object<\n {\n AND: () => V.Optional<\n V.Union<readonly [WhereSchema<M, F>, V.Array<WhereSchema<M, F>>]>\n >;\n OR: () => V.Optional<V.Array<WhereSchema<M, F>>>;\n NOT: () => V.Optional<\n V.Union<readonly [WhereSchema<M, F>, V.Array<WhereSchema<M, F>>]>\n >;\n } & WhereSchemaBase<M, F>[\"entries\"]\n>;\n\nexport const getWhereSchema = <M extends AnyModel, F extends ScalarSchemas<M>>(\n model: M,\n fieldSchemas: F\n): WhereSchema<M, F> => {\n // Build scalar and relation filter entries\n\n const scalarFilter = entriesFromObject<F[\"scalars\"], \"filter\">(\n fieldSchemas.scalars,\n \"filter\"\n );\n const relationFilter = entriesFromObject<F[\"relations\"], \"filter\">(\n fieldSchemas.relations,\n \"filter\"\n );\n const polymorphicFilter = entriesFromObject<F[\"polymorphic\"], \"filter\">(\n fieldSchemas.polymorphic,\n \"filter\"\n );\n\n // Create the recursive where schema with AND/OR/NOT using thunks\n const whereSchema: WhereSchema<M, F> = v.object({\n // Recursive AND/OR/NOT using thunks\n AND: () => v.optional(v.union([whereSchema, v.array(whereSchema)])),\n OR: () => v.optional(v.array(whereSchema)),\n NOT: () => v.optional(v.union([whereSchema, v.array(whereSchema)])),\n ...scalarFilter,\n ...relationFilter,\n ...polymorphicFilter,\n });\n\n // A `where` is the operand-callback scope boundary: `ctx.fields` inside it\n // names THIS model's columns. A nested relation filter embeds the TARGET\n // model's `where`, which carries its own boundary, so depth re-scopes for\n // free and pops back on the way out (see `primitives/operand.ts`).\n return scopeOperands(whereSchema, model);\n};\n\n// =============================================================================\n// WHERE UNIQUE SCHEMA\n// =============================================================================\n\n/**\n * Build whereUnique schema - unique fields + compound constraints\n * Combines single-field uniques with compound ID and compound uniques\n */\ntype WhereUniqueIdentityEntries<\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n> = UniqueFilterSchema<M, F>[\"entries\"] &\n CompoundConstraintFilterSchema<M>[\"entries\"];\n\ntype DecimalListUniqueRefusalSchema = ReturnType<typeof v.refused>;\n\ntype DecimalListWhereUniqueEntries<M extends AnyModel> = V.FromKeys<\n DecimalListScalarKeys<M[\"~\"][\"state\"][\"scalars\"]>[],\n DecimalListUniqueRefusalSchema\n>[\"entries\"];\n\ntype WhereUniqueEntries<\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n> = WhereUniqueIdentityEntries<M, F> & DecimalListWhereUniqueEntries<M>;\n\ntype WhereUniqueKey<M extends AnyModel, F extends ScalarSchemas<M>> = Extract<\n keyof WhereUniqueIdentityEntries<M, F>,\n string\n>;\n\ntype WhereUniqueOptions<M extends AnyModel, F extends ScalarSchemas<M>> = {\n nonEmpty: true;\n requiresOneOf: readonly [WhereUniqueKey<M, F>[]];\n};\n\nexport type WhereUniqueSchema<\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n> = V.Object<WhereUniqueEntries<M, F>, WhereUniqueOptions<M, F>>;\n\nfunction getDecimalListWhereUniqueEntries<M extends AnyModel>(\n model: M\n): V.FromKeys<\n DecimalListScalarKeys<M[\"~\"][\"state\"][\"scalars\"]>[],\n DecimalListUniqueRefusalSchema\n>;\nfunction getDecimalListWhereUniqueEntries(model: AnyModel) {\n const keys: string[] = [];\n for (const name of Object.keys(model[\"~\"].state.scalars)) {\n const scalar = model[\"~\"].state.scalars[name];\n const state = scalar[\"~\"].state;\n if (state.type === \"decimal\" && state.array === true) keys.push(name);\n }\n return v.fromKeys(\n keys,\n v.refused(\"A decimal list cannot be used as a unique selector or cursor.\")\n );\n}\n\nexport const getWhereUniqueSchema = <\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n>(\n model: M,\n fieldSchemas: F\n): WhereUniqueSchema<M, F> => {\n // Single-field unique constraints\n const uniqueFilter = getUniqueFilter(model, fieldSchemas);\n\n // Add compound constraints (ID + uniques) using the compound filter helpers\n const compoundConstraintFilter = getCompoundConstraintFilter(\n model,\n fieldSchemas\n );\n\n const identities: WhereUniqueIdentityEntries<M, F> = {\n ...uniqueFilter.entries,\n ...compoundConstraintFilter.entries,\n };\n const keys = Object.keys(identities) as WhereUniqueKey<M, F>[];\n const decimalListRefusals = getDecimalListWhereUniqueEntries(model);\n const entries: WhereUniqueEntries<M, F> = {\n ...identities,\n ...decimalListRefusals.entries,\n };\n\n return v.object(entries, {\n nonEmpty: true,\n requiresOneOf: [keys],\n });\n};\n\n// =============================================================================\n// EXTENDED WHERE UNIQUE SCHEMA (Prisma >= 4.5)\n// =============================================================================\n\n/**\n * The merged entry set: the ordinary `where` MINUS the names the discriminators\n * take back, PLUS the discriminators. Named once so the local that builds it can\n * be annotated with the same type `WhereUniqueExtendedSchema` declares.\n */\ntype WhereUniqueExtendedEntries<\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n> = Omit<WhereSchema<M, F>[\"entries\"], keyof WhereUniqueIdentityEntries<M, F>> &\n WhereUniqueIdentityEntries<M, F>;\n\n/**\n * Build the EXTENDED whereUnique schema — Prisma >= 4.5's `AtLeast<…>` shape:\n * the unique discriminators (single field or complete compound) PLUS the model's\n * ordinary `where` — non-unique scalar filters, RELATION filters, and `AND` /\n * `OR` / `NOT` — with **at least one** discriminator still required\n * (`requiresOneOf`, which the type level applies as a union of \"this key is\n * required\" shapes — Prisma's `AtLeast`, for free).\n *\n * SCOPE. This schema is the `where` of the TOP-LEVEL `findUnique` /\n * `findUniqueOrThrow` / `update` / `delete` / `upsert`, and of the NESTED `update` /\n * `upsert` / `delete` TARGET selectors too. Those nested positions were once strict\n * because \"a nested target is located by PK boundaries the extra filters would\n * collide with\"; a nested locate now RETURNS its primary key however the row was\n * named, so there is no collision left to avoid. Prisma's nested selectors are\n * unique-only there, which makes this a deliberate SUPERSET (capability matrix,\n * §write).\n *\n * Still strict, and for reasons that are their own, not leftovers:\n * · `connect` / `disconnect` / `set` / `connectOrCreate.where` — these NAME a row\n * to link, they do not locate one to mutate. Prisma parity, and nothing in the\n * engine reads a filter half there.\n * · `cursor` — its meaning is an exact row address in an ordering, not a predicate.\n *\n * The filter half stays inert to everything compile-time wherever this schema is\n * used: `getWhereUniqueEntries` returns the discriminator alone, so pins, `racePin`\n * attribution and identity cannot see it by construction. See\n * `query-engine-v2/shared.ts` `uniqueSelectorConjuncts` for the one place the two\n * halves are recombined, and `docs/content/docs/client/*`.\n *\n * RELATION FILTERS. They were refused here until the write half learned\n * to name its own table. A unique `where`'s filter half compiles into the\n * UPDATE/DELETE as well as the locate (batch mode addresses the row by the\n * original `where`, so guard and write pin one row), and there the target\n * carries no alias: a correlated `EXISTS` built against bare column names binds\n * the OUTER column to the RELATED table whenever both models carry that name —\n * silently, on every dialect. `buildUpdate` / `buildDelete` now qualify the\n * unique `where` by the target's table name and declare it as the\n * `mutationTable`, which is exactly what `buildUpdateMany` / `buildDeleteMany`\n * have always done: the correlation is unambiguous, and MySQL's refusal to read\n * the mutated table in a subquery (error 1093) is answered by the same\n * derived-table wrapper, engaged only where the relation actually reads that\n * table (a self-relation, or a self-M2M's target side).\n *\n * A unique field keeps its BARE-VALUE schema at the top level (Prisma spells\n * `{ email: \"a@b\" }`, never `{ email: { equals: … } }`, in the unique position),\n * so the discriminator entries are applied LAST and win over the filter entry of\n * the same name. Inside `AND` / `OR` / `NOT` the same field is an ordinary\n * filter, exactly as in Prisma.\n */\nexport type WhereUniqueExtendedSchema<\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n> = V.Object<WhereUniqueExtendedEntries<M, F>, WhereUniqueOptions<M, F>>;\n\nexport const getWhereUniqueExtendedSchema = <\n M extends AnyModel,\n F extends ScalarSchemas<M>,\n>(\n model: M,\n fieldSchemas: F\n): WhereUniqueExtendedSchema<M, F> => {\n const uniqueFilter = getUniqueFilter(model, fieldSchemas);\n const compoundConstraintFilter = getCompoundConstraintFilter(\n model,\n fieldSchemas\n );\n const where = getWhereSchema<M, F>(model, fieldSchemas);\n\n const discriminators: WhereUniqueIdentityEntries<M, F> = {\n ...uniqueFilter.entries,\n ...compoundConstraintFilter.entries,\n };\n const keys = Object.keys(discriminators) as WhereUniqueKey<M, F>[];\n // Annotated, not asserted, like `discriminators` above and the sibling\n // `getWhereUniqueSchema`: the annotation checks the FILTER half of the merge\n // (dropping `...where.entries` is a compile error; under an `as` it was not).\n // It cannot check the discriminator half — those entries are optional in the\n // ordinary `where` they overwrite, so their absence is assignable either way.\n const entries: WhereUniqueExtendedEntries<M, F> = {\n ...where.entries,\n ...discriminators,\n };\n\n // The filter portion of an extended unique `where` is an ordinary filter, so\n // it opens the same operand callbacks and needs the same scope. (The\n // discriminator entries are BARE values — no operand position there.)\n return scopeOperands(\n v.object(entries, {\n nonEmpty: true,\n requiresOneOf: [keys],\n }),\n model\n );\n};\n","// Core schema factories - re-exports\n\n// Create exports\nexport {\n type BulkCreateSchema,\n type CreateSchema,\n getBulkCreate,\n getCreateSchema,\n getNestedScalarCreateWithOmittedRequiredKeys,\n getRelationCreate,\n getScalarCreate,\n type NestedScalarCreateWithOmittedRequiredKeys,\n type RelationCreateSchema,\n type ScalarCreateSchema,\n} from \"./create\";\n// Filter exports\nexport {\n type CompoundConstraintFilterSchema,\n type CompoundIdFilterSchema,\n getCompoundConstraintFilter,\n getCompoundIdFilter,\n getRelationFilter,\n getScalarFilter,\n getUniqueFilter,\n type RelationFilterSchema,\n type ScalarFilterSchema,\n type UniqueFilterSchema,\n} from \"./filter\";\n// OrderBy exports\nexport {\n getOrderBySchema,\n type OrderBySchema,\n sortOrderSchema,\n} from \"./orderby\";\n// Select/Include exports\nexport {\n getIncludeSchema,\n getScalarSelectSchema,\n getSelectSchema,\n type IncludeSchema,\n type ScalarSelectSchema,\n type SelectSchema,\n} from \"./select\";\n// Update exports\nexport {\n getRelationUpdate,\n getScalarUpdate,\n getUpdateSchema,\n type RelationUpdateSchema,\n type ScalarUpdateSchema,\n type UpdateSchema,\n} from \"./update\";\n// Where exports\nexport {\n getWhereSchema,\n getWhereUniqueExtendedSchema,\n getWhereUniqueSchema,\n type WhereSchema,\n type WhereUniqueExtendedSchema,\n type WhereUniqueSchema,\n} from \"./where\";\n\n// =============================================================================\n// CORE SCHEMAS TYPE\n// =============================================================================\n\nimport type { AnyModel } from \"@schema/model\";\nimport type { ResolvedSlot } from \"@schema/validation/relation-resolution\";\nimport { lazyRecord } from \"../../lazy\";\nimport {\n getOmitSchema,\n getUpsertProjectionSchema,\n type OmitSchema,\n type UpsertProjectionSchema,\n} from \"../args/omit\";\nimport type { ScalarSchemas } from \"../index\";\nimport {\n type BulkCreateSchema,\n type CreateSchema,\n getBulkCreate,\n getCreateSchema,\n getRelationCreate,\n getScalarCreate,\n type RelationCreateSchema,\n type ScalarCreateSchema,\n} from \"./create\";\nimport {\n type CompoundConstraintFilterSchema,\n type CompoundIdFilterSchema,\n getCompoundConstraintFilter,\n getCompoundIdFilter,\n getRelationFilter,\n getScalarFilter,\n getUniqueFilter,\n type RelationFilterSchema,\n type ScalarFilterSchema,\n type UniqueFilterSchema,\n} from \"./filter\";\nimport { getOrderBySchema, type OrderBySchema } from \"./orderby\";\nimport {\n getIncludeSchema,\n getScalarSelectSchema,\n getSelectSchema,\n type IncludeSchema,\n type ScalarSelectSchema,\n type SelectSchema,\n} from \"./select\";\nimport {\n getRelationUpdate,\n getScalarUpdate,\n getUpdateSchema,\n type RelationUpdateSchema,\n type ScalarUpdateSchema,\n type UpdateSchema,\n} from \"./update\";\nimport {\n getWhereSchema,\n getWhereUniqueExtendedSchema,\n getWhereUniqueSchema,\n type WhereSchema,\n type WhereUniqueExtendedSchema,\n type WhereUniqueSchema,\n} from \"./where\";\n\n/**\n * Type representing all core schemas for a model.\n * Used by args factories to reference schema types.\n */\nexport type CoreSchemas<M extends AnyModel, F extends ScalarSchemas<M>> = {\n scalarFilter: ScalarFilterSchema<M, F>;\n uniqueFilter: UniqueFilterSchema<M, F>;\n relationFilter: RelationFilterSchema<M, F>;\n compoundIdFilter: CompoundIdFilterSchema<M>;\n compoundConstraintFilter: CompoundConstraintFilterSchema<M>;\n scalarCreate: ScalarCreateSchema<M, F>;\n bulkCreate: BulkCreateSchema<M, F>;\n relationCreate: RelationCreateSchema<M, F>;\n scalarUpdate: ScalarUpdateSchema<M, F>;\n relationUpdate: RelationUpdateSchema<M, F>;\n where: WhereSchema<M, F>;\n /**\n * The STRICT unique selector: unique discriminators only. Used by `cursor` and\n * by every NESTED relation-write target selector (`connect`, `disconnect`,\n * `set`, nested `update`/`delete`/`upsert` `where`), which keep it deliberately.\n */\n whereUnique: WhereUniqueSchema<M, F>;\n /**\n * The EXTENDED unique selector (Prisma >= 4.5): discriminators PLUS non-unique\n * scalar filters and AND/OR/NOT. Used ONLY by the TOP-LEVEL `findUnique` /\n * `findUniqueOrThrow` / `update` / `delete` / `upsert` `where`.\n */\n whereUniqueExtended: WhereUniqueExtendedSchema<M, F>;\n create: CreateSchema<M, F>;\n update: UpdateSchema<M, F>;\n select: SelectSchema<M, F>;\n /**\n * The negative projection (see `src/validation/model/args/omit.ts`). Keyed on\n * the scalars a query may project, so a model-level `.omit()`-ed field cannot\n * even be named here.\n */\n omit: OmitSchema<M>;\n /**\n * `{ select?, include?, omit? }` on its own, for `upsert` — the one operation\n * with no whole-args parse to desugar `omit` inside of.\n */\n upsertProjection: UpsertProjectionSchema<M, F>;\n /** The scalar-only projection used by the bulk writes (see `ScalarSelectSchema`). */\n scalarSelect: ScalarSelectSchema<M>;\n include: IncludeSchema<F>;\n orderBy: OrderBySchema<M, F>;\n};\n\nexport const getCoreSchemas = <M extends AnyModel, F extends ScalarSchemas<M>>(\n model: M,\n fieldSchemas: F,\n slots: ReadonlyMap<string, ResolvedSlot>\n): CoreSchemas<M, F> => {\n // Each core schema is built on first access and memoized. Consumers only ever\n // read individual keys (e.g. `core.where`, `core.whereUnique`), so a query\n // pays only for the schemas its operation actually references.\n const core: CoreSchemas<M, F> = lazyRecord<CoreSchemas<M, F>>({\n scalarFilter: () => getScalarFilter<M, F>(fieldSchemas),\n uniqueFilter: () => getUniqueFilter(model, fieldSchemas),\n relationFilter: () => getRelationFilter<M, F>(fieldSchemas),\n compoundIdFilter: () => getCompoundIdFilter(model, fieldSchemas),\n compoundConstraintFilter: () =>\n getCompoundConstraintFilter(model, fieldSchemas),\n scalarCreate: () => getScalarCreate(model, fieldSchemas),\n bulkCreate: () => getBulkCreate(model, fieldSchemas, slots),\n relationCreate: () => getRelationCreate<M, F>(fieldSchemas),\n scalarUpdate: () => getScalarUpdate<M, F>(fieldSchemas),\n relationUpdate: () => getRelationUpdate<M, F>(fieldSchemas),\n where: () => getWhereSchema<M, F>(model, fieldSchemas),\n whereUnique: () => getWhereUniqueSchema(model, fieldSchemas),\n whereUniqueExtended: () =>\n getWhereUniqueExtendedSchema(model, fieldSchemas),\n create: () => getCreateSchema(model, fieldSchemas, slots),\n update: () => getUpdateSchema<M, F>(fieldSchemas),\n select: () => getSelectSchema(model, fieldSchemas),\n omit: () => getOmitSchema(model),\n // Self-referential, and safe: `lazyRecord` builds each entry on first\n // access, long after `core` is bound.\n upsertProjection: () => getUpsertProjectionSchema(model, core),\n scalarSelect: () => getScalarSelectSchema(model),\n include: () => getIncludeSchema(model, fieldSchemas),\n orderBy: () => getOrderBySchema<M, F>(model, fieldSchemas),\n });\n return core;\n};\n","import type { AnyModel } from \"@schema/model\";\nimport type { ResolvedSlot } from \"@schema/validation/relation-resolution\";\nimport type { GetRelationsSchemas } from \"@validation/relations\";\nimport type { GetPolymorphicRelationsSchemas } from \"@validation/relations/polymorphic\";\nimport type { GetScalarsSchemas } from \"@validation/scalars\";\nimport { type ArgsSchemas, getArgsSchemas } from \"./args\";\nimport { type CoreSchemas, getCoreSchemas } from \"./core\";\n\nexport type { ArgsSchemas } from \"./args\";\nexport type { CoreSchemas } from \"./core\";\n\nexport type ScalarSchemas<M extends AnyModel> = {\n scalars: GetScalarsSchemas<M>;\n relations: GetRelationsSchemas<M>;\n polymorphic: GetPolymorphicRelationsSchemas<M>;\n};\n\ntype SchemaInput<S> = S extends { \" vibInferred\": [infer Input, unknown] }\n ? Input\n : never;\n\ntype SchemaOutput<S> = S extends { \" vibInferred\": [unknown, infer Output] }\n ? Output\n : never;\n\nexport type ModelSchemas<\n M extends AnyModel,\n F extends ScalarSchemas<M> = ScalarSchemas<M>,\n> = {\n core: CoreSchemas<M, F>;\n args: ArgsSchemas<M, F>;\n scalars: F[\"scalars\"];\n relations: F[\"relations\"];\n polymorphic: F[\"polymorphic\"];\n};\n\nexport type ModelStateSchemas<M extends AnyModel> = ModelSchemas<\n M,\n ScalarSchemas<M>\n>;\n\nexport type ModelArgsSchemas<M extends AnyModel> = ModelStateSchemas<M>[\"args\"];\n\nexport type ModelCoreSchemas<M extends AnyModel> = ModelStateSchemas<M>[\"core\"];\n\nexport type ModelOperationInput<\n M extends AnyModel,\n Operation extends keyof ModelArgsSchemas<M>,\n> = SchemaInput<ModelArgsSchemas<M>[Operation]>;\n\nexport type ModelOperationOutput<\n M extends AnyModel,\n Operation extends keyof ModelArgsSchemas<M>,\n> = SchemaOutput<ModelArgsSchemas<M>[Operation]>;\n\nexport type ModelCoreInput<\n M extends AnyModel,\n Schema extends keyof ModelCoreSchemas<M>,\n> = SchemaInput<ModelCoreSchemas<M>[Schema]>;\n\nexport type ModelRelationNestedInput<\n M extends AnyModel,\n Schema extends keyof ModelCoreSchemas<M>,\n> = ModelCoreInput<M, Schema>;\n\nexport const getModelSchemas = <\n M extends AnyModel,\n F extends ScalarSchemas<M> = ScalarSchemas<M>,\n>(\n model: M,\n schemas: F,\n slots: ReadonlyMap<string, ResolvedSlot>\n): ModelSchemas<M, F> => {\n const core = getCoreSchemas(model, schemas, slots);\n const args = getArgsSchemas(model, schemas, core);\n return {\n core,\n args,\n scalars: schemas.scalars,\n relations: schemas.relations,\n polymorphic: schemas.polymorphic,\n };\n};\n","// Count Filter Schema\n// Schema for _count filtering - accepts true or { where: ... }\n\nimport type { RelationState } from \"@schema/relation/types\";\nimport v, { type V } from \"../primitives/v\";\nimport type { GetTargetSchemas, SchemaGetter } from \"./helpers\";\n\n/**\n * Count filter schema: true or { where: <filter> }\n *\n * Used in _count select to filter which related records to count.\n * - true: count all related records\n * - { where: ... }: count related records matching the filter\n */\nexport type CountFilterSchema<S extends RelationState> = V.Union<\n readonly [\n V.Literal<true>,\n V.Object<{\n where: () => GetTargetSchemas<S>[\"core\"][\"where\"];\n }>,\n ]\n>;\nexport const countFilterFactory = <\n S extends RelationState,\n T extends SchemaGetter<S>,\n>(\n state: S,\n targetSchemas: T\n): CountFilterSchema<S> => {\n return v.union([\n v.literal(true),\n v.object({\n where: () => targetSchemas().core.where,\n }),\n ]);\n};\n","// Nested relation-data projection — ONE owner, both levels.\n//\n// A nested payload never writes into the target model's own `core.create` /\n// `core.update`: it writes into the projection of those schemas that the ENCLOSING\n// relation leaves for the caller. Two edges answer \"what does the enclosing step\n// already own\" differently — an inverse stored reference owns the target's\n// foreign-key COLUMNS, a variant inverse owns the target's CARRIER RELATION KEY —\n// and until this module existed each answer had its own verb factories.\n//\n// This is the one place that difference is decided, and it is decided from ONE\n// input: the membership of the asking slot. The type half reads the static\n// projection (`@schema/relation/static-membership`), the runtime half reads the\n// resolved edge. Neither scans the target model's declarations, invokes a getter,\n// or reconstructs a binding.\n//\n// The verb factories (`toOne/toMany` × `create/update`) consume the projection\n// blindly, so a surface that used to be a clone is now the same factory with a\n// different projection.\n\nimport type { AnyModel } from \"@schema/model\";\nimport type {\n DerivedNestedKeys,\n StaticResolvedMembership,\n} from \"@schema/relation/static-membership\";\nimport type { RelationState } from \"@schema/relation/types\";\nimport type { ResolvedSlot } from \"@schema/validation/relation-resolution\";\nimport { type V, v } from \"../primitives/v\";\nimport type { GetTargetSchemas, SchemaGetter } from \"./helpers\";\n\n// =============================================================================\n// WHAT THE ENCLOSING STEP OWNS — one question, asked once per nesting context\n// =============================================================================\n\n/**\n * How the enclosing step records this membership on the TARGET row.\n *\n * - `columns` — an inverse-held foreign key. The keys are writable scalars.\n * - `carrier` — a variant carrier. The one key is that carrier's relation field.\n * - `none` — the asking slot holds the membership itself, or the graph is\n * unproven. Nothing on the target row is derived, so nothing is omitted.\n */\ntype OwnershipKind<\n Source extends AnyModel,\n Key,\n S extends RelationState,\n> = StaticResolvedMembership<Source, Key, S> extends infer Membership\n ? Membership extends {\n readonly kind: \"foreignKey\";\n readonly owner: \"inverse\";\n }\n ? \"columns\"\n : Membership extends { readonly kind: \"variantInverse\" }\n ? \"carrier\"\n : \"none\"\n : never;\n\n/**\n * The keys of the TARGET's schemas that the enclosing step already owns.\n *\n * Narrowed to keys the schema actually HAS, because that intersection is what\n * `V.Omit` removes: a derived column the target's schema does not expose (a\n * model-level `.omit()`, a generated column) is already absent, and naming it\n * would make the omission list a claim about a key that is not there.\n */\ntype OwnedTargetKeys<\n Source extends AnyModel,\n Key,\n S extends RelationState,\n Entries,\n> = Extract<DerivedNestedKeys<Source, Key, S>, keyof Entries>;\n\ntype CreateWithOwnedKeysOmitted<\n Source extends AnyModel,\n Key,\n S extends RelationState,\n> = V.Omit<\n GetTargetSchemas<S>[\"core\"][\"create\"],\n readonly [\n OwnedTargetKeys<\n Source,\n Key,\n S,\n GetTargetSchemas<S>[\"core\"][\"create\"][\"entries\"]\n >,\n ]\n>;\n\ntype UpdateWithOwnedKeysOmitted<\n Source extends AnyModel,\n Key,\n S extends RelationState,\n> = V.Omit<\n GetTargetSchemas<S>[\"core\"][\"update\"],\n readonly [\n OwnedTargetKeys<\n Source,\n Key,\n S,\n GetTargetSchemas<S>[\"core\"][\"update\"][\"entries\"]\n >,\n ]\n>;\n\n// =============================================================================\n// THE TWO RE-ENTRY EXCEPTIONS\n// =============================================================================\n//\n// An omitted key may be spelled again only where re-entering it cannot create a\n// SECOND PROVENANCE for the membership the enclosing step has already bound.\n// That single rule produces exactly two cells, one per ownership kind, and they\n// are on opposite verbs:\n//\n// - `columns` on a CREATE root: the engine ABSORBS an agreeing owned foreign\n// key (`RelationUpsertPart.withoutAgreeingOwnedFk`), and only a create root\n// whose own key is spelled has a value to agree with. A carrier relation key\n// is not a column and has no value to agree with, so the exception does not\n// apply to it.\n// - `carrier` on an UPDATE root's SELECTED arm: the engine has already located\n// that exact incoming parent and carries its row continuity, so re-entering\n// the carrier relation is a second write to a bound parent, not a second\n// claim about which parent. A writable foreign-key COLUMN in the same place\n// could repoint the row, so it stays omitted.\n//\n// Both are retained behavior. Neither direction may be \"unified\" into the other.\n\n/** The update arm of a to-many `upsert` under an UPDATE root. */\ntype SelectedUpsertUpdate<\n Source extends AnyModel,\n Key,\n S extends RelationState,\n> = OwnershipKind<Source, Key, S> extends \"carrier\"\n ? GetTargetSchemas<S>[\"core\"][\"update\"]\n : UpdateWithOwnedKeysOmitted<Source, Key, S>;\n\n/** The update arm of a to-many `upsert` under a CREATE root. */\ntype CreateUpsertUpdate<\n Source extends AnyModel,\n Key,\n S extends RelationState,\n> = OwnershipKind<Source, Key, S> extends \"columns\"\n ? GetTargetSchemas<S>[\"core\"][\"update\"]\n : UpdateWithOwnedKeysOmitted<Source, Key, S>;\n\n// =============================================================================\n// THE PROJECTION — one alias, one instantiation per relation\n// =============================================================================\n\n/**\n * Every projected fact of one nesting context, computed ONCE per\n * `<Source, Key, S>`.\n *\n * Deliberately a single record rather than one conditional per verb: proving\n * the pairing through the schema graph is the expensive question, and a\n * per-verb spelling would instantiate it six times for every relation in the\n * schema.\n */\nexport interface NestedRelationDataProjection<\n Source extends AnyModel,\n Key,\n S extends RelationState,\n> {\n create: CreateWithOwnedKeysOmitted<Source, Key, S>;\n update: UpdateWithOwnedKeysOmitted<Source, Key, S>;\n selectedUpsertUpdate: SelectedUpsertUpdate<Source, Key, S>;\n createUpsertUpdate: CreateUpsertUpdate<Source, Key, S>;\n}\n\n/** The target schema a nested `create` payload writes into. */\nexport type ProjectedNestedCreate<\n Source extends AnyModel,\n Key,\n S extends RelationState,\n> = NestedRelationDataProjection<Source, Key, S>[\"create\"];\n\n/** The target schema nested UPDATE data writes into. */\nexport type ProjectedNestedUpdate<\n Source extends AnyModel,\n Key,\n S extends RelationState,\n> = NestedRelationDataProjection<Source, Key, S>[\"update\"];\n\n/** See the re-entry rule above. */\nexport type ProjectedSelectedUpsertUpdate<\n Source extends AnyModel,\n Key,\n S extends RelationState,\n> = NestedRelationDataProjection<Source, Key, S>[\"selectedUpsertUpdate\"];\n\n/** See the re-entry rule above. */\nexport type ProjectedCreateUpsertUpdate<\n Source extends AnyModel,\n Key,\n S extends RelationState,\n> = NestedRelationDataProjection<Source, Key, S>[\"createUpsertUpdate\"];\n\n// =============================================================================\n// RUNTIME\n// =============================================================================\n\ntype AnyObjectSchema = V.Object<any, any>;\n\n/** The runtime twin of {@link NestedRelationDataProjection}. */\nexport interface NestedRelationDataSchemas {\n /** `v.omit(core.create, <what the enclosing edge owns>)`. */\n readonly getCreateSchema: () => AnyObjectSchema;\n /** The same omission applied to nested UPDATE data. */\n readonly getUpdateSchema: () => AnyObjectSchema;\n /** See {@link ProjectedSelectedUpsertUpdate}. */\n readonly getSelectedUpsertUpdateSchema: () => AnyObjectSchema;\n /** See {@link ProjectedCreateUpsertUpdate}. */\n readonly getCreateUpsertUpdateSchema: () => AnyObjectSchema;\n}\n\ntype Ownership = {\n readonly kind: \"columns\" | \"carrier\" | \"none\";\n readonly keys: readonly string[];\n};\n\nconst NOTHING_OWNED: Ownership = { kind: \"none\", keys: [] };\n\n/** `(model, field)` is the whole contextual identity of a slot. */\nconst isAskingSlot = (\n resolved: ResolvedSlot,\n candidate: { readonly source: AnyModel; readonly field: string }\n): boolean =>\n candidate.source === resolved.slot.source &&\n candidate.field === resolved.slot.field;\n\n/**\n * The runtime twin of {@link OwnershipKind} + {@link DerivedNestedKeys}, read\n * from the resolved edge.\n *\n * An asking-held foreign key names columns on the SOURCE row, which a nested\n * TARGET payload could not spell anyway, so it owns nothing here — that is the\n * exact-omission rule (§11.2.21), not an oversight: a self parent/children pair\n * omits `parentId` from `children.create` and from nothing else.\n */\nconst ownedByEnclosingStep = (resolved: ResolvedSlot): Ownership => {\n const edge = resolved.edge;\n if (edge.kind === \"foreignKey\") {\n return isAskingSlot(resolved, edge.owner)\n ? NOTHING_OWNED\n : {\n kind: \"columns\",\n keys: edge.reference.members.map((member) => member.foreignField),\n };\n }\n if (\n edge.kind === \"variantRowCarrier\" ||\n edge.kind === \"variantJunctionCarrier\"\n ) {\n return isAskingSlot(resolved, edge.carrier)\n ? NOTHING_OWNED\n : { kind: \"carrier\", keys: [edge.carrier.field] };\n }\n // A junction row records the membership; no key on either row does.\n return NOTHING_OWNED;\n};\n\n/**\n * Build the projection for one nesting context.\n *\n * LAZINESS IS A NON-TERMINATION HAZARD, not a performance note. Every schema this\n * returns is a THUNK, because materializing the target model's `core.create` while\n * the enclosing model's schemas are still under construction never terminates for a\n * self-referential relation. Call it from inside a verb factory (each of which is\n * itself reached through `v.lazy`), never from `getRelationSchemas`: the pin is\n * `polymorphic.core.test.ts` \"inverse topology stays lazy until create validation\",\n * which counts ZERO target-getter invocations after `core.create` is merely READ.\n */\nexport const nestedRelationDataProjection = <\n S extends RelationState,\n T extends SchemaGetter<S>,\n>(\n resolved: ResolvedSlot,\n targetSchemas: T\n): NestedRelationDataSchemas => {\n const owned = ownedByEnclosingStep(resolved);\n const bareUpdate = () =>\n targetSchemas().core.update as unknown as AnyObjectSchema;\n const getCreateSchema = () =>\n v.omit(\n targetSchemas().core.create as unknown as AnyObjectSchema,\n owned.keys\n ) as unknown as AnyObjectSchema;\n const getUpdateSchema = () =>\n v.omit(bareUpdate(), owned.keys) as unknown as AnyObjectSchema;\n return {\n getCreateSchema,\n getUpdateSchema,\n getSelectedUpsertUpdateSchema:\n owned.kind === \"carrier\" ? bareUpdate : getUpdateSchema,\n getCreateUpsertUpdateSchema:\n owned.kind === \"columns\" ? bareUpdate : getUpdateSchema,\n };\n};\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { ObjectOptions, ObjectSchema } from \"../primitives/object\";\nimport v from \"../primitives/v\";\nimport type { InferInput, InferOutput } from \"../types\";\nimport { isRecord } from \"../value-guards\";\n\ntype MutationKey<T> = Extract<keyof T, string>;\n\ntype InactiveMutationValue<T> = false extends T ? false : never;\n\ntype EmptyMutation<T> = {\n [Key in MutationKey<T>]?: InactiveMutationValue<T[Key]>;\n};\n\ntype MutationArm<T, Active extends MutationKey<T>> = {\n [Key in Active]-?: Exclude<T[Key], undefined>;\n} & {\n [Key in Exclude<MutationKey<T>, Active>]?: InactiveMutationValue<T[Key]>;\n};\n\n/**\n * EXACTLY one active intent — the arms without the empty one.\n *\n * This is the whole type-level content of the `exactlyOne` composition mode. A\n * surface that carries its target discriminator INSIDE each verb payload (the direct\n * polymorphic edge) has no coherent reading of an empty payload and no reading at all\n * of two intents, because the storage pair it writes is atomic: one `(type, id)`.\n */\ntype ExactlyOneMutation<T> = {\n [Key in MutationKey<T>]: MutationArm<T, Key>;\n}[MutationKey<T>];\n\ntype AtMostOneMutation<T> = EmptyMutation<T> | ExactlyOneMutation<T>;\n\n/**\n * ONE composition, spelled as the arm that activates every key it names — and `never`\n * when the surface does not own ALL of them.\n *\n * That collapse is the only gate the composition alternatives need besides the\n * direction flag: the create root owns neither `update` nor a vacate key, an inverse\n * whose foreign key cannot be nulled owns no `disconnect`, and a required relation owns\n * neither vacate. Each of those surfaces silently loses exactly the alternatives it\n * cannot spell, with no second conditional and no per-surface list.\n */\ntype ComposedMutation<T, Keys extends string> = Exclude<\n Keys,\n MutationKey<T>\n> extends never\n ? MutationArm<T, Extract<Keys, MutationKey<T>>>\n : never;\n\ntype VacateThenSupplyMutation<\n T,\n Vacate extends string,\n Supply extends string,\n> = ComposedMutation<T, Vacate | Supply>;\n\ntype SupplyThenModifyMutation<T, Supply extends string> = ComposedMutation<\n T,\n Supply | \"update\"\n>;\n\ntype VacateSupplyThenModifyMutation<\n T,\n Vacate extends string,\n Supply extends string,\n> = ComposedMutation<T, Vacate | Supply | \"update\">;\n\n/**\n * The five accepted replacements: one vacate, then one supplier. `delete` beside\n * `connectOrCreate` is the sixth pair the accepted set has never contained, kept out\n * deliberately rather than by omission — it is pinned as a refusal in\n * `parity-h-to-one-lattice.test.ts` and in `vacate-then-supply-behavior.ts`, and the\n * engine's own positional `isVacateThenSupply` excludes the same pair.\n */\ntype ReplacementMutation<T> =\n | VacateThenSupplyMutation<T, \"disconnect\", \"connectOrCreate\">\n | VacateThenSupplyMutation<T, \"disconnect\", \"connect\">\n | VacateThenSupplyMutation<T, \"disconnect\", \"create\">\n | VacateThenSupplyMutation<T, \"delete\", \"connect\">\n | VacateThenSupplyMutation<T, \"delete\", \"create\">;\n\n/** The same five replacements, each composed with a modify of the supplied target. */\ntype ReplacementThenModifyMutation<T> =\n | VacateSupplyThenModifyMutation<T, \"disconnect\", \"connectOrCreate\">\n | VacateSupplyThenModifyMutation<T, \"disconnect\", \"connect\">\n | VacateSupplyThenModifyMutation<T, \"disconnect\", \"create\">\n | VacateSupplyThenModifyMutation<T, \"delete\", \"connect\">\n | VacateSupplyThenModifyMutation<T, \"delete\", \"create\">;\n\n/**\n * A child-held edge composes freely: the child row carries the foreign key, so the\n * supplier's own identity is what a following `update` addresses, and a vacate before\n * it touches a DIFFERENT row.\n */\ntype ChildHeldCompositionMutation<T> =\n | ReplacementMutation<T>\n | SupplyThenModifyMutation<T, \"create\">\n | SupplyThenModifyMutation<T, \"connect\">\n | SupplyThenModifyMutation<T, \"connectOrCreate\">\n | ReplacementThenModifyMutation<T>;\n\n/**\n * A parent-held edge composes into ONE final foreign-key value on the record's own\n * root statement, which is what limits the set: a vacate and a supplier fold to the\n * supplier's value, and `connect` is the one supplier whose target is already\n * identified when the modify has to correlate. `create` and `connectOrCreate` beside\n * `update` would have to modify a row whose identity the same statement is still\n * producing; that composition is refused here rather than half-supported.\n *\n * The CHILD-held direction admits those same two shapes and EXECUTES them: the\n * residual lift's Package E gave the engine a membership-capture continuation\n * (the supplier runs, the one row carrying the supplied membership is captured, and\n * the retained update source compiles against that selected target), so the engine\n * sentence that used to refuse them is gone. The two directions still differ because\n * only this one can be seen from the payload alone — a parent-held supplier and its\n * modify fold into the record's own root statement, so \"the identity is not there\n * yet\" is a property of the shape, not of how the engine locates a selected record.\n * Anyone widening this direction should read the child-held continuation owner\n * before assuming the two agree.\n */\ntype ParentHeldCompositionMutation<T> =\n | ReplacementMutation<T>\n | SupplyThenModifyMutation<T, \"connect\">;\n\n/**\n * Which composition rule this surface publishes. `lattice` is the accepted-set rule\n * every ordinary and inverse to-one edge uses; `exactlyOne` is the strictly narrower\n * one — no empty payload, no composition — and it exists because a direct\n * polymorphic payload has neither reading. There is no third rule and no way to\n * spell one: a surface picks one of these two.\n */\nexport type ToOneMutationComposition = \"lattice\" | \"exactlyOne\";\n\ntype ToOneMutationInputValue<\n T,\n ChildHeld extends boolean,\n Composition extends ToOneMutationComposition,\n> = T extends object\n ? Composition extends \"exactlyOne\"\n ? ExactlyOneMutation<T>\n :\n | AtMostOneMutation<T>\n | (ChildHeld extends true\n ? ChildHeldCompositionMutation<T>\n : ParentHeldCompositionMutation<T>)\n : T;\n\ntype BaseObjectSchema<\n Entries,\n Options extends ObjectOptions | undefined,\n> = ObjectSchema<Entries, Options>;\n\ntype ToOneMutationInput<\n Entries,\n Options extends ObjectOptions | undefined,\n ChildHeld extends boolean,\n Composition extends ToOneMutationComposition,\n> = ToOneMutationInputValue<\n InferInput<BaseObjectSchema<Entries, Options>>,\n ChildHeld,\n Composition\n>;\n\ntype ToOneMutationOutput<\n Entries,\n Options extends ObjectOptions | undefined,\n> = InferOutput<BaseObjectSchema<Entries, Options>>;\n\n/** A to-one mutation object with its allowed active-operation lattice. */\nexport interface ToOneMutationSchema<\n Entries extends object,\n Options extends ObjectOptions | undefined = undefined,\n ChildHeld extends boolean = false,\n Composition extends ToOneMutationComposition = \"lattice\",\n> extends ObjectSchema<\n Entries,\n Options,\n ToOneMutationInput<Entries, Options, ChildHeld, Composition>,\n ToOneMutationOutput<Entries, Options>\n > {}\n\nconst VACATE_KINDS: ReadonlySet<string> = new Set([\"disconnect\", \"delete\"]);\n\nconst SUPPLY_KINDS: ReadonlySet<string> = new Set([\n \"create\",\n \"connect\",\n \"connectOrCreate\",\n]);\n\n/**\n * The runtime half of the lattice the types above describe, decided from the ACTIVE\n * keys alone. Each refusal below is one of the plan's continuing restrictions:\n * supplier plus supplier (two identities, one slot), `upsert` beside another target\n * intent (its own two arms already decide the target), a vacate with no supplier to\n * follow it, and two vacates.\n */\nfunction isAcceptedComposition(\n active: readonly string[],\n childHeld: boolean\n): boolean {\n if (active.length <= 1) return true;\n\n let vacate: string | undefined;\n let supply: string | undefined;\n let modify = false;\n for (const key of active) {\n if (VACATE_KINDS.has(key)) {\n if (vacate !== undefined) return false;\n vacate = key;\n } else if (SUPPLY_KINDS.has(key)) {\n if (supply !== undefined) return false;\n supply = key;\n } else if (key === \"update\") {\n // One key carries the modify, so a second one is not a shape this can see.\n modify = true;\n } else {\n return false;\n }\n }\n\n if (supply === undefined) return false;\n if (vacate === \"delete\" && supply === \"connectOrCreate\") return false;\n if (!modify) return true;\n return childHeld || (vacate === undefined && supply === \"connect\");\n}\n\nconst unsupportedCombination = (active: readonly string[]) => ({\n issues: [\n {\n message: `Unsupported to-one operation combination: ${active.join(\", \")}`,\n },\n ],\n});\n\nfunction enforceCompositionLattice<Output>(\n result: StandardSchemaV1.Result<Output>,\n operationKeys: readonly string[],\n childHeld: boolean,\n exactlyOne: boolean\n): StandardSchemaV1.Result<Output> {\n if (result.issues) return result;\n const output = result.value;\n if (!isRecord(output)) return result;\n\n const active: string[] = [];\n for (const key of operationKeys) {\n const value = output[key];\n if (value !== undefined && value !== false) active.push(key);\n }\n if (exactlyOne) {\n if (active.length === 1) return result;\n // Two intents is the SAME fact the lattice already has a sentence for, so it\n // keeps that sentence. Zero is the fact only this mode can state.\n return active.length === 0\n ? {\n issues: [\n {\n message: `Missing to-one operation: expected exactly one of ${operationKeys.join(\", \")}`,\n },\n ],\n }\n : unsupportedCombination(active);\n }\n if (isAcceptedComposition(active, childHeld)) return result;\n return unsupportedCombination(active);\n}\n\n/**\n * Validate the underlying object once, then enforce to-one operation compatibility on\n * its canonical output. `false` remains a no-op for boolean mutation verbs.\n *\n * `childHeld` names the relation DIRECTION, because the two directions accept\n * different compositions (see the two `…CompositionMutation` types). The create root\n * passes no value for it: that surface owns no vacate and no `update`, so no\n * composition is spellable there and the flag has nothing to decide.\n *\n * `composition` names the RULE. `exactlyOne` narrows this owner for the direct\n * polymorphic edge, whose payload writes one atomic `(type, id)` pair and carries the\n * discriminator inside each verb: an empty payload names no target for a membership\n * the model may require, and two intents name two. Both were refused before this mode\n * existed — the first by a union that had no empty member, the second by hand-spelled\n * exclusivity — and both are refused here now, in this owner's voice.\n *\n * The counting validator is built HERE, before the schema object exists, and no\n * property of a constructed schema is ever redefined (validation Rule 4). That is not\n * a style preference: `v.union` and the lazy records capture a member's\n * `~standard.validate` at construction, so a validator patched onto a schema after the\n * fact is a validator some readers hold the un-patched version of.\n */\nexport function toOneMutationSchema<\n Entries extends object,\n const Options extends ObjectOptions | undefined = undefined,\n const ChildHeld extends boolean = false,\n const Composition extends ToOneMutationComposition = \"lattice\",\n>(\n entries: Entries,\n options?: Options,\n childHeld?: ChildHeld,\n composition?: Composition\n): ToOneMutationSchema<Entries, Options, ChildHeld, Composition> {\n const base = v.object(entries, options);\n const operationKeys = Object.keys(entries);\n const baseValidate = base[\"~standard\"].validate;\n const isChildHeld = childHeld === true;\n const isExactlyOne = composition === \"exactlyOne\";\n const validate: typeof baseValidate = (value, validationOptions) =>\n enforceCompositionLattice(\n baseValidate(value, validationOptions),\n operationKeys,\n isChildHeld,\n isExactlyOne\n );\n\n const schema = {\n ...base,\n \"~standard\": {\n version: 1 as const,\n vendor: \"viborm\" as const,\n validate,\n // The lattice is not expressible in JSON Schema and never was, so the converter\n // is the base object's — reached through it rather than rebuilt, which keeps it\n // lazy for a self-referential relation.\n get jsonSchema() {\n return base[\"~standard\"].jsonSchema;\n },\n },\n };\n Object.defineProperty(schema, \" vibInferred\", {\n value: undefined,\n enumerable: false,\n });\n\n return schema as ToOneMutationSchema<\n Entries,\n Options,\n ChildHeld,\n Composition\n >;\n}\n","// Relation Create Schemas\n\nimport type { AnyModel } from \"@schema/model\";\nimport type { RelationState } from \"@schema/relation/types\";\nimport type { ResolvedSlot } from \"@schema/validation/relation-resolution\";\nimport { refuseDefaultOnlySkipDuplicates } from \"@validation/model/args/mutation\";\nimport { type V, v } from \"../primitives/v\";\nimport type { GetTargetSchemas, SchemaGetter } from \"./helpers\";\nimport {\n nestedRelationDataProjection,\n type ProjectedCreateUpsertUpdate,\n type ProjectedNestedCreate,\n} from \"./nested-data-projection\";\nimport {\n type ToOneMutationSchema,\n toOneMutationSchema,\n} from \"./to-one-mutation-schema\";\n\n// =============================================================================\n// CREATE SCHEMA TYPES (exported for consumer use)\n// =============================================================================\n\ntype AvailableNestedCreateManySchema<\n Source extends AnyModel,\n Key,\n S extends RelationState,\n> = V.Object<\n {\n data: () => V.Array<ProjectedNestedCreate<Source, Key, S>>;\n skipDuplicates: V.Boolean<{ optional: true }>;\n },\n { atLeast: [\"data\"] }\n>;\n\nexport type NestedCreateManySchema<\n Source extends AnyModel,\n Key,\n S extends RelationState,\n> = AvailableNestedCreateManySchema<Source, Key, S>;\n\n// =============================================================================\n// CREATE FACTORY IMPLEMENTATIONS\n// =============================================================================\n\n/**\n * To-one create: { create?, connect?, connectOrCreate? }\n */\ntype ToOneCreateEntries<\n Source extends AnyModel,\n Key,\n S extends RelationState,\n> = {\n create: () => ProjectedNestedCreate<Source, Key, S>;\n connect: () => GetTargetSchemas<S>[\"core\"][\"whereUnique\"];\n connectOrCreate: V.Object<\n {\n where: () => GetTargetSchemas<S>[\"core\"][\"whereUnique\"];\n create: () => ProjectedNestedCreate<Source, Key, S>;\n },\n { partial: false }\n >;\n};\n\nexport type ToOneCreateSchema<\n Source extends AnyModel,\n Key,\n S extends RelationState,\n> = ToOneMutationSchema<ToOneCreateEntries<Source, Key, S>, { optional: true }>;\n\nexport const toOneCreateFactory = <\n Source extends AnyModel,\n Key,\n S extends RelationState,\n T extends SchemaGetter<S>,\n>(\n resolved: ResolvedSlot,\n targetSchemas: T\n): ToOneCreateSchema<Source, Key, S> => {\n const projection = nestedRelationDataProjection<S, T>(\n resolved,\n targetSchemas\n );\n const getCreateSchema = projection.getCreateSchema;\n\n return toOneMutationSchema(\n {\n create: getCreateSchema,\n connect: () => targetSchemas().core.whereUnique,\n connectOrCreate: v.object(\n {\n where: () => targetSchemas().core.whereUnique,\n create: getCreateSchema,\n },\n { partial: false }\n ),\n },\n { optional: true }\n ) as unknown as ToOneCreateSchema<Source, Key, S>;\n};\n\n/**\n * To-many create: { create?, createMany?, connect?, connectOrCreate? }\n * All accept single or array, normalized to array\n * Uses thunks for lazy evaluation to avoid circular reference issues\n *\n * Each createMany row uses the same projected create schema as `create`. The\n * query engine keeps scalar-only rows on its grouped fast path and composes\n * relation-bearing rows as an ordered record series.\n */\n\nexport type ToManyCreateSchema<\n Source extends AnyModel,\n Key,\n S extends RelationState,\n> = V.Object<\n {\n create: () => V.SingleOrArray<ProjectedNestedCreate<Source, Key, S>>;\n createMany: NestedCreateManySchema<Source, Key, S>;\n connect: () => V.SingleOrArray<GetTargetSchemas<S>[\"core\"][\"whereUnique\"]>;\n connectOrCreate: () => V.SingleOrArray<\n V.Object<\n {\n where: () => GetTargetSchemas<S>[\"core\"][\"whereUnique\"];\n create: () => ProjectedNestedCreate<Source, Key, S>;\n },\n { partial: false }\n >\n >;\n // COMPATIBILITY NOTE (deliberate Prisma superset — query-engine-v2 PLAN\n // P−1.2 / ATOM §4): nested `upsert` under a top-level `create` is NOT a\n // Prisma create input. VibORM supports it with GLOBAL-LOOKUP,\n // ADOPT-AND-UPDATE semantics: the target is located by its own unique\n // `where` (no parent correlation is possible under a fresh parent), the\n // found branch adopts it (reparents) and applies `update`, and the missing\n // branch creates it under the new parent. This is the natural completion of\n // the adopt family that `connect`/`connectOrCreate` already provide here.\n // The difference is pinned in docs/content/docs/client/compatibility.mdx;\n // it is never silently divergent.\n upsert: () => V.SingleOrArray<\n V.Object<\n {\n where: () => GetTargetSchemas<S>[\"core\"][\"whereUnique\"];\n create: () => ProjectedNestedCreate<Source, Key, S>;\n update: () => ProjectedCreateUpsertUpdate<Source, Key, S>;\n },\n { partial: false }\n >\n >;\n },\n { optional: true }\n>;\n\nexport const toManyCreateFactory = <\n Source extends AnyModel,\n Key,\n S extends RelationState,\n T extends SchemaGetter<S>,\n>(\n resolved: ResolvedSlot,\n targetSchemas: T\n): ToManyCreateSchema<Source, Key, S> => {\n const projection = nestedRelationDataProjection<S, T>(\n resolved,\n targetSchemas\n );\n const getCreateSchema = projection.getCreateSchema;\n\n const createManySchema = v.object(\n {\n data: () => v.array(getCreateSchema()),\n skipDuplicates: v.boolean({ optional: true }),\n },\n { atLeast: [\"data\"], refuse: refuseDefaultOnlySkipDuplicates }\n );\n\n return v.object(\n {\n create: () => v.singleOrArray(getCreateSchema()),\n createMany: createManySchema,\n connect: () => v.singleOrArray(targetSchemas().core.whereUnique),\n connectOrCreate: () =>\n v.singleOrArray(\n v.object(\n {\n where: () => targetSchemas().core.whereUnique,\n create: getCreateSchema,\n },\n { partial: false }\n )\n ),\n // Deliberate Prisma superset (see the type above): global-lookup,\n // adopt-and-update. The engine (query-engine-v2 CreateOperation) owns the\n // adopt semantics; this schema only pins the accepted input surface.\n upsert: () =>\n v.singleOrArray(\n v.object(\n {\n where: () => targetSchemas().core.whereUnique,\n create: getCreateSchema,\n // The agreeing-owned-FK asymmetry, carried as projection data rather than\n // decided here: see {@link ProjectedCreateUpsertUpdate}.\n update: projection.getCreateUpsertUpdateSchema,\n },\n { partial: false }\n )\n ),\n },\n { optional: true }\n ) as unknown as ToManyCreateSchema<Source, Key, S>;\n};\n","// Relation Filter Schemas\n\nimport type { AnyModel } from \"@schema/model\";\nimport { slotMayBeEmpty } from \"@schema/relation/clearability\";\nimport type { SlotMayBeEmpty } from \"@schema/relation/static-membership\";\nimport type { RelationState } from \"@schema/relation/types\";\nimport type { ResolvedSlot } from \"@schema/validation/relation-resolution\";\nimport { createSchema, fail, ok, validateSchema } from \"../primitives/helpers\";\nimport { type V, v } from \"../primitives/v\";\nimport type { VibSchema } from \"../types\";\nimport { isRecord } from \"../value-guards\";\nimport type { GetTargetSchemas, SchemaGetter } from \"./helpers\";\nimport {\n type RecurrenceFor,\n recurrenceSchema,\n type UnavailableRecurrenceSchema,\n type UnavailableRecursiveClauseSchema,\n unavailableRecursiveClause,\n withRecursiveNode,\n} from \"./recurrence\";\n\n/**\n * To-one filter. Two spellings are accepted (Prisma parity):\n *\n * explicit { author: { is: {...}, isNot: {...} } }\n * shorthand { author: { name: \"x\" } } === { author: { is: { name: \"x\" } } }\n *\n * DISAMBIGUATION (Prisma's rule): if EVERY key of the object is `is` or\n * `isNot`, the object is the explicit filter; otherwise the whole object is a\n * target-model `where` and desugars to `{ is: <object> }`. An empty object has\n * no key outside that set, so `{}` reads as the (vacuous) explicit filter.\n *\n * COLLISION RULE: a target model with a scalar field literally named `is` or\n * `isNot` cannot be filtered on that field through the shorthand — an object\n * whose only keys are `is`/`isNot` always reads as the explicit filter. Reach\n * such a field through the explicit spelling instead:\n * { author: { is: { is: \"x\" } } }\n * Prisma has the same ambiguity and resolves it the same way. The shorthand's\n * input type marks `is`/`isNot` as `never` (Prisma spells this `XOR<…>`), so a\n * collision is a type error rather than a silent reinterpretation.\n *\n * `recurse` collides the same way, one step earlier: an object that spells\n * `recurse` (not `undefined`) IS the recursive filter, on every relation slot,\n * and never reaches the shorthand. A target field literally named `recurse` is\n * reached through `{ parent: { is: { recurse: … } } }`; one named `self` is\n * unaffected, because only `recurse` selects the form. Both spelled\n * `undefined` read as absent, like every undefined key of an object.\n *\n * For optional relations, `is` can also be null, and the bare `null`\n * shorthand normalizes to `{ is: null }` (unchanged by the object shorthand).\n *\n * Dispatch is DETERMINISTIC — the key rule selects exactly one member and that\n * member's error is what surfaces — rather than `v.union`'s try-each-in-order,\n * which would report a union-wide miss for a merely malformed explicit filter.\n * Uses thunks for lazy evaluation to avoid circular reference issues.\n */\n\ntype NullToIsNull = V.Schema<null, { is: null }>;\nconst nullToIsNull: NullToIsNull = createSchema(\"object\", () =>\n ok({ is: null })\n);\n\n/**\n * May this slot be empty? The DERIVED answer, not a declared flag: `is: null`\n * exists exactly where the membership can be absent, which for a stored\n * reference is its own nullable tuple and for every non-owner is always.\n */\ntype MayBeEmpty<\n Source extends AnyModel,\n Key,\n S extends RelationState,\n> = SlotMayBeEmpty<Source, Key, S> extends false ? false : true;\n\ntype ToOneFilterObjectSchema<\n Source extends AnyModel,\n Key,\n S extends RelationState,\n> = V.Object<\n {\n is: () => V.MaybeNullable<\n GetTargetSchemas<S>[\"core\"][\"where\"],\n MayBeEmpty<Source, Key, S>\n >;\n isNot: () => V.MaybeNullable<\n GetTargetSchemas<S>[\"core\"][\"where\"],\n MayBeEmpty<Source, Key, S>\n >;\n } & NoClosure\n>;\n\ntype TargetWhereSchema<S extends RelationState> =\n GetTargetSchemas<S>[\"core\"][\"where\"];\n\n/** `some`/`every`/`none`, each the target's full `where`. */\ntype Quantifiers<S extends RelationState> = {\n some: () => TargetWhereSchema<S>;\n every: () => TargetWhereSchema<S>;\n none: () => TargetWhereSchema<S>;\n};\n\n/**\n * The recursive filter: a quantifier over the slot's transitive closure from\n * the filtered row, `self` adding that row itself. `recurse` is the language\n * `select`/`include` admit on the slot without its output budget, so\n * eligibility, bounds and normalization have one owner. Where the slot cannot\n * recurse the required `recurse` is `never` and the form is uninhabitable;\n * eligibility stays inside the required key, as on the select side, so no\n * ordinary filter compares the cyclic model graph eagerly.\n */\ntype RecursiveFilterSchema<\n Source extends AnyModel,\n Key,\n S extends RelationState,\n> = V.Object<\n {\n recurse: RecurrenceFor<Source, Key, S, \"filter\">;\n self: V.Boolean;\n is: UnavailableRecursiveClauseSchema;\n isNot: UnavailableRecursiveClauseSchema;\n } & Quantifiers<S>,\n { atLeast: [\"recurse\"] }\n>;\n\n/**\n * The ordinary forms' statement of the dispatcher's invariant: they never see\n * `recurse`, nor a `self` spelled `undefined`, so neither is theirs to accept.\n * Types only, like the shorthand's `is?: never`; the runtime objects carry no\n * entry, because `withRecursiveNode` routes a spelled `recurse` away and drops\n * both keys spelled `undefined`.\n */\ntype NoClosure = {\n recurse: UnavailableRecurrenceSchema;\n self: UnavailableRecurrenceSchema;\n};\n\n/**\n * The shorthand member: a target-model `where` whose parsed value is wrapped\n * into the explicit `{ is }` shape. Its input type excludes `is`/`isNot` so the\n * two spellings stay mutually exclusive at the type level exactly as the key\n * rule makes them at runtime.\n */\ntype ToOneShorthandFilterSchema<\n Source extends AnyModel,\n Key,\n S extends RelationState,\n> = V.Transform<\n V.Input<TargetWhereSchema<S>> & {\n is?: never;\n isNot?: never;\n recurse?: never;\n },\n V.Output<ToOneFilterObjectSchema<Source, Key, S>>\n> & { wrapped: TargetWhereSchema<S> };\n\nexport type ToOneFilterSchema<\n Source extends AnyModel,\n Key,\n S extends RelationState,\n> = MayBeEmpty<Source, Key, S> extends true\n ? V.Union<\n readonly [\n NullToIsNull,\n ToOneFilterObjectSchema<Source, Key, S>,\n ToOneShorthandFilterSchema<Source, Key, S>,\n RecursiveFilterSchema<Source, Key, S>,\n ]\n >\n : V.Union<\n readonly [\n ToOneFilterObjectSchema<Source, Key, S>,\n ToOneShorthandFilterSchema<Source, Key, S>,\n RecursiveFilterSchema<Source, Key, S>,\n ]\n >;\n\n/**\n * A relation filter that names no quantifier is not a filter.\n *\n * `where: { posts: {} }` and `where: { author: {} }` state nothing about the\n * relation, and an engine that reads them as silence lowers them to TRUE —\n * which is how `deleteMany({ where: { posts: {} } })` came to delete every\n * row. Unlike a scalar filter object, a relation filter schema is built per\n * RELATION, so it can and does still name the slot in its own sentence.\n */\nconst TO_MANY_QUANTIFIERS = [\"some\", \"every\", \"none\"] as const;\nconst TO_ONE_QUANTIFIERS = [\"is\", \"isNot\"] as const;\n\nconst requireRelationQuantifier = (\n resolved: ResolvedSlot,\n quantifiers: readonly string[]\n): ((value: Record<string, unknown>) => string | undefined) => {\n const refusal = `Relation filter '${resolved.slot.field}' requires one of: ${quantifiers.join(\", \")}.`;\n return (value) =>\n quantifiers.some((quantifier) => value[quantifier] !== undefined)\n ? undefined\n : refusal;\n};\n\n/** {@link Quantifiers}' runtime entries. */\nconst quantifierEntries = <S extends RelationState>(\n targetSchemas: SchemaGetter<S>\n) => ({\n some: () => targetSchemas().core.where,\n every: () => targetSchemas().core.where,\n none: () => targetSchemas().core.where,\n});\n\n/**\n * The recursive filter of a slot that can recurse, or `undefined`. Its\n * `recurse` is the `select`/`include` language without `maxOccurrences`.\n */\nconst recursiveFilter = <S extends RelationState, T extends SchemaGetter<S>>(\n resolved: ResolvedSlot,\n targetSchemas: T\n) => {\n const recurrence = recurrenceSchema(resolved, \"filter\");\n return (\n recurrence &&\n v.object(\n {\n recurse: recurrence,\n self: v.boolean(),\n ...quantifierEntries(targetSchemas),\n is: unavailableRecursiveClause(\"is\"),\n isNot: unavailableRecursiveClause(\"isNot\"),\n },\n {\n atLeast: [\"recurse\"],\n refuse: requireRelationQuantifier(resolved, TO_MANY_QUANTIFIERS),\n }\n )\n );\n};\n\n/** The keys that spell the explicit `{ is, isNot }` filter. */\nconst EXPLICIT_TO_ONE_FILTER_KEYS = new Set([\"is\", \"isNot\"]);\n\nconst isExplicitToOneFilter = (value: object): boolean => {\n for (const key in value) {\n if (!EXPLICIT_TO_ONE_FILTER_KEYS.has(key)) {\n return false;\n }\n }\n return true;\n};\n\nexport const toOneFilterFactory = <\n Source extends AnyModel,\n Key,\n S extends RelationState,\n T extends SchemaGetter<S>,\n>(\n resolved: ResolvedSlot,\n targetSchemas: T\n): ToOneFilterSchema<Source, Key, S> => {\n const isOptional = slotMayBeEmpty(resolved);\n const filterObject = v.object(\n {\n is: () =>\n v.maybeNullable(\n targetSchemas().core.where,\n isOptional as MayBeEmpty<Source, Key, S>\n ),\n isNot: () =>\n v.maybeNullable(\n targetSchemas().core.where,\n isOptional as MayBeEmpty<Source, Key, S>\n ),\n },\n { refuse: requireRelationQuantifier(resolved, TO_ONE_QUANTIFIERS) }\n );\n\n // The target `where` is reached through a thunk: building it here would\n // resolve the target model's schemas while this one is still under\n // construction, which never terminates for a self-referential relation.\n // The cast narrows the shorthand's INPUT to exclude `is`/`isNot` (see the\n // collision rule above); the runtime value is exactly this transform.\n const shorthand = v.lazy(() =>\n v.coerce(targetSchemas().core.where, (where) => ({ is: where }))\n ) as unknown as ToOneShorthandFilterSchema<Source, Key, S>;\n\n const members: readonly VibSchema<unknown, unknown>[] = isOptional\n ? [nullToIsNull, filterObject, shorthand]\n : [filterObject, shorthand];\n\n // A genuine union of the members above, but with deterministic dispatch\n // instead of first-match-wins. `type`/`options` mirror `v.union` so\n // introspection (JSON Schema conversion) sees the alternatives it expects.\n const schema = createSchema<unknown, unknown>(\"union\", (value) => {\n if (value === null) {\n return isOptional\n ? validateSchema(nullToIsNull, value)\n : fail(\"Expected object\");\n }\n if (!isRecord(value)) {\n return fail(\"Expected object\");\n }\n return isExplicitToOneFilter(value)\n ? validateSchema(filterObject, value)\n : validateSchema(shorthand, value);\n });\n return withRecursiveNode(\n Object.assign(schema, { options: members }),\n recursiveFilter(resolved, targetSchemas)\n ) as unknown as ToOneFilterSchema<Source, Key, S>;\n};\n\n/**\n * To-many filter: { some?, every?, none? }, or the recursive filter.\n * Uses thunks for lazy evaluation - getTargetWhereSchema already returns thunk\n */\n\nexport type ToManyFilterSchema<\n Source extends AnyModel,\n Key,\n S extends RelationState,\n> = V.Union<\n readonly [\n V.Object<Quantifiers<S> & NoClosure>,\n RecursiveFilterSchema<Source, Key, S>,\n ]\n>;\n\nexport const toManyFilterFactory = <\n Source extends AnyModel,\n Key,\n S extends RelationState,\n T extends SchemaGetter<S>,\n>(\n resolved: ResolvedSlot,\n targetSchemas: T\n): ToManyFilterSchema<Source, Key, S> =>\n withRecursiveNode(\n v.object(quantifierEntries(targetSchemas), {\n refuse: requireRelationQuantifier(resolved, TO_MANY_QUANTIFIERS),\n }),\n recursiveFilter(resolved, targetSchemas)\n ) as unknown as ToManyFilterSchema<Source, Key, S>;\n","import type { AnyModel } from \"@schema/model\";\nimport type { DecimalListScalarKeys, StringKeyOf } from \"@schema/model/helper\";\nimport { type AnyRelation, isVariantRelationState } from \"@schema/relation\";\nimport type {\n Cardinality,\n TargetKind,\n} from \"@schema/relation/static-membership\";\nimport type { RelationState } from \"@schema/relation/types\";\nimport type { ScalarState } from \"@schema/scalars\";\nimport {\n type DecimalListOrderByRefusalSchema,\n decimalListOrderByRefusalSchema,\n isDecimalListScalarKey,\n type OrderableScalarKeys,\n type SortOrderSchema,\n sortOrderSchema,\n type VectorSortOrderSchema,\n vectorSortOrderSchema,\n} from \"@validation/model/core/orderby\";\nimport { entriesFromKeys } from \"../primitives/record\";\nimport v, { type V } from \"../primitives/v\";\nimport type { VibSchema } from \"../types\";\nimport type { SchemaGetter, TargetModel } from \"./helpers\";\n\ntype ModelStateOf<M extends AnyModel> = M[\"~\"][\"state\"];\ntype ModelScalars<M extends AnyModel> = ModelStateOf<M>[\"scalars\"];\ntype ModelScalarKey<M extends AnyModel> = StringKeyOf<ModelScalars<M>>;\ntype ModelDecimalListScalarKey<M extends AnyModel> = DecimalListScalarKeys<\n ModelScalars<M>\n>;\n\ntype ScalarStateOf<F> = F extends { \"~\": { state: infer S } }\n ? S extends ScalarState\n ? S\n : never\n : never;\n\ntype VectorScalarKey<M extends AnyModel> = {\n [K in keyof ModelScalars<M>]: ScalarStateOf<\n ModelScalars<M>[K]\n >[\"type\"] extends \"vector\"\n ? K extends string\n ? K\n : never\n : never;\n}[keyof ModelScalars<M>];\n\ntype NonVectorScalarKey<M extends AnyModel> = Exclude<\n OrderableScalarKeys<M>,\n VectorScalarKey<M>\n>;\n\ntype ModelScalarOrderByEntries<M extends AnyModel> = V.FromKeys<\n NonVectorScalarKey<M>[],\n SortOrderSchema\n>[\"entries\"] &\n V.FromKeys<VectorScalarKey<M>[], VectorSortOrderSchema>[\"entries\"] &\n V.FromKeys<\n ModelDecimalListScalarKey<M>[],\n DecimalListOrderByRefusalSchema\n >[\"entries\"];\n\ntype RuntimeRelationMap = Record<string, AnyRelation>;\n\n/**\n * Maximum number of to-one relation hops an `orderBy` chain may cross, e.g.\n * `orderBy: { a: { b: { c: { name: 'asc' } } } }` is 3 hops.\n *\n * Raised 3 -> 8 by decision D-5 (docs/architecture/prisma-parity-v2-plan.md).\n * Lifting it further, or removing it, needs a lazy self-reference in the\n * orderBy schema rather than this bounded strict-schema recursion.\n *\n * This is the FRONT LINE: past the cap the schema simply stops offering\n * relation keys, so an over-deep chain is rejected here as an unknown key.\n * It is now also the ONLY line. The V1 builder that re-checked the same cap\n * while building joins (`query-engine/builders/relation-orderby-builder.ts`)\n * was retired with the pattern experiment, so there is no second constant to\n * keep equal; tests/contracts/engine/query/orderby-relation-depth.core.test.ts\n * pins that this one owns it.\n */\nconst MAX_RELATION_ORDER_DEPTH = 8;\n\n/**\n * Type-level twin of MAX_RELATION_ORDER_DEPTH: one tuple element per allowed\n * hop, consumed by ConsumeRelationHop as the schema type recurses. Derived\n * from the constant so the two cannot drift.\n */\ntype BuildRelationOrderDepth<\n N extends number,\n Acc extends readonly unknown[] = [],\n> = Acc[\"length\"] extends N\n ? Acc\n : BuildRelationOrderDepth<N, [...Acc, unknown]>;\n\ntype RelationOrderDepth = BuildRelationOrderDepth<\n typeof MAX_RELATION_ORDER_DEPTH\n>;\n\ntype ConsumeRelationHop<Depth extends readonly unknown[]> =\n Depth extends readonly [unknown, ...infer Rest extends readonly unknown[]]\n ? Rest\n : [];\n\ntype ToOneRelationKeys<M extends AnyModel> = {\n [K in keyof ModelStateOf<M>[\"relations\"]]: Cardinality<\n ModelStateOf<M>[\"relations\"][K]\n > extends \"one\"\n ? TargetKind<ModelStateOf<M>[\"relations\"][K]> extends \"model\"\n ? K extends string\n ? K\n : never\n : never\n : never;\n}[keyof ModelStateOf<M>[\"relations\"]];\n\ntype RelationStateOf<R> = R extends { \"~\": { state: infer S } }\n ? S extends RelationState\n ? S\n : never\n : never;\n\ntype RelationTargetModel<R> = TargetModel<RelationStateOf<R>>;\n\ntype ToOneRelationOrderByEntries<\n M extends AnyModel,\n Depth extends readonly unknown[],\n> = Depth extends readonly [unknown, ...infer Rest extends readonly unknown[]]\n ? {\n [K in ToOneRelationKeys<M>]: () => ToOneModelOrderBySchema<\n RelationTargetModel<ModelStateOf<M>[\"relations\"][K]>,\n Rest\n >;\n }\n : Record<never, never>;\n\ntype ToOneModelOrderBySchema<\n M extends AnyModel,\n Depth extends readonly unknown[],\n> = V.Object<\n ModelScalarOrderByEntries<M> & ToOneRelationOrderByEntries<M, Depth>\n>;\n\ntype ToOneOrderByRemainingDepth = ConsumeRelationHop<RelationOrderDepth>;\n\n/**\n * Which nested relations a to-one `orderBy` may descend into: MODEL-target\n * singular slots only. A variant slot has several targets and no single column\n * family to order by, which is why its own `orderBy` family is a named refusal;\n * reaching it from here would reopen that refusal one level down.\n */\nconst isOrderableToOneRelation = (state: RelationState): boolean =>\n state.cardinality === \"one\" && !isVariantRelationState(state);\n\ntype ToManyRelationOrderByFailureSchema = VibSchema<never, never>;\ntype RuntimeToOneRelationOrderByEntry =\n | (() => ToOneModelOrderBySchema<AnyModel, []>)\n | ToManyRelationOrderByFailureSchema;\n\nconst createToManyRelationOrderByFailureSchema = (\n relationName: string\n): ToManyRelationOrderByFailureSchema => {\n return v.refused(\n `Relation orderBy '${relationName}' cannot order through a to-many relation; use '_count'.`\n );\n};\n\nconst getModelScalarOrderByEntries = <M extends AnyModel>(\n target: M\n): ModelScalarOrderByEntries<M> => {\n const vectorScalarKeys: VectorScalarKey<M>[] = [];\n const nonVectorScalarKeys: NonVectorScalarKey<M>[] = [];\n const decimalListScalarKeys: ModelDecimalListScalarKey<M>[] = [];\n const scalarKeys = Object.keys(\n target[\"~\"].state.scalars\n ) as ModelScalarKey<M>[];\n\n for (const fieldName of scalarKeys) {\n if (isDecimalListScalarKey(target, fieldName)) {\n decimalListScalarKeys.push(fieldName);\n continue;\n }\n const scalar = target[\"~\"].state.scalars[fieldName];\n const state = scalar[\"~\"].state;\n if (state.type === \"vector\") {\n vectorScalarKeys.push(fieldName as VectorScalarKey<M>);\n continue;\n }\n nonVectorScalarKeys.push(fieldName as NonVectorScalarKey<M>);\n }\n\n const scalarEntries = entriesFromKeys<\n NonVectorScalarKey<M>[],\n SortOrderSchema\n >(nonVectorScalarKeys, sortOrderSchema);\n const vectorEntries = entriesFromKeys<\n VectorScalarKey<M>[],\n VectorSortOrderSchema\n >(vectorScalarKeys, vectorSortOrderSchema);\n const decimalListEntries = entriesFromKeys<\n ModelDecimalListScalarKey<M>[],\n DecimalListOrderByRefusalSchema\n >(decimalListScalarKeys, decimalListOrderByRefusalSchema);\n\n return {\n ...scalarEntries,\n ...vectorEntries,\n ...decimalListEntries,\n };\n};\n\nconst getToOneRelationOrderByEntries = <\n M extends AnyModel,\n Depth extends readonly unknown[],\n>(\n target: M,\n depth: number\n): ToOneRelationOrderByEntries<M, Depth> => {\n if (depth <= 0) {\n return {} as ToOneRelationOrderByEntries<M, Depth>;\n }\n\n const relationEntries: Record<string, RuntimeToOneRelationOrderByEntry> = {};\n const relations = target[\"~\"].state.relations as RuntimeRelationMap;\n for (const [relationName, relation] of Object.entries(relations)) {\n const relationState = relation[\"~\"].state;\n if (isOrderableToOneRelation(relationState)) {\n relationEntries[relationName] = () =>\n v.lazyRef(() =>\n buildToOneOrderBySchema(\n relation[\"~\"].settleTarget() as AnyModel,\n depth - 1\n )\n );\n continue;\n }\n\n relationEntries[relationName] =\n createToManyRelationOrderByFailureSchema(relationName);\n }\n\n return relationEntries as ToOneRelationOrderByEntries<M, Depth>;\n};\n\nconst buildToOneOrderBySchema = <\n M extends AnyModel,\n Depth extends readonly unknown[] = ToOneOrderByRemainingDepth,\n>(\n target: M,\n depth: number\n): ToOneModelOrderBySchema<M, Depth> => {\n const scalarEntries = getModelScalarOrderByEntries(target);\n const relationEntries = getToOneRelationOrderByEntries<M, Depth>(\n target,\n depth\n );\n\n return v.object({\n ...scalarEntries,\n ...relationEntries,\n }) as ToOneModelOrderBySchema<M, Depth>;\n};\n\n/**\n * To-one orderBy: scalar fields and bounded to-one chains from the related model.\n * e.g., orderBy: { author: { name: 'asc' } }\n */\nexport type ToOneOrderBySchema<S extends RelationState> =\n () => ToOneModelOrderBySchema<TargetModel<S>, ToOneOrderByRemainingDepth>;\n\nexport const toOneOrderByFactory = <\n S extends RelationState,\n T extends SchemaGetter<S>,\n>(\n relation: AnyRelation,\n _targetSchemas: T\n): ToOneOrderBySchema<S> => {\n // OrderBy entries have no default. Reading their validator must not build a\n // target branch until the input actually orders through that relation.\n return () =>\n v.lazyRef(() =>\n buildToOneOrderBySchema(\n relation[\"~\"].settleTarget() as TargetModel<S>,\n MAX_RELATION_ORDER_DEPTH - 1\n )\n );\n};\n\n/**\n * To-many orderBy: can order by _count aggregate\n * e.g., orderBy: { posts: { _count: 'desc' } }\n */\nexport type ToManyOrderBySchema<_S extends RelationState> = V.Object<{\n _count: V.Enum<[\"asc\", \"desc\"]>;\n}>;\nexport const toManyOrderByFactory = <S extends RelationState>(\n _state: S\n): ToManyOrderBySchema<S> => {\n return v.object({\n _count: v.enum([\"asc\", \"desc\"]),\n });\n};\n","// Relation Select & Include Schemas\n\nimport type { AnyModel, ModelState } from \"@schema/model\";\nimport type { StringKeyOf } from \"@schema/model/helper\";\nimport type { AnyRelation } from \"@schema/relation\";\nimport type { RelationState } from \"@schema/relation/types\";\nimport type { ResolvedSlot } from \"@schema/validation/relation-resolution\";\nimport { withOmitProjection } from \"../model/args/omit\";\nimport {\n type PaginationSkipSchema,\n type PaginationTakeSchema,\n paginationSkip,\n paginationTake,\n} from \"../model/args/pagination\";\nimport { rejectSelectInclude } from \"../model/args/select-include-exclusivity\";\nimport { projectableScalarNames } from \"../model/core/projection\";\nimport v, { type V } from \"../primitives/v\";\nimport type { VibSchema } from \"../types\";\nimport type { GetTargetSchemas, SchemaGetter, TargetModel } from \"./helpers\";\nimport {\n type RecurrenceFor,\n type RecurrenceSchema,\n recurrenceSchema,\n type UnavailableRecurrenceSchema,\n type UnavailableRecursiveClauseSchema,\n unavailableRecurrence,\n unavailableRecursiveClause,\n withRecursiveNode,\n} from \"./recurrence\";\n\n// =============================================================================\n// TRANSFORM HELPERS\n// =============================================================================\n\nconst getTargetState = (relation: AnyRelation): ModelState =>\n getTargetModel(relation)[\"~\"].state as ModelState;\n\n/**\n * `settleTarget` is the one sanctioned getter invocation: the target is settled\n * once per declaration and every schema graph reusing this terminal observes\n * the same return or the same normalized `Error`.\n */\nconst getTargetModel = (relation: AnyRelation): AnyModel =>\n relation[\"~\"].settleTarget() as AnyModel;\n\nconst buildSelectionForModel = (target: AnyModel): Record<string, true> => {\n const select: Record<string, true> = {};\n for (const field of projectableScalarNames(target)) {\n select[field] = true;\n }\n return select;\n};\n\n/**\n * The label a nested node's `omit` failure carries. Relations name themselves\n * when the schema disambiguated them (`.name()`); otherwise the message still\n * names the target model, which is the part a caller needs.\n */\nconst nestedOmitLabel = (relation: AnyRelation): string => {\n const name = relation[\"~\"].state.name;\n return name ? `include.${name}` : \"a nested include\";\n};\n\n/**\n * A relation node accepts `omit` exactly like a top-level operation does:\n * subtractive with `select`, composable with `include`, and desugared into one\n * explicit `select` before anything downstream sees it. Wrapping the node\n * schema with the SAME helper the top level uses is what keeps the two surfaces\n * from drifting — and it runs BEFORE `includeToField`, which then finds a\n * `select` already in place and leaves it alone.\n */\nconst withOmitForModel = <Schema extends V.Object<any>>(\n target: AnyModel,\n label: string,\n schema: Schema\n): Schema => withOmitProjection(schema as never, target, label) as never;\n\nconst withNestedOmit = <Schema extends V.Object<any>>(\n relation: AnyRelation,\n schema: Schema\n): Schema =>\n withOmitForModel(getTargetModel(relation), nestedOmitLabel(relation), schema);\n\n/** The asking key cannot have a second producer inside its own repeated node. */\nconst askingKeyRefusal = (key: string) =>\n v.optional(\n v.refused(\n `${key} is produced by recurse and cannot be selected again inside its own recursive node`\n )\n );\n\n/** A target projection whose asking key is refused, keeping its options. */\ntype ProjectionWithoutAsking<Schema extends V.Object<any, any>, Key> = V.Object<\n Omit<Schema[\"entries\"], Extract<Key, keyof Schema[\"entries\"]>> &\n Record<Extract<Key, string>, ReturnType<typeof askingKeyRefusal>>\n>;\n\nconst projectionWithoutAsking = (schema: V.Object<any, any>, key: string) =>\n schema.extend({ [key]: askingKeyRefusal(key) });\n\n/** The clauses a to-many recursive node adds beside the shared entries. */\ntype RecursiveClauses = Readonly<\n Record<string, VibSchema<any, any> | (() => VibSchema<any, any>)>\n>;\n\n/** A to-many node's `orderBy`: one order term, or a list of them. */\nconst termOrList = <Term extends VibSchema<any, any>>(term: Term) =>\n v.union([term, v.array(term)]);\n\n/**\n * The one recursive node: the four entries every recursive node shares, beside\n * the collection clauses a to-many node adds, under the ordinary node's\n * `rejectSelectInclude` + `withNestedOmit` + `includeToField` chain.\n */\nconst buildRecursiveNode = <S extends RelationState, T extends SchemaGetter<S>>(\n relation: AnyRelation,\n field: string,\n recurrence: RecurrenceSchema,\n targetSchemas: T,\n collectionClauses: RecursiveClauses = {}\n) =>\n v.coerce(\n withNestedOmit(\n relation,\n rejectSelectInclude(\n v.object({\n ...collectionClauses,\n select: () =>\n projectionWithoutAsking(targetSchemas().core.select, field),\n include: () =>\n projectionWithoutAsking(targetSchemas().core.include, field),\n omit: () => targetSchemas().core.omit,\n recurse: recurrence,\n })\n )\n ),\n includeToField(relation)\n );\n\n/**\n * The factory tail every relation node shares: the ordinary language alone\n * where the slot cannot recurse, and beside it the recursive node where it can.\n * The collection clauses are built only for a slot that recurses.\n */\nconst withRecurrence = <S extends RelationState, T extends SchemaGetter<S>>(\n ordinary: V.Union<readonly [VibSchema<any, any>, VibSchema<any, any>]>,\n relation: AnyRelation,\n resolved: ResolvedSlot,\n targetSchemas: T,\n collectionClauses?: () => RecursiveClauses\n) => {\n const recurrence = recurrenceSchema(resolved);\n if (!recurrence) return ordinary;\n return withRecursiveNode(\n ordinary,\n buildRecursiveNode(\n relation,\n resolved.slot.field,\n recurrence,\n targetSchemas,\n collectionClauses?.()\n )\n );\n};\n\ntype RecursiveProjectionSchemas<S extends RelationState, Key> = {\n readonly select: ProjectionWithoutAsking<\n GetTargetSchemas<S>[\"core\"][\"select\"],\n Key\n >;\n readonly include: ProjectionWithoutAsking<\n GetTargetSchemas<S>[\"core\"][\"include\"],\n Key\n >;\n};\n\ntype ToOneRecursiveNodeSchema<\n Source extends AnyModel,\n Key,\n S extends RelationState,\n> = IncludeToField<\n V.Object<\n {\n recurse: RecurrenceFor<Source, Key, S>;\n where: UnavailableRecursiveClauseSchema;\n orderBy: UnavailableRecursiveClauseSchema;\n select: () => RecursiveProjectionSchemas<S, Key>[\"select\"];\n include: () => RecursiveProjectionSchemas<S, Key>[\"include\"];\n omit: () => GetTargetSchemas<S>[\"core\"][\"omit\"];\n },\n { atLeast: [\"recurse\"] }\n >\n>;\n\n// Eligibility belongs to the node's required `recurse` value. Choosing the\n// whole arm eagerly compares cyclic model graphs for ordinary includes too.\n// Ineligible nodes retain `recurse: never` and cannot admit a payload.\n\n/**\n * Nested `distinct`: scalar field names of the RELATED model, deduplicating\n * that relation's ordered rows before `take`/`skip` window them (the same\n * enum-of-scalars schema the top-level findMany args use).\n */\ntype NestedDistinctSchema<S extends RelationState> = V.Enum<\n StringKeyOf<TargetModel<S>[\"~\"][\"state\"][\"scalars\"]>[],\n { array: true }\n>;\n\nconst nestedDistinctNames = <S extends RelationState>(\n relation: AnyRelation\n): StringKeyOf<TargetModel<S>[\"~\"][\"state\"][\"scalars\"]>[] =>\n Object.keys(getTargetState(relation).scalars) as StringKeyOf<\n TargetModel<S>[\"~\"][\"state\"][\"scalars\"]\n >[];\n\ntype IncludeToField<Schema extends V.Object<any, any>> = V.Coerce<\n Schema,\n Schema[\" vibInferred\"][\"1\"] & { select?: Record<string, true> }\n>;\n\nconst includeToFieldForModel =\n (target: AnyModel) =>\n <V extends Record<string, any>>(\n value: V\n ): V & { select?: Record<string, true> } => {\n if (Object.hasOwn(value, \"select\") && value.select !== false) {\n return value;\n }\n const select = buildSelectionForModel(target);\n if (Object.keys(select).length === 0) return value;\n return {\n ...value,\n select,\n };\n };\n\nconst includeToField = (relation: AnyRelation) =>\n includeToFieldForModel(getTargetModel(relation));\n\ntype BooleanToSelect = V.Coerce<\n V.Boolean,\n { select?: Record<string, true> } | false\n>;\n\n/**\n * The node a bare `true` desugars to: an explicit projection of the target's\n * projectable scalars, FRESH on every parse so the engine never receives a\n * schema-level singleton it could mutate. A target with nothing projectable\n * yields `{}`, which the builder reads as \"default row\".\n */\nexport const defaultSelectionNode = (\n target: AnyModel\n): { select?: Record<string, true> } => {\n const select = buildSelectionForModel(target);\n return Object.keys(select).length > 0 ? { select } : {};\n};\n\n// `false` stays `false` so the query engine omits the relation entirely\n// (Prisma parity: include/select `rel: false` must not return the relation)\nconst booleanToSelect = (relation: AnyRelation): BooleanToSelect =>\n v.coerce(\n v.boolean(),\n (value: boolean): { select?: Record<string, true> } | false =>\n value ? defaultSelectionNode(getTargetModel(relation)) : false\n );\n\n// =============================================================================\n// INCLUDE FACTORY IMPLEMENTATIONS\n// =============================================================================\n\n/**\n * To-one include: true or nested { select, include }\n * `select` and `include` are mutually exclusive on the same node (Prisma parity)\n */\n\nexport type ToOneIncludeSchema<\n Source extends AnyModel,\n Key,\n S extends RelationState,\n> = V.Union<\n readonly [\n BooleanToSelect,\n IncludeToField<\n V.Object<{\n select: () => GetTargetSchemas<S>[\"core\"][\"select\"];\n include: () => GetTargetSchemas<S>[\"core\"][\"include\"];\n omit: () => GetTargetSchemas<S>[\"core\"][\"omit\"];\n recurse: UnavailableRecurrenceSchema;\n }>\n >,\n ToOneRecursiveNodeSchema<Source, Key, S>,\n ]\n>;\nexport const toOneIncludeFactory = <\n Source extends AnyModel,\n Key,\n S extends RelationState,\n T extends SchemaGetter<S>,\n>(\n relation: AnyRelation,\n resolved: ResolvedSlot,\n targetSchemas: T\n): ToOneIncludeSchema<Source, Key, S> => {\n const ordinary = v.union([\n booleanToSelect(relation),\n v.coerce(\n withNestedOmit(\n relation,\n rejectSelectInclude(\n v.object({\n select: () => targetSchemas().core.select,\n include: () => targetSchemas().core.include,\n omit: () => targetSchemas().core.omit,\n recurse: unavailableRecurrence(),\n })\n )\n ),\n includeToField(relation)\n ),\n ]);\n return withRecurrence(ordinary, relation, resolved, targetSchemas) as never;\n};\n\n/**\n * THE TO-MANY NESTED NODE — `{ where, orderBy, take, skip, cursor, distinct,\n * select, include, omit }`, with `select`/`include` mutually exclusive on the\n * same node (Prisma parity).\n *\n * `take`/`skip`/`cursor`/`distinct` are the very schemas the top level uses: a\n * negative `take` is Prisma's \"last N\" (the relation subquery runs the reversed\n * order with an absolute limit and the parser restores the logical order), a\n * non-integer take or a negative skip is refused with the top-level message,\n * `cursor` is a whereUnique of the RELATED model applied per parent, and\n * `distinct` names scalars of the RELATED model.\n *\n * DECOUPLED FROM `RelationState` on purpose. Everything the node needs reduces\n * to four facts — the target model (default projection + `omit` desugaring),\n * the label an `omit` failure carries, the target's core schemas, and the\n * target's scalar names for `distinct`. Naming those four directly is what lets\n * a SECOND caller build the identical node without a relation to read them off:\n * a polymorphic collection's per-variant arm\n * (`./polymorphic/select-include.ts`), whose target is chosen by a\n * discriminator rather than by an edge.\n *\n * Extracted rather than hand-copied. Two hand-written copies of these nine keys\n * under `rejectSelectInclude` + `withOmitProjection` + `includeToField` would be\n * two things to keep in step, and the drift would be silent — a polymorphic arm\n * quietly missing `cursor`, say, reads as \"not supported\" rather than as a bug.\n * `to-many.core.test.ts` is the regression net for the extraction itself.\n */\n/** The six core schemas of the related model a to-many node reaches for. */\nexport type ToManyNestedTargetCore = {\n readonly where: VibSchema<any, any>;\n readonly orderBy: VibSchema<any, any>;\n readonly whereUnique: VibSchema<any, any>;\n readonly select: VibSchema<any, any>;\n readonly include: VibSchema<any, any>;\n readonly omit: VibSchema<any, any>;\n};\n\nexport type ToManyNestedNodeSchema<\n Core extends ToManyNestedTargetCore,\n Distinct,\n> = IncludeToField<\n V.Object<{\n where: () => Core[\"where\"];\n orderBy: () => V.Union<\n readonly [Core[\"orderBy\"], V.Array<Core[\"orderBy\"]>]\n >;\n take: PaginationTakeSchema;\n skip: PaginationSkipSchema;\n cursor: () => Core[\"whereUnique\"];\n distinct: Distinct;\n select: () => Core[\"select\"];\n include: () => Core[\"include\"];\n omit: () => Core[\"omit\"];\n recurse: UnavailableRecurrenceSchema;\n }>\n>;\n\nexport const buildToManyNestedNode = <\n Core extends ToManyNestedTargetCore,\n ScalarNames extends string[],\n>(config: {\n readonly targetModel: AnyModel;\n readonly label: string;\n readonly core: () => Core;\n readonly scalarNames: ScalarNames;\n}): ToManyNestedNodeSchema<Core, V.Enum<ScalarNames, { array: true }>> => {\n const { targetModel, label, scalarNames } = config;\n // ELEMENT access, not `core().where`: a dotted read on a value of generic\n // type collapses to the CONSTRAINT's property (`VibSchema<any, any>`), which\n // erases the caller's real schema and with it the whole nested node's input\n // type. Keying with a generic `K` keeps the deferred `Core[K]`.\n const at = <K extends keyof Core>(key: K): Core[K] => config.core()[key];\n return v.coerce(\n withOmitForModel(\n targetModel,\n label,\n rejectSelectInclude(\n v.object({\n where: () => at(\"where\"),\n orderBy: () => termOrList(at(\"orderBy\")),\n take: paginationTake(),\n skip: paginationSkip(),\n cursor: () => at(\"whereUnique\"),\n distinct: v.enum(scalarNames, { array: true }),\n select: () => at(\"select\"),\n include: () => at(\"include\"),\n omit: () => at(\"omit\"),\n recurse: unavailableRecurrence(),\n })\n )\n ),\n includeToFieldForModel(targetModel)\n );\n};\n\ntype ToManyRecursiveNodeSchema<\n Source extends AnyModel,\n Key,\n S extends RelationState,\n> = IncludeToField<\n V.Object<\n {\n where: () => GetTargetSchemas<S>[\"core\"][\"where\"];\n orderBy: () => V.Union<\n readonly [\n GetTargetSchemas<S>[\"core\"][\"orderBy\"],\n V.Array<GetTargetSchemas<S>[\"core\"][\"orderBy\"]>,\n ]\n >;\n take: UnavailableRecursiveClauseSchema;\n skip: UnavailableRecursiveClauseSchema;\n cursor: UnavailableRecursiveClauseSchema;\n distinct: UnavailableRecursiveClauseSchema;\n select: () => RecursiveProjectionSchemas<S, Key>[\"select\"];\n include: () => RecursiveProjectionSchemas<S, Key>[\"include\"];\n omit: () => GetTargetSchemas<S>[\"core\"][\"omit\"];\n recurse: RecurrenceFor<Source, Key, S>;\n },\n { atLeast: [\"recurse\"] }\n >\n>;\n\nexport type ToManyIncludeSchema<\n Source extends AnyModel,\n Key,\n S extends RelationState,\n> = V.Union<\n readonly [\n BooleanToSelect,\n ToManyNestedNodeSchema<\n GetTargetSchemas<S>[\"core\"],\n NestedDistinctSchema<S>\n >,\n ToManyRecursiveNodeSchema<Source, Key, S>,\n ]\n>;\nexport const toManyIncludeFactory = <\n Source extends AnyModel,\n Key,\n S extends RelationState,\n T extends SchemaGetter<S>,\n>(\n relation: AnyRelation,\n resolved: ResolvedSlot,\n targetSchemas: T\n): ToManyIncludeSchema<Source, Key, S> => {\n const ordinary = v.union([\n booleanToSelect(relation),\n buildToManyNestedNode({\n targetModel: getTargetModel(relation),\n label: nestedOmitLabel(relation),\n core: () => targetSchemas().core,\n scalarNames: nestedDistinctNames<S>(relation),\n }),\n ]);\n return withRecurrence(ordinary, relation, resolved, targetSchemas, () => ({\n where: () => targetSchemas().core.where,\n orderBy: () => termOrList(targetSchemas().core.orderBy),\n take: unavailableRecursiveClause(\"take\"),\n skip: unavailableRecursiveClause(\"skip\"),\n cursor: unavailableRecursiveClause(\"cursor\"),\n distinct: unavailableRecursiveClause(\"distinct\"),\n })) as never;\n};\n\n/**\n * Relation-level args are the same shape in select and include position\n * (Prisma parity: select/include can alternate down the relation tree)\n */\nexport type ToOneSelectSchema<\n Source extends AnyModel,\n Key,\n S extends RelationState,\n> = ToOneIncludeSchema<Source, Key, S>;\nexport const toOneSelectFactory = toOneIncludeFactory;\n\nexport type ToManySelectSchema<\n Source extends AnyModel,\n Key,\n S extends RelationState,\n> = ToManyIncludeSchema<Source, Key, S>;\nexport const toManySelectFactory = toManyIncludeFactory;\n","// The two spellings of a to-one nested `update` payload (Prisma 5).\n\nimport { isRecord } from \"../value-guards\";\n\n/**\n * Prisma 5 accepts TWO spellings for a nested `update` on a **to-one** relation:\n *\n * bare `{ author: { update: { name: \"x\" } } }`\n * wrapped `{ author: { update: { where: { active: true }, data: { name: \"x\" } } } }`\n *\n * The wrapper's `where` is a **non-unique** `WhereInput`. It does not choose among\n * candidates — a to-one has exactly one connected record — it FILTERS that record:\n * the currently connected row must satisfy it, and if it does not the whole\n * operation aborts with the not-found class, state unchanged.\n *\n * DISAMBIGUATION. An object carrying a `data` key whose value is a plain object has\n * the envelope's SHAPE. On almost every target that shape is unambiguous, because\n * `data` is not one of the target's own update keys and the bare reading could not\n * validate — so the shape IS the envelope, exactly as Prisma reads it.\n *\n * On a target that owns a field (or relation) literally named `data` — a JSON\n * document column being the common case — the same shape has TWO meanings, and they\n * write different columns:\n *\n * `update: { data: { label: \"x\" } }` envelope → sets the target's `label`\n * bare → stores `{ label: \"x\" }` in `data`\n *\n * Neither reading can be preferred without silently doing something other than what\n * the caller wrote, and \"whichever one happens to validate\" would make the FORM\n * depend on the DATA — the identical spelling meaning one thing for `{ seed: true }`\n * and another for `{ label: \"x\" }`. So this collision is REFUSED\n * ({@link AMBIGUOUS_TO_ONE_UPDATE}), and the refusal names the two unambiguous\n * spellings, both of which go through the explicit envelope:\n *\n * `update: { where: {}, data: { … } }` update the target's fields\n * `update: { where: {}, data: { data: … } }` write the target's `data` field\n *\n * A `where` key is what makes the envelope explicit (a to-one update payload has no\n * `where` of its own, so the key cannot be bare data), and an empty `where`\n * constrains nothing. A non-object payload for a `data`-named field\n * (`update: { data: 5 }`, the scalar shorthand, or any class instance — a Date, a\n * Decimal, a `JsonNull` sentinel) never had the envelope's shape and stays bare, at\n * the root and at every depth.\n *\n * The rule reads the USER's payload and is applied EXACTLY ONCE, by the schema\n * ({@link file://./update.ts}). Its output is the canonical envelope\n * ({@link ToOneUpdateEnvelope}) for BOTH spellings, so no later reader has to\n * re-derive the form. That is not a convenience — it is the only correct design:\n * an output is not a faithful witness of the form, because `core.update` rewrites\n * scalar shorthands, so a model owning a field named `data` turns the BARE\n * `{ data: 7 }` into `{ data: { set: 7 } }`, which has the envelope's shape. The\n * engine sees only outputs one level deep (the enclosing whole-args parse already\n * normalized the tree), so a second application of the rule there necessarily\n * DISAGREED with the schema's — a measured depth regression. One\n * home, one application, at the parse boundary.\n *\n * RESIDUAL, documented: a target owning a field named `where` cannot use the bare\n * spelling for it either — `{ where: …, data: … }` is read as the envelope. Reach\n * such a field through the envelope's `data`.\n */\n\n/** The three readings of a to-one nested `update` payload. */\nexport type ToOneUpdateForm = \"bare\" | \"envelope\" | \"ambiguous\";\n\n/**\n * The refusal for the one shape that has two honest meanings. Stated as the two\n * spellings that do not, because a caller who hits this needs the way out, not the\n * taxonomy.\n */\nexport const AMBIGUOUS_TO_ONE_UPDATE =\n \"Ambiguous to-one nested `update`: `{ data: … }` reads both as the `{ where?, data }` envelope and as bare update data for this target's own `data` field. Spell the envelope out — `update: { where: {}, data: { … } }` updates the target's fields (put a filter in `where` to make it conditional), and `update: { where: {}, data: { data: … } }` writes its `data` field.\" as const;\n\n/**\n * Decide which spelling a to-one `update` payload is, from the USER's payload.\n *\n * @param value - the payload as written by the caller\n * @param targetOwnsDataField - whether the target's update schema has its own\n * `data` key. When it does, the envelope's shape is ambiguous unless the payload\n * also carries `where`.\n */\nexport function readToOneUpdateForm(\n value: unknown,\n targetOwnsDataField: boolean\n): ToOneUpdateForm {\n if (!hasEnvelopeShape(value)) return \"bare\";\n if (!targetOwnsDataField) return \"envelope\";\n // `where` is not an update key, so it cannot be bare data: it says \"envelope\"\n // out loud. Prisma parity: an explicit `undefined` is an absent key.\n if (value.where !== undefined) return \"envelope\";\n return \"ambiguous\";\n}\n\n/**\n * The canonical output of a to-one nested `update` payload — what the schema emits\n * for BOTH spellings. The bare spelling yields `{ data }`; the wrapper additionally\n * carries its non-unique `where`.\n *\n * The envelope is SELF-DESCRIBING: it reads back as the envelope rather than as bare\n * data, so no reader can resolve the form differently than this schema did. Nothing\n * re-reads it through the schema today — the X1c nested-target delegation consumes\n * the parsed subtree as-is, because re-parsing a transformed value is not a no-op\n * (a JSON write's `{ set: … }` envelope is itself a legal JSON document).\n */\nexport interface ToOneUpdateEnvelope {\n readonly data: Record<string, unknown>;\n readonly where?: Record<string, unknown> | undefined;\n}\n\n/**\n * Wrap a parsed BARE payload in the canonical envelope. The wrapper spelling is\n * already in envelope shape and is emitted as parsed.\n *\n * On a target that owns a `data` field the plain `{ data }` envelope would read back\n * as AMBIGUOUS — a reader cannot see that this object is a schema OUTPUT rather than\n * a caller's payload. So for those targets the canonical envelope carries the same\n * `where` marker a caller would have to write: an empty, constraint-free one. That\n * keeps the output honest about its own form no matter who reads it.\n * {@link splitToOneUpdateTarget} drops an empty `where`, so not one compiled step\n * changes.\n */\nexport function toOneUpdateEnvelope(\n data: Record<string, unknown>,\n targetOwnsDataField: boolean\n): ToOneUpdateEnvelope {\n return targetOwnsDataField ? { where: {}, data } : { data };\n}\n\n/** A to-one `update` payload resolved to its two halves: the update `data`, and the\n * optional non-unique `filter` the connected record must satisfy. The bare spelling\n * yields no filter — byte-identical to the bare-payload reading. An empty wrapper\n * `where` (`{}`) constrains nothing, so it is dropped rather than compiled into a\n * vacuous `AND` term. */\nexport interface ToOneUpdateTarget {\n readonly data: Record<string, unknown>;\n readonly filter?: Record<string, unknown>;\n}\n\n/**\n * Read a to-one `update` schema output into its data and its optional filter.\n *\n * This is a projection of the canonical envelope, NOT a second application of the\n * disambiguation rule — the form was decided once, at the parse boundary, from the\n * user's own payload. Every caller reaches this with a value the to-one relation\n * update schema produced (the update root parses `data.<relation>` per relation, and\n * every deeper reader — including the nested-target delegation — consumes that same\n * output without parsing it again), so a non-envelope here is a broken invariant\n * rather than a user error — it fails closed.\n */\nexport function splitToOneUpdateTarget(\n parsed: ToOneUpdateEnvelope\n): ToOneUpdateTarget {\n const where = parsed.where;\n if (!where || Object.keys(where).length === 0) {\n return { data: parsed.data };\n }\n return { data: parsed.data, filter: where };\n}\n\n/** The envelope's SHAPE — a `data` key holding a plain object. Not the form: on a\n * target owning a `data` field this shape is also how bare data spells that field,\n * which is what {@link readToOneUpdateForm} arbitrates. */\nfunction hasEnvelopeShape(value: unknown): value is {\n readonly data: Record<string, unknown>;\n readonly where?: unknown;\n} {\n return (\n isPlainObject(value) &&\n Object.hasOwn(value, \"data\") &&\n isPlainObject(value.data)\n );\n}\n\n/** A PLAIN object — an object literal, or one made with a null prototype. A class\n * instance is deliberately excluded: a `Date`, a `Decimal`, a `Uint8Array` or a\n * `JsonNull` sentinel written against a `data`-named field is a VALUE, and reading\n * it as an envelope would hand the target's update schema an object with no keys. */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (!isRecord(value)) {\n return false;\n }\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n","// Relation Update Schemas\n\nimport type { AnyModel } from \"@schema/model\";\nimport {\n membershipCanBeCleared,\n slotMayBeEmpty,\n} from \"@schema/relation/clearability\";\nimport type {\n MembershipCanBeCleared,\n SlotMayBeEmpty,\n} from \"@schema/relation/static-membership\";\nimport type {\n ForeignKeyDeclaration,\n RelationState,\n} from \"@schema/relation/types\";\nimport type { ResolvedSlot } from \"@schema/validation/relation-resolution\";\nimport { refuseDefaultOnlySkipDuplicates } from \"@validation/model/args/mutation\";\nimport { createSchema, fail, ok, validateSchema } from \"../primitives/helpers\";\nimport v, { type V } from \"../primitives/v\";\nimport type { VibSchema } from \"../types\";\nimport type { NestedCreateManySchema } from \"./create\";\nimport type { GetTargetSchemas, SchemaGetter } from \"./helpers\";\nimport {\n nestedRelationDataProjection,\n type ProjectedNestedCreate,\n type ProjectedNestedUpdate,\n type ProjectedSelectedUpsertUpdate,\n} from \"./nested-data-projection\";\nimport {\n type ToOneMutationSchema,\n toOneMutationSchema,\n} from \"./to-one-mutation-schema\";\nimport {\n AMBIGUOUS_TO_ONE_UPDATE,\n readToOneUpdateForm,\n toOneUpdateEnvelope,\n} from \"./to-one-update-form\";\n\n// =============================================================================\n// UPDATE FACTORY IMPLEMENTATIONS\n// =============================================================================\n\n/**\n * The `{ where?, data }` wrapper spelling of a to-one nested `update` (Prisma 5).\n * `where` is a NON-unique `WhereInput` — a to-one has exactly one connected record,\n * so this filters that record rather than selecting among candidates.\n */\ntype ToOneUpdateWrapperSchema<\n S extends RelationState,\n UpdateSchema extends V.Object<any, any>,\n> = V.Object<\n {\n where: () => GetTargetSchemas<S>[\"core\"][\"where\"];\n data: () => UpdateSchema;\n },\n { atLeast: [\"data\"] }\n>;\n\n/**\n * A to-one nested `update` payload: bare data OR the `{ where?, data }` wrapper.\n * Dispatch is DETERMINISTIC and structural — never try-this-then-that — so a\n * malformed wrapper surfaces the wrapper's own error rather than a union-wide miss,\n * and the form a payload takes never depends on the values inside it.\n *\n * This is the ONE place the rule is applied, because it is the only place that sees\n * the USER's payload: both arms emit the same canonical `{ data, where? }` envelope,\n * so no later reader (the update root, a target one level deeper, the nested-target\n * delegation) ever has to tell the spellings apart from an output that already\n * rewrote scalar shorthands. See {@link file://./to-one-update-form.ts} for the rule,\n * and for the collision it REFUSES: on a target that owns a field named `data`, the\n * envelope's shape is also how bare data spells that field, and only the caller can\n * say which was meant.\n */\nexport type ToOneUpdateTargetWithDataSchema<\n S extends RelationState,\n UpdateSchema extends V.Object<any, any>,\n> = V.Union<readonly [ToOneUpdateWrapperSchema<S, UpdateSchema>, UpdateSchema]>;\n\nexport type ToOneUpdateTargetSchema<\n Source extends AnyModel,\n Key,\n S extends RelationState,\n> = ToOneUpdateTargetWithDataSchema<S, ProjectedNestedUpdate<Source, Key, S>>;\n\n/**\n * `getUpdateSchema` is REQUIRED — nested update data is always built from the\n * relation's nested-data projection ({@link ProjectedNestedUpdate}: the omitted-FK\n * schema for an ordinary edge, the omitted-relation-key one for a polymorphic\n * inverse). The optional parameter this used to take defaulted to the target's bare\n * `core.update`, which is precisely the schema that let a caller spell the enclosing\n * relation's foreign key (N1).\n */\nexport function toOneUpdateTargetFactory<\n S extends RelationState,\n T extends SchemaGetter<S>,\n UpdateSchema extends V.Object<any, any>,\n>(\n targetSchemas: T,\n getUpdateSchema: () => UpdateSchema\n): ToOneUpdateTargetWithDataSchema<S, UpdateSchema> {\n const updateSchema = getUpdateSchema;\n const wrapper = v.object(\n {\n where: () => targetSchemas().core.where,\n data: updateSchema,\n },\n { atLeast: [\"data\"] }\n );\n // The bare arm is reached through a thunk: building it here would resolve the\n // target model's schemas while this one is still under construction, which never\n // terminates for a self-referential relation.\n const bare = v.lazy(updateSchema);\n const members: readonly VibSchema<unknown, unknown>[] = [\n wrapper as unknown as VibSchema<unknown, unknown>,\n bare as unknown as VibSchema<unknown, unknown>,\n ];\n // Does the TARGET own an update key named `data`? Answered from the target's own\n // update schema (its entries are one key per updatable field and relation), and\n // only ONCE — but not before the first parse, because resolving the target's\n // schemas here would not terminate for a self-referential relation. An update\n // schema whose entries cannot be read is treated as owning the key: the\n // ambiguous spelling is then REFUSED rather than guessed.\n let ownsDataKey: boolean | undefined;\n const targetOwnsDataField = (): boolean => {\n if (ownsDataKey === undefined) {\n ownsDataKey = Object.hasOwn(updateSchema().entries, \"data\");\n }\n return ownsDataKey;\n };\n const schema = createSchema<unknown, unknown>(\"union\", (value) => {\n const ownsData = targetOwnsDataField();\n const form = readToOneUpdateForm(value, ownsData);\n if (form === \"ambiguous\") return fail(AMBIGUOUS_TO_ONE_UPDATE);\n if (form === \"envelope\") return validateSchema(wrapper, value);\n // The bare arm is CANONICALIZED into the same envelope the wrapper arm emits.\n // Without it, `core.update`'s scalar-shorthand rewrite makes the bare output of\n // a model owning a `data` field indistinguishable from a wrapper, and every\n // reader downstream of this parse would resolve the form differently than the\n // user wrote it.\n const parsed = validateSchema(bare, value);\n return parsed.issues\n ? parsed\n : ok(\n toOneUpdateEnvelope(parsed.value as Record<string, unknown>, ownsData)\n );\n });\n // Mirror `v.union`'s introspection surface so JSON-schema conversion sees the\n // alternatives it expects (the same shape `toOneFilterFactory` publishes).\n (schema as { options?: unknown }).options = members;\n return schema as unknown as ToOneUpdateTargetWithDataSchema<S, UpdateSchema>;\n}\n\n/**\n * To-one update: { create?, connect?, connectOrCreate?, update?, upsert?, disconnect?, delete? }\n * disconnect and delete only available for optional relations.\n */\n\ntype ToOneUpdateEntriesBase<\n Source extends AnyModel,\n Key,\n S extends RelationState,\n> = {\n create: () => ProjectedNestedCreate<Source, Key, S>;\n connect: () => GetTargetSchemas<S>[\"core\"][\"whereUnique\"];\n connectOrCreate: V.Object<\n {\n where: () => GetTargetSchemas<S>[\"core\"][\"whereUnique\"];\n create: () => ProjectedNestedCreate<Source, Key, S>;\n },\n { partial: false }\n >;\n update: () => ToOneUpdateTargetSchema<Source, Key, S>;\n upsert: V.Object<\n {\n create: () => ProjectedNestedCreate<Source, Key, S>;\n update: () => ProjectedNestedUpdate<Source, Key, S>;\n },\n { partial: false }\n >;\n};\n\ntype ToOneUpdateSchemaDisconnect = V.Object<{\n disconnect: V.Boolean;\n}>;\n\ntype ToOneUpdateSchemaDelete = V.Object<{\n delete: V.Boolean;\n}>;\n\n/** A structural prohibition that survives generic public operation arguments. */\ntype ToOneUpdateSchemaNoDisconnect = {\n disconnect: never;\n};\n\n/**\n * Does the OTHER row hold this membership? A slot that completed\n * `.fields(...).references(...)` stores it itself; everything else — an\n * inverse, a junction side, a variant inverse — reads it from elsewhere, which\n * is what the to-one mutation envelope needs to know about its own row.\n */\ntype IsChildHeldToOne<S extends RelationState> = S extends {\n readonly foreignKey: ForeignKeyDeclaration;\n}\n ? false\n : true;\n\n/**\n * The two facts, read as the two availability rules they are: `delete` follows the\n * SLOT (this branch is only reached when it may be empty), `disconnect` follows the\n * MEMBERSHIP. They coincide on every shape except one — a slot whose membership\n * lives on storage that cannot be emptied, where the record can still be deleted\n * but the connection cannot be cut.\n */\ntype OptionalToOneUpdateEntries<\n Source extends AnyModel,\n Key,\n S extends RelationState,\n> = ToOneUpdateSchemaDelete[\"entries\"] &\n (MembershipCanBeCleared<Source, Key, S> extends true\n ? ToOneUpdateSchemaDisconnect[\"entries\"]\n : ToOneUpdateSchemaNoDisconnect);\n\nexport type ToOneUpdateSchema<\n Source extends AnyModel,\n Key,\n S extends RelationState,\n> = SlotMayBeEmpty<Source, Key, S> extends false\n ? ToOneMutationSchema<\n ToOneUpdateEntriesBase<Source, Key, S>,\n undefined,\n IsChildHeldToOne<S>\n >\n : ToOneMutationSchema<\n OptionalToOneUpdateEntries<Source, Key, S> &\n ToOneUpdateEntriesBase<Source, Key, S>,\n undefined,\n IsChildHeldToOne<S>\n >;\n\nexport const toOneUpdateFactory = <\n Source extends AnyModel,\n Key,\n S extends RelationState,\n T extends SchemaGetter<S>,\n>(\n state: S,\n resolved: ResolvedSlot,\n targetSchemas: T\n): ToOneUpdateSchema<Source, Key, S> => {\n const projection = nestedRelationDataProjection<S, T>(\n resolved,\n targetSchemas\n );\n const getCreateSchema = projection.getCreateSchema;\n // The same owner, applied to nested UPDATE data. See\n // {@link ProjectedNestedUpdate} for why the two contexts share one rule.\n //\n // This omission is the SINGLE owner of the spelled-owned-FK refusal on every\n // schema. The engine guard that once backed it up\n // (`assertOwnedFkAbsentFromUpdateData`, guard-ledger site 11) is deleted: its\n // only route was a zero-argument `.fields()` one scanner read as truthy while\n // the engine read length, and both readings now come from the ONE resolved\n // edge, so the divergent payload refuses here, as `Unknown key`, like every\n // other schema's.\n const getUpdateSchema = projection.getUpdateSchema;\n\n const connectOrCreateSchema = v.object(\n {\n where: () => targetSchemas().core.whereUnique,\n create: getCreateSchema,\n },\n { partial: false }\n );\n\n const upsertSchema = v.object(\n {\n create: getCreateSchema,\n update: getUpdateSchema,\n },\n { partial: false }\n );\n\n const baseEntries = {\n create: getCreateSchema,\n connect: () => targetSchemas().core.whereUnique,\n connectOrCreate: connectOrCreateSchema,\n // Bare data OR `{ where?, data }` — the wrapper's `where` filters the\n // currently connected record (see `toOneUpdateTargetFactory`).\n update: () =>\n toOneUpdateTargetFactory<S, T, ReturnType<typeof getUpdateSchema>>(\n targetSchemas,\n getUpdateSchema\n ),\n upsert: upsertSchema,\n };\n // The DIRECTION, read from the declaration: a slot that completed\n // `.fields(...).references(...)` carries the membership on its own row.\n const isChildHeld = state.foreignKey === undefined;\n\n // The SLOT fact: a relation that must hold a record owns neither removal verb.\n if (!slotMayBeEmpty(resolved)) {\n return toOneMutationSchema(\n baseEntries,\n undefined,\n isChildHeld\n ) as unknown as ToOneUpdateSchema<Source, Key, S>;\n }\n\n // The MEMBERSHIP fact, asked from the same resolved edge: an empty slot does not\n // imply a clearable membership. An inverse whose stored reference has no nullable\n // member can lose its record but cannot cut the connection, so it publishes\n // `delete` without `disconnect`.\n return (membershipCanBeCleared(resolved)\n ? toOneMutationSchema(\n {\n ...baseEntries,\n disconnect: v.boolean(),\n delete: v.boolean(),\n },\n undefined,\n isChildHeld\n )\n : toOneMutationSchema(\n { ...baseEntries, delete: v.boolean() },\n undefined,\n isChildHeld\n )) as unknown as ToOneUpdateSchema<Source, Key, S>;\n};\n\n/**\n * To-many update: {\n * create?, createMany?, connect?, disconnect?, delete?,\n * connectOrCreate?, set?, update?, updateMany?, upsert?, deleteMany?\n * }\n * Most operations accept single or array.\n */\n\ntype ToManyUpdateEntries<\n Source extends AnyModel,\n Key,\n S extends RelationState,\n> = {\n create: () => V.SingleOrArray<ProjectedNestedCreate<Source, Key, S>>;\n createMany: NestedCreateManySchema<Source, Key, S>;\n connect: () => V.SingleOrArray<GetTargetSchemas<S>[\"core\"][\"whereUnique\"]>;\n delete: () => V.SingleOrArray<\n GetTargetSchemas<S>[\"core\"][\"whereUniqueExtended\"]\n >;\n connectOrCreate: V.SingleOrArray<\n V.Object<\n {\n where: () => GetTargetSchemas<S>[\"core\"][\"whereUnique\"];\n create: () => ProjectedNestedCreate<Source, Key, S>;\n },\n { partial: false }\n >\n >;\n set: () => V.SingleOrArray<GetTargetSchemas<S>[\"core\"][\"whereUnique\"]>;\n update: V.SingleOrArray<\n V.Object<\n {\n where: () => GetTargetSchemas<S>[\"core\"][\"whereUniqueExtended\"];\n data: () => ProjectedNestedUpdate<Source, Key, S>;\n },\n { atLeast: [\"where\", \"data\"] }\n >\n >;\n updateMany: V.SingleOrArray<\n V.Object<\n {\n where: () => GetTargetSchemas<S>[\"core\"][\"where\"];\n data: () => ProjectedNestedUpdate<Source, Key, S>;\n },\n { atLeast: [\"data\"] }\n >\n >;\n upsert: V.SingleOrArray<\n V.Object<\n {\n where: () => GetTargetSchemas<S>[\"core\"][\"whereUniqueExtended\"];\n create: () => ProjectedNestedCreate<Source, Key, S>;\n update: () => ProjectedSelectedUpsertUpdate<Source, Key, S>;\n },\n { partial: false }\n >\n >;\n deleteMany: () => V.SingleOrArray<GetTargetSchemas<S>[\"core\"][\"where\"]>;\n};\n\ntype ToManyDisconnectEntry<S extends RelationState> = {\n disconnect: () => V.SingleOrArray<GetTargetSchemas<S>[\"core\"][\"whereUnique\"]>;\n};\n\ntype ToManyNoDisconnectEntry = {\n disconnect: never;\n};\n\nexport type ToManyUpdateSchema<\n Source extends AnyModel,\n Key,\n S extends RelationState,\n> = V.Object<\n ToManyUpdateEntries<Source, Key, S> &\n (MembershipCanBeCleared<Source, Key, S> extends true\n ? ToManyDisconnectEntry<S>\n : ToManyNoDisconnectEntry)\n>;\n\nexport const toManyUpdateFactory = <\n Source extends AnyModel,\n Key,\n S extends RelationState,\n T extends SchemaGetter<S>,\n>(\n resolved: ResolvedSlot,\n targetSchemas: T\n): ToManyUpdateSchema<Source, Key, S> => {\n const projection = nestedRelationDataProjection<S, T>(\n resolved,\n targetSchemas\n );\n const getCreateSchema = projection.getCreateSchema;\n // N1 — see the to-one factory above and {@link ProjectedNestedUpdate}.\n const getUpdateSchema = projection.getUpdateSchema;\n const getSelectedUpsertUpdateSchema =\n projection.getSelectedUpsertUpdateSchema;\n\n const createManySchema = v.object(\n {\n data: () => v.array(getCreateSchema()),\n skipDuplicates: v.boolean({ optional: true }),\n },\n { atLeast: [\"data\"], refuse: refuseDefaultOnlySkipDuplicates }\n );\n\n const connectOrCreateSchema = v.object(\n {\n where: () => targetSchemas().core.whereUnique,\n create: getCreateSchema,\n },\n { partial: false }\n );\n\n const updateSchema = v.object(\n {\n where: () => targetSchemas().core.whereUniqueExtended,\n data: getUpdateSchema,\n },\n { atLeast: [\"where\", \"data\"] }\n );\n\n const updateManySchema = v.object(\n {\n where: () => targetSchemas().core.where,\n data: getUpdateSchema,\n },\n { atLeast: [\"data\"] }\n );\n\n const upsertSchema = v.object(\n {\n where: () => targetSchemas().core.whereUniqueExtended,\n create: getCreateSchema,\n update: getSelectedUpsertUpdateSchema,\n },\n { partial: false }\n );\n\n // ONE expression, one owner. A junction membership always clears — the junction\n // row goes and no column on either row is nulled — and that is the answer the\n // clearability owner gives for an ordinary junction, for a member junction, and\n // for a PLURAL variant collection inverse alike (§9.5). A to-many slot whose\n // partner holds a stored reference clears exactly when that reference has a\n // nullable member. There is no second cardinality test here any more.\n const disconnectEntry = membershipCanBeCleared(resolved)\n ? {\n disconnect: () => v.singleOrArray(targetSchemas().core.whereUnique),\n }\n : {};\n\n return v.object({\n create: () => v.singleOrArray(getCreateSchema()),\n createMany: createManySchema,\n connect: () => v.singleOrArray(targetSchemas().core.whereUnique),\n ...disconnectEntry,\n delete: () => v.singleOrArray(targetSchemas().core.whereUniqueExtended),\n connectOrCreate: v.singleOrArray(connectOrCreateSchema),\n set: () => v.singleOrArray(targetSchemas().core.whereUnique),\n update: v.singleOrArray(updateSchema),\n updateMany: v.singleOrArray(updateManySchema),\n upsert: v.singleOrArray(upsertSchema),\n deleteMany: () => v.singleOrArray(targetSchemas().core.where),\n }) as unknown as ToManyUpdateSchema<Source, Key, S>;\n};\n","// Relation Schema Factories\n// Builds filter, create, update schemas for relations using Valibot\nimport type { RelationState } from \"@schema/relation/types\";\n\nexport { countFilterFactory } from \"./count-filter\";\nexport { toManyCreateFactory, toOneCreateFactory } from \"./create\";\nexport { toManyFilterFactory, toOneFilterFactory } from \"./filter\";\nexport { toManyOrderByFactory, toOneOrderByFactory } from \"./order-by\";\n// Re-export individual schema factories\nexport {\n toManyIncludeFactory,\n toManySelectFactory,\n toOneIncludeFactory,\n toOneSelectFactory,\n} from \"./select-include\";\nexport {\n toManyUpdateFactory,\n toOneUpdateFactory,\n toOneUpdateTargetFactory,\n} from \"./update\";\n\nimport { ValidationError } from \"@errors\";\nimport type { AnyModel } from \"@schema/model\";\nimport { type AnyRelation, isVariantRelationState } from \"@schema/relation\";\nimport type { Cardinality } from \"@schema/relation/static-membership\";\nimport type { ResolvedSlot } from \"@schema/validation/relation-resolution\";\nimport { lazyRecord } from \"../lazy\";\nimport v from \"../primitives/v\";\nimport { type CountFilterSchema, countFilterFactory } from \"./count-filter\";\nimport {\n type ToManyCreateSchema,\n type ToOneCreateSchema,\n toManyCreateFactory,\n toOneCreateFactory,\n} from \"./create\";\nimport {\n type ToManyFilterSchema,\n type ToOneFilterSchema,\n toManyFilterFactory,\n toOneFilterFactory,\n} from \"./filter\";\nimport type { SchemaGetter } from \"./helpers\";\nimport {\n type ToManyOrderBySchema,\n type ToOneOrderBySchema,\n toManyOrderByFactory,\n toOneOrderByFactory,\n} from \"./order-by\";\n// Import for internal use\nimport {\n type ToManyIncludeSchema,\n type ToManySelectSchema,\n type ToOneIncludeSchema,\n type ToOneSelectSchema,\n toManyIncludeFactory,\n toManySelectFactory,\n toOneIncludeFactory,\n toOneSelectFactory,\n} from \"./select-include\";\nimport {\n type ToManyUpdateSchema,\n type ToOneUpdateSchema,\n toManyUpdateFactory,\n toOneUpdateFactory,\n} from \"./update\";\n\n// =============================================================================\n// SCHEMA BUNDLES\n// =============================================================================\n\nconst toOneSchemas = <\n Source extends AnyModel,\n Key,\n S extends RelationState,\n T extends SchemaGetter<S>,\n>(\n relation: AnyRelation,\n resolved: ResolvedSlot,\n targetSchemas: T\n) => {\n const state = relation[\"~\"].state as S;\n return {\n filter: v.lazy(() =>\n toOneFilterFactory<Source, Key, S, T>(resolved, targetSchemas)\n ),\n create: v.lazy(() =>\n toOneCreateFactory<Source, Key, S, T>(resolved, targetSchemas)\n ),\n update: v.lazy(() =>\n toOneUpdateFactory<Source, Key, S, T>(state, resolved, targetSchemas)\n ),\n select: v.lazy(() =>\n toOneSelectFactory<Source, Key, S, T>(relation, resolved, targetSchemas)\n ),\n include: v.lazy(() =>\n toOneIncludeFactory<Source, Key, S, T>(relation, resolved, targetSchemas)\n ),\n orderBy: toOneOrderByFactory<S, T>(relation, targetSchemas),\n countFilter: v.lazy(() => countFilterFactory(state, targetSchemas)),\n };\n};\n\nconst toManySchemas = <\n Source extends AnyModel,\n Key,\n S extends RelationState,\n T extends SchemaGetter<S>,\n>(\n relation: AnyRelation,\n resolved: ResolvedSlot,\n targetSchemas: T\n) => {\n const state = relation[\"~\"].state as S;\n return {\n filter: v.lazy(() =>\n toManyFilterFactory<Source, Key, S, T>(resolved, targetSchemas)\n ),\n create: v.lazy(() =>\n toManyCreateFactory<Source, Key, S, T>(resolved, targetSchemas)\n ),\n update: v.lazy(() =>\n toManyUpdateFactory<Source, Key, S, T>(resolved, targetSchemas)\n ),\n select: v.lazy(() =>\n toManySelectFactory<Source, Key, S, T>(relation, resolved, targetSchemas)\n ),\n include: v.lazy(() =>\n toManyIncludeFactory<Source, Key, S, T>(relation, resolved, targetSchemas)\n ),\n orderBy: v.lazy(() => toManyOrderByFactory(state)),\n countFilter: v.lazy(() => countFilterFactory(state, targetSchemas)),\n };\n};\n\n// =============================================================================\n// TYPE INFERENCE\n// =============================================================================\n\nexport type ToOneSchemas<\n Source extends AnyModel,\n Key,\n S extends RelationState,\n> = {\n filter: ToOneFilterSchema<Source, Key, S>;\n create: ToOneCreateSchema<Source, Key, S>;\n update: ToOneUpdateSchema<Source, Key, S>;\n select: ToOneSelectSchema<Source, Key, S>;\n include: ToOneIncludeSchema<Source, Key, S>;\n orderBy: ToOneOrderBySchema<S>;\n countFilter: CountFilterSchema<S>;\n};\n\nexport type ToManySchemas<\n Source extends AnyModel,\n Key,\n S extends RelationState,\n> = {\n filter: ToManyFilterSchema<Source, Key, S>;\n create: ToManyCreateSchema<Source, Key, S>;\n update: ToManyUpdateSchema<Source, Key, S>;\n select: ToManySelectSchema<Source, Key, S>;\n include: ToManyIncludeSchema<Source, Key, S>;\n orderBy: ToManyOrderBySchema<S>;\n countFilter: CountFilterSchema<S>;\n};\n\n/**\n * A relation's schemas are decided by ITS OWN cardinality, and by nothing else.\n *\n * This is the FIRST step of §8.2's dispatch — cardinality, then target kind,\n * then resolved membership. The target-kind step lives one level up\n * (`getPolymorphicRelationsSchemas` owns the variant half's eight families);\n * the membership step lives inside the create/update families, where the\n * projection and the clearability owner answer it.\n *\n * The polymorphic-inverse dispatch that used to live here — a second to-one and a\n * second to-many family, spelled key by key — is gone: what differs about a\n * ROW-HELD variant inverse is which target schema its nested payloads write\n * into and whether its membership can be cleared, and both facts are now the\n * `nested-data-projection` and `clearability` owners', read by the same four\n * verb factories.\n *\n * BOTH COLLECTION INVERSE ARITIES ARE ORDINARY. A variant-bound to-many is a\n * fixed-variant junction VIEW (§9.5): the binder supplies the same\n * `ResolvedJunctionTopology` in reverse orientation, and `RelationJunctionPart` /\n * `JunctionStatements` — written entirely against `membership.source` /\n * `membership.target` — own every verb unchanged. A variant-bound singular slot\n * is one member-junction row under a UNIQUE over the complete variant side,\n * which is a to-one slot with a to-one slot's vocabulary.\n * `RelationJunctionToOnePart` lowers its four correlated spellings, so the\n * ordinary to-one families serve it verbatim and there is nothing left here to\n * substitute.\n *\n * The removal verbs hang on the two derived facts alone — `slotMayBeEmpty` and\n * `membershipCanBeCleared`, both read from the ONE resolved edge — rather than\n * on a declared flag a schema author had to remember to write.\n */\nexport type GetRelationSchemas<\n Source extends AnyModel,\n Key,\n S extends RelationState,\n> = Cardinality<S> extends \"many\"\n ? ToManySchemas<Source, Key, S>\n : ToOneSchemas<Source, Key, S>;\n\n// =============================================================================\n// MAIN EXPORT\n// =============================================================================\n\n/** Get all schemas for a relation, from its own cardinality. */\nexport const getRelationSchemas = <\n Source extends AnyModel,\n Key,\n S extends RelationState,\n T extends SchemaGetter<S>,\n>(\n relation: AnyRelation,\n resolved: ResolvedSlot,\n targetSchemas: T\n) => {\n const isToMany = relation[\"~\"].state.cardinality === \"many\";\n // The bundle builders are left to INFER, so the union each write family really\n // carries is visible inside this function; {@link GetRelationSchemas} is the\n // type-level owner of which arm a given `<Source, Key, S>` lands on, and this is\n // the single seam where the two meet — the same boundary crossing this return\n // has always performed.\n return (isToMany\n ? toManySchemas<Source, Key, S, T>(relation, resolved, targetSchemas)\n : toOneSchemas<Source, Key, S, T>(\n relation,\n resolved,\n targetSchemas\n )) as unknown as GetRelationSchemas<Source, Key, S>;\n};\n\n/**\n * Every MODEL-target relation of one model, keyed by its own field key.\n *\n * The key is not decoration: it is the asking-slot identity the static\n * membership projection excludes in step 2, and a projection that dropped it\n * would let a self relation select its own declaration as its inverse.\n */\nexport const getRelationsSchemas = <Source extends AnyModel>(\n source: Source,\n createSchemasGetter: <S extends RelationState>(\n relation: AnyRelation\n ) => SchemaGetter<S>,\n slots: ReadonlyMap<string, ResolvedSlot>\n) => {\n // Build each relation's schemas lazily: a relation's filter/create/update/\n // select/include schemas are only constructed when that relation is first\n // referenced (via `v.fromObject(relations, \"<subkey>\")`). A query that\n // touches no relations (e.g. findUnique by id) builds none of them.\n const builders: Record<string, () => unknown> = {};\n const relations: Record<string, AnyRelation> = source[\"~\"].state.relations;\n for (const field in relations) {\n const relation = relations[field]!;\n if (isVariantRelationState(relation[\"~\"].state)) continue;\n const resolved = resolvedSlotOrThrow(source, field, slots);\n builders[field] = () => {\n const targetSchemas = createSchemasGetter(relation);\n return getRelationSchemas(relation, resolved, targetSchemas);\n };\n }\n return lazyRecord(builders) as GetRelationsSchemas<Source>;\n};\n\n/**\n * The registry's operation schemas ARE topology answers — which mutation verbs a\n * caller may spell, which keys a nested payload owns — so a registry built over\n * an index that does not describe this schema has no answer to give. That is a\n * different failure from an invalid schema (the definition gate owns that one):\n * it means two different schema objects were composed at one boundary.\n */\nconst resolvedSlotOrThrow = (\n source: AnyModel,\n field: string,\n slots: ReadonlyMap<string, ResolvedSlot>\n): ResolvedSlot => {\n const resolved = slots.get(field);\n if (resolved) return resolved;\n const model = source[\"~\"].names.ts ?? \"model\";\n throw new ValidationError({ kind: \"registry\", property: field }, [\n {\n path: `${model}.${field}`,\n message: `The resolved relation index does not describe '${model}.${field}'`,\n },\n ]);\n};\n\n/** The MODEL-target keys of a relation map — the half this module owns. */\ntype ModelRelationKeys<Relations> = {\n [Key in keyof Relations]: Relations[Key] extends {\n readonly \"~\": {\n readonly state: { readonly target: { readonly kind: \"variants\" } };\n };\n }\n ? never\n : Key;\n}[keyof Relations];\n\nexport type GetRelationsSchemas<Source extends AnyModel> = {\n [R in ModelRelationKeys<\n Source[\"~\"][\"state\"][\"relations\"]\n >]: GetRelationSchemas<\n Source,\n R,\n Source[\"~\"][\"state\"][\"relations\"][R][\"~\"][\"state\"]\n >;\n};\n","import type { VariantRelationState } from \"@schema/relation\";\nimport type { VariantEntries } from \"@schema/relation/static-membership\";\nimport type { InferInput, InferOutput, VibSchema } from \"@validation/types\";\n\n/**\n * The slice of a target model's `ModelSchemas` a polymorphic family reaches\n * for. The runtime value is always the full `ModelSchemas`; this interface is\n * the DECLARED reach, and it is the thing hand-built doubles in the type tests\n * must satisfy.\n *\n * `orderBy` is here because a COLLECTION arm node is the ordinary to-many nested\n * node (`buildToManyNestedNode`), which offers `orderBy` on the related model.\n * The to-one families never asked for it, which is why it was absent.\n *\n * `whereUniqueExtended` is here because the COLLECTION WRITE family addresses a\n * member exactly where the ordinary to-many operation does (`toManyUpdateFactory`:\n * `update`, `upsert` and `delete` all take it). That is a deliberate divergence\n * from the to-one polymorphic `update`, whose `where` merely FILTERS the one\n * connected record and is therefore the plain `where` — a slot already names its\n * target, a collection member does not.\n */\ninterface PolymorphicTargetSchemas {\n readonly core: {\n readonly create: VibSchema;\n readonly update: VibSchema;\n readonly where: VibSchema;\n readonly whereUnique: VibSchema;\n readonly whereUniqueExtended: VibSchema;\n readonly orderBy: VibSchema;\n readonly select: VibSchema;\n readonly include: VibSchema;\n readonly omit: VibSchema;\n };\n}\n\nexport type PolymorphicTargetSchemaGetters<State extends VariantRelationState> =\n {\n readonly [PublicType in keyof VariantEntries<State>]: () => PolymorphicTargetSchemas;\n };\n\nexport type ExactPolymorphicTargetSchemaGetters<\n State extends VariantRelationState,\n Getters extends PolymorphicTargetSchemaGetters<State>,\n> = Getters &\n Record<Exclude<keyof Getters, keyof VariantEntries<State>>, never>;\n\ntype SchemasAt<\n Getters,\n PublicType extends keyof Getters,\n> = Getters[PublicType] extends () => infer Schemas ? Schemas : never;\n\ntype CoreSchemaAt<\n Getters,\n PublicType extends keyof Getters,\n CoreKey extends PropertyKey,\n> = SchemasAt<Getters, PublicType> extends {\n readonly core: infer Core;\n}\n ? CoreKey extends keyof Core\n ? Core[CoreKey]\n : never\n : never;\n\nexport type CoreInputAt<\n Getters,\n PublicType extends keyof Getters,\n CoreKey extends PropertyKey,\n> = InferInput<CoreSchemaAt<Getters, PublicType, CoreKey>>;\n\nexport type CoreOutputAt<\n Getters,\n PublicType extends keyof Getters,\n CoreKey extends PropertyKey,\n> = InferOutput<CoreSchemaAt<Getters, PublicType, CoreKey>>;\n\nexport type PolymorphicSchema<Input, Output = Input> = VibSchema<Input, Output>;\n\nexport const polymorphicPublicTypes = <State extends VariantRelationState>(\n state: State\n): Extract<keyof VariantEntries<State>, string>[] =>\n Object.keys(state.target.entries) as Extract<\n keyof VariantEntries<State>,\n string\n >[];\n","import type { VariantRelationState } from \"@schema/relation\";\nimport type { VariantEntries } from \"@schema/relation/static-membership\";\nimport { refuseDefaultOnlySkipDuplicates } from \"@validation/model/args/mutation\";\nimport v from \"@validation/primitives/v\";\nimport type { VibSchema } from \"@validation/types\";\nimport type {\n CoreInputAt,\n CoreOutputAt,\n ExactPolymorphicTargetSchemaGetters,\n PolymorphicTargetSchemaGetters,\n} from \"./types\";\nimport { polymorphicPublicTypes } from \"./types\";\n\n/**\n * THE DIRECT POLYMORPHIC COLLECTION WRITE GRAMMAR (plan §9.1).\n *\n * Every verb value is a UNION over the configured public types, and the\n * discriminator/payload correlation is a free property of that union — the same\n * idiom the two to-one families use (`polymorphic/create.ts`), for the same\n * reason: a direct payload carries its discriminator INSIDE each verb, so no\n * projection the enclosing edge applies can say what a variant's `where` or\n * `data` means.\n *\n * THREE DELIBERATE DIVERGENCES, each recorded where it is spelled:\n *\n * 1. **`singleOrArray` on EVERY verb, `createMany` included.** §9.1's \"`createMany`\n * remains a group\" constrains the INNER shape (a `{data, skipDuplicates}`\n * envelope), not the arity: a mixed-variant call needs several groups, one per\n * variant, and the plan's own example spells `createMany: [ {type,data,…} ]`.\n * The ordinary nested `createMany` is a BARE object (`create.ts` /\n * `update.ts`); this one is not, and that is the divergence.\n *\n * 2. **The bags are plain `v.object`s, never `toOneMutationSchema`.** Reaching for\n * the to-one envelope would import `enforceCompositionLattice`'s `exactlyOne`\n * rule, which refuses BOTH zero active keys and two — and a collection is\n * exactly the shape where several verbs legitimately coexist (`disconnect` some,\n * `create` others) and where an empty bag is inert rather than malformed.\n *\n * 3. **No `upsert` in the CREATE bag** — see {@link polymorphicCollectionCreateFactory}.\n *\n * `disconnect` is UNCONDITIONAL, unlike the ordinary to-many factory's\n * clearability-gated entry: a member junction row always clears, because the row\n * goes and no column is nulled. There is no `disconnect: true` spelling at all —\n * §9.2 gives `set: []` that meaning, so the junction estate's\n * `m2mDisconnectRequiresSelector` refusal stays unreachable from this grammar.\n */\n\ntype TaggedWhere<Getters, CoreKey extends PropertyKey> = {\n [PublicType in Extract<keyof Getters, string>]: {\n readonly type: PublicType;\n readonly where: CoreInputAt<Getters, PublicType, CoreKey>;\n };\n}[Extract<keyof Getters, string>];\n\ntype TaggedWhereOutput<Getters, CoreKey extends PropertyKey> = {\n [PublicType in Extract<keyof Getters, string>]: {\n readonly type: PublicType;\n readonly where: CoreOutputAt<Getters, PublicType, CoreKey>;\n };\n}[Extract<keyof Getters, string>];\n\ntype TaggedCreateInput<Getters> = {\n [PublicType in Extract<keyof Getters, string>]: {\n readonly type: PublicType;\n readonly data: CoreInputAt<Getters, PublicType, \"create\">;\n };\n}[Extract<keyof Getters, string>];\n\ntype TaggedCreateOutput<Getters> = {\n [PublicType in Extract<keyof Getters, string>]: {\n readonly type: PublicType;\n readonly data: CoreOutputAt<Getters, PublicType, \"create\">;\n };\n}[Extract<keyof Getters, string>];\n\ntype TaggedConnectOrCreateInput<Getters> = {\n [PublicType in Extract<keyof Getters, string>]: {\n readonly type: PublicType;\n readonly where: CoreInputAt<Getters, PublicType, \"whereUnique\">;\n readonly create: CoreInputAt<Getters, PublicType, \"create\">;\n };\n}[Extract<keyof Getters, string>];\n\ntype TaggedConnectOrCreateOutput<Getters> = {\n [PublicType in Extract<keyof Getters, string>]: {\n readonly type: PublicType;\n readonly where: CoreOutputAt<Getters, PublicType, \"whereUnique\">;\n readonly create: CoreOutputAt<Getters, PublicType, \"create\">;\n };\n}[Extract<keyof Getters, string>];\n\ntype TaggedUpdateInput<Getters> = {\n [PublicType in Extract<keyof Getters, string>]: {\n readonly type: PublicType;\n readonly where: CoreInputAt<Getters, PublicType, \"whereUniqueExtended\">;\n readonly data: CoreInputAt<Getters, PublicType, \"update\">;\n };\n}[Extract<keyof Getters, string>];\n\ntype TaggedUpdateOutput<Getters> = {\n [PublicType in Extract<keyof Getters, string>]: {\n readonly type: PublicType;\n readonly where: CoreOutputAt<Getters, PublicType, \"whereUniqueExtended\">;\n readonly data: CoreOutputAt<Getters, PublicType, \"update\">;\n };\n}[Extract<keyof Getters, string>];\n\ntype TaggedUpdateManyInput<Getters> = {\n [PublicType in Extract<keyof Getters, string>]: {\n readonly type: PublicType;\n readonly where?: CoreInputAt<Getters, PublicType, \"where\">;\n readonly data: CoreInputAt<Getters, PublicType, \"update\">;\n };\n}[Extract<keyof Getters, string>];\n\ntype TaggedUpdateManyOutput<Getters> = {\n [PublicType in Extract<keyof Getters, string>]: {\n readonly type: PublicType;\n readonly where?: CoreOutputAt<Getters, PublicType, \"where\">;\n readonly data: CoreOutputAt<Getters, PublicType, \"update\">;\n };\n}[Extract<keyof Getters, string>];\n\ntype TaggedUpsertInput<Getters> = {\n [PublicType in Extract<keyof Getters, string>]: {\n readonly type: PublicType;\n readonly where: CoreInputAt<Getters, PublicType, \"whereUniqueExtended\">;\n readonly create: CoreInputAt<Getters, PublicType, \"create\">;\n readonly update: CoreInputAt<Getters, PublicType, \"update\">;\n };\n}[Extract<keyof Getters, string>];\n\ntype TaggedUpsertOutput<Getters> = {\n [PublicType in Extract<keyof Getters, string>]: {\n readonly type: PublicType;\n readonly where: CoreOutputAt<Getters, PublicType, \"whereUniqueExtended\">;\n readonly create: CoreOutputAt<Getters, PublicType, \"create\">;\n readonly update: CoreOutputAt<Getters, PublicType, \"update\">;\n };\n}[Extract<keyof Getters, string>];\n\ntype TaggedCreateManyInput<Getters> = {\n [PublicType in Extract<keyof Getters, string>]: {\n readonly type: PublicType;\n readonly data: readonly CoreInputAt<Getters, PublicType, \"create\">[];\n readonly skipDuplicates?: boolean;\n };\n}[Extract<keyof Getters, string>];\n\ntype TaggedCreateManyOutput<Getters> = {\n [PublicType in Extract<keyof Getters, string>]: {\n readonly type: PublicType;\n readonly data: readonly CoreOutputAt<Getters, PublicType, \"create\">[];\n readonly skipDuplicates?: boolean;\n };\n}[Extract<keyof Getters, string>];\n\n/** Every verb accepts one tagged item or a list of them, and normalizes to a list. */\ntype Many<Value> = Value | readonly Value[];\n\n/** The four supply verbs a FRESH owner can name. Declaration order is message order. */\nexport interface PolymorphicCollectionCreateInput<Getters> {\n readonly create?: Many<TaggedCreateInput<Getters>>;\n readonly createMany?: Many<TaggedCreateManyInput<Getters>>;\n readonly connect?: Many<TaggedWhere<Getters, \"whereUnique\">>;\n readonly connectOrCreate?: Many<TaggedConnectOrCreateInput<Getters>>;\n}\n\nexport interface PolymorphicCollectionCreateOutput<Getters> {\n readonly create?: readonly TaggedCreateOutput<Getters>[];\n readonly createMany?: readonly TaggedCreateManyOutput<Getters>[];\n readonly connect?: readonly TaggedWhereOutput<Getters, \"whereUnique\">[];\n readonly connectOrCreate?: readonly TaggedConnectOrCreateOutput<Getters>[];\n}\n\n/** All eleven §9.1 verbs, on a LOCATED owner. */\nexport interface PolymorphicCollectionUpdateInput<Getters> {\n readonly create?: Many<TaggedCreateInput<Getters>>;\n readonly createMany?: Many<TaggedCreateManyInput<Getters>>;\n readonly connect?: Many<TaggedWhere<Getters, \"whereUnique\">>;\n readonly connectOrCreate?: Many<TaggedConnectOrCreateInput<Getters>>;\n readonly set?: Many<TaggedWhere<Getters, \"whereUnique\">>;\n readonly disconnect?: Many<TaggedWhere<Getters, \"whereUnique\">>;\n readonly delete?: Many<TaggedWhere<Getters, \"whereUniqueExtended\">>;\n readonly deleteMany?: Many<TaggedWhere<Getters, \"where\">>;\n readonly update?: Many<TaggedUpdateInput<Getters>>;\n readonly updateMany?: Many<TaggedUpdateManyInput<Getters>>;\n readonly upsert?: Many<TaggedUpsertInput<Getters>>;\n}\n\nexport interface PolymorphicCollectionUpdateOutput<Getters> {\n readonly create?: readonly TaggedCreateOutput<Getters>[];\n readonly createMany?: readonly TaggedCreateManyOutput<Getters>[];\n readonly connect?: readonly TaggedWhereOutput<Getters, \"whereUnique\">[];\n readonly connectOrCreate?: readonly TaggedConnectOrCreateOutput<Getters>[];\n readonly set?: readonly TaggedWhereOutput<Getters, \"whereUnique\">[];\n readonly disconnect?: readonly TaggedWhereOutput<Getters, \"whereUnique\">[];\n readonly delete?: readonly TaggedWhereOutput<\n Getters,\n \"whereUniqueExtended\"\n >[];\n readonly deleteMany?: readonly TaggedWhereOutput<Getters, \"where\">[];\n readonly update?: readonly TaggedUpdateOutput<Getters>[];\n readonly updateMany?: readonly TaggedUpdateManyOutput<Getters>[];\n readonly upsert?: readonly TaggedUpsertOutput<Getters>[];\n}\n\nexport type PolymorphicCollectionCreateSchema<Getters> = VibSchema<\n PolymorphicCollectionCreateInput<Getters> | undefined,\n PolymorphicCollectionCreateOutput<Getters> | undefined\n>;\n\nexport type PolymorphicCollectionUpdateSchema<Getters> = VibSchema<\n PolymorphicCollectionUpdateInput<Getters>,\n PolymorphicCollectionUpdateOutput<Getters>\n>;\n\n/**\n * One verb's tagged union, built the way the to-one families build theirs: one\n * `v.object` per configured public type, discriminated by a `type` literal.\n */\ntype TaggedVerbOptions = ({ partial: false } | { atLeast: string[] }) & {\n refuse?: (value: Record<string, unknown>) => string | undefined;\n};\n\nfunction taggedVerb<State extends VariantRelationState>(\n publicTypes: readonly Extract<keyof VariantEntries<State>, string>[],\n fields: (\n publicType: Extract<keyof VariantEntries<State>, string>\n ) => Record<string, unknown>,\n options: TaggedVerbOptions\n): VibSchema {\n return v.singleOrArray(\n v.union(\n publicTypes.map((publicType) =>\n v.object(\n {\n type: v.literal(publicType),\n ...fields(publicType),\n },\n options\n )\n )\n )\n ) as unknown as VibSchema;\n}\n\ninterface CollectionVerbs {\n readonly create: VibSchema;\n readonly createMany: VibSchema;\n readonly connect: VibSchema;\n readonly connectOrCreate: VibSchema;\n readonly set: VibSchema;\n readonly disconnect: VibSchema;\n readonly delete: VibSchema;\n readonly deleteMany: VibSchema;\n readonly update: VibSchema;\n readonly updateMany: VibSchema;\n readonly upsert: VibSchema;\n}\n\n/** THE ELEVEN VERB BUILDERS — one owner, read by both context bags. */\nfunction collectionVerbs<\n State extends VariantRelationState,\n Getters extends PolymorphicTargetSchemaGetters<State>,\n>(\n state: State,\n targetSchemas: ExactPolymorphicTargetSchemaGetters<State, Getters>\n): CollectionVerbs {\n const schemaGetters: PolymorphicTargetSchemaGetters<State> = targetSchemas;\n const publicTypes = polymorphicPublicTypes(state);\n const tagged = (\n fields: (\n publicType: Extract<keyof VariantEntries<State>, string>\n ) => Record<string, unknown>,\n options: TaggedVerbOptions = { partial: false }\n ) => taggedVerb<State>(publicTypes, fields, options);\n\n return {\n create: tagged((publicType) => ({\n data: () => schemaGetters[publicType]().core.create,\n })),\n // The GROUP shape §9.1 pins — a `{data: [...], skipDuplicates?}` envelope —\n // carried per variant, several groups per call.\n createMany: tagged(\n (publicType) => ({\n data: () => v.array(schemaGetters[publicType]().core.create),\n skipDuplicates: v.boolean({ optional: true }),\n }),\n // The same admission fact the root and nested `createMany` arms ask\n // ({@link refuseDefaultOnlySkipDuplicates}): this group is the third\n // place the verb is spelled, and a default-only row has no conflict\n // target to suppress on here either.\n { atLeast: [\"type\", \"data\"], refuse: refuseDefaultOnlySkipDuplicates }\n ),\n connect: tagged((publicType) => ({\n where: () => schemaGetters[publicType]().core.whereUnique,\n })),\n connectOrCreate: tagged((publicType) => ({\n where: () => schemaGetters[publicType]().core.whereUnique,\n create: () => schemaGetters[publicType]().core.create,\n })),\n set: tagged((publicType) => ({\n where: () => schemaGetters[publicType]().core.whereUnique,\n })),\n // UNCONDITIONAL: a member junction row always clears.\n disconnect: tagged((publicType) => ({\n where: () => schemaGetters[publicType]().core.whereUnique,\n })),\n delete: tagged((publicType) => ({\n where: () => schemaGetters[publicType]().core.whereUniqueExtended,\n })),\n deleteMany: tagged((publicType) => ({\n where: () => schemaGetters[publicType]().core.where,\n })),\n // `where` is MANDATORY and EXTENDED — exactly where the ordinary to-many\n // `update` addresses its member, and deliberately NOT the to-one polymorphic\n // reading where `where` merely filters the one connected record.\n update: tagged(\n (publicType) => ({\n where: () => schemaGetters[publicType]().core.whereUniqueExtended,\n data: () => schemaGetters[publicType]().core.update,\n }),\n { atLeast: [\"type\", \"where\", \"data\"] }\n ),\n updateMany: tagged(\n (publicType) => ({\n where: () => schemaGetters[publicType]().core.where,\n data: () => schemaGetters[publicType]().core.update,\n }),\n { atLeast: [\"type\", \"data\"] }\n ),\n upsert: tagged((publicType) => ({\n where: () => schemaGetters[publicType]().core.whereUniqueExtended,\n create: () => schemaGetters[publicType]().core.create,\n update: () => schemaGetters[publicType]().core.update,\n })),\n };\n}\n\n/**\n * The CREATE-context bag: four supply verbs, and **no `upsert`**.\n *\n * The ordinary `ToManyCreateSchema` carries a Prisma-superset `upsert` with\n * global-lookup / adopt-and-update semantics. The collection omits it, and the\n * asymmetry is deliberate: §9.2 gives the collection `upsert` UPDATE-context\n * semantics — the found arm is scoped to THIS owner's membership — and a fresh\n * owner has no membership to scope to. The only two readings left would be a\n * silent global adopt (a different verb wearing this name) or a refusal at\n * compile time in the engine (a grammar that accepts what it cannot execute).\n * Omitting the key says the same thing once, at the boundary.\n */\nexport function polymorphicCollectionCreateFactory<\n State extends VariantRelationState,\n Getters extends PolymorphicTargetSchemaGetters<State>,\n>(\n state: State,\n targetSchemas: ExactPolymorphicTargetSchemaGetters<State, Getters>\n): PolymorphicCollectionCreateSchema<Getters> {\n const verbs = collectionVerbs(state, targetSchemas);\n return v.object(\n {\n create: verbs.create,\n createMany: verbs.createMany,\n connect: verbs.connect,\n connectOrCreate: verbs.connectOrCreate,\n },\n { optional: true }\n ) as unknown as PolymorphicCollectionCreateSchema<Getters>;\n}\n\n/** The UPDATE-context bag: all eleven §9.1 verbs, every one of them optional. */\nexport function polymorphicCollectionUpdateFactory<\n State extends VariantRelationState,\n Getters extends PolymorphicTargetSchemaGetters<State>,\n>(\n state: State,\n targetSchemas: ExactPolymorphicTargetSchemaGetters<State, Getters>\n): PolymorphicCollectionUpdateSchema<Getters> {\n const verbs = collectionVerbs(state, targetSchemas);\n return v.object({\n create: verbs.create,\n createMany: verbs.createMany,\n connect: verbs.connect,\n connectOrCreate: verbs.connectOrCreate,\n set: verbs.set,\n disconnect: verbs.disconnect,\n delete: verbs.delete,\n deleteMany: verbs.deleteMany,\n update: verbs.update,\n updateMany: verbs.updateMany,\n upsert: verbs.upsert,\n }) as unknown as PolymorphicCollectionUpdateSchema<Getters>;\n}\n","import type { VariantRelationState } from \"@schema/relation\";\nimport v from \"@validation/primitives/v\";\nimport type {\n CoreInputAt,\n CoreOutputAt,\n PolymorphicTargetSchemaGetters,\n} from \"./types\";\nimport { polymorphicPublicTypes } from \"./types\";\n\n/**\n * THE TAGGED TARGET PREDICATE — `{ type }`, `{ type, is }`, `{ type, isNot }`,\n * unioned over every configured public discriminator.\n *\n * One shape, three consumers, one owner:\n * - the to-one `filter` family (`./filter.ts`), where it sits beside the\n * null-presence arms an optional slot adds;\n * - a collection's `{ some | every | none }` quantifiers, which have NO\n * presence arm at all (an empty collection is not a null one);\n * - a collection's filtered `_count` (`./count-filter.ts`).\n *\n * It is a FUNCTION of the state, not a shared singleton: `is`/`isNot` resolve\n * through the per-variant `where` thunk, so the schema each caller receives is\n * bound to that caller's target getters.\n *\n * `{ partial: false }` on every member is what makes `type` mandatory and the\n * union's arms mutually exclusive — `{ type, is, isNot }` matches none of them.\n */\n\ntype TaggedPredicateFor<Getters, PublicType extends keyof Getters, IsAt> =\n | { readonly type: PublicType; readonly is?: never; readonly isNot?: never }\n | {\n readonly type: PublicType;\n readonly is: IsAt;\n readonly isNot?: never;\n }\n | {\n readonly type: PublicType;\n readonly is?: never;\n readonly isNot: IsAt;\n };\n\n/** The value a caller writes: one tagged arm per configured variant. */\nexport type TaggedPredicateInput<Getters> = {\n [PublicType in keyof Getters]: TaggedPredicateFor<\n Getters,\n PublicType,\n CoreInputAt<Getters, PublicType, \"where\">\n >;\n}[keyof Getters];\n\n/** The value the engine receives, with each variant's `where` parsed. */\nexport type TaggedPredicateOutput<Getters> = {\n [PublicType in keyof Getters]: TaggedPredicateFor<\n Getters,\n PublicType,\n CoreOutputAt<Getters, PublicType, \"where\">\n >;\n}[keyof Getters];\n\nexport function taggedTargetPredicate<State extends VariantRelationState>(\n state: State,\n targetSchemas: PolymorphicTargetSchemaGetters<State>\n) {\n const targetMembers = polymorphicPublicTypes(state).flatMap((publicType) => {\n const schemas = targetSchemas[publicType];\n return [\n v.object({ type: v.literal(publicType) }, { partial: false }),\n v.object(\n {\n type: v.literal(publicType),\n is: () => schemas().core.where,\n },\n { partial: false }\n ),\n v.object(\n {\n type: v.literal(publicType),\n isNot: () => schemas().core.where,\n },\n { partial: false }\n ),\n ];\n });\n return v.union(targetMembers);\n}\n","import type { VariantRelationState } from \"@schema/relation\";\nimport v from \"@validation/primitives/v\";\nimport type { VibSchema } from \"@validation/types\";\nimport type {\n TaggedPredicateInput,\n TaggedPredicateOutput,\n} from \"./tagged-predicate\";\nimport { taggedTargetPredicate } from \"./tagged-predicate\";\nimport type {\n ExactPolymorphicTargetSchemaGetters,\n PolymorphicSchema,\n PolymorphicTargetSchemaGetters,\n} from \"./types\";\n\n/**\n * `_count: { select: { items: true | { where } } }` over a collection.\n *\n * `true` counts every member of every configured variant — the engine sums one\n * correlated count per member table, in declaration order. The filtered form\n * takes the SAME tagged predicate the quantifier filter takes, which is what\n * makes \"count the posts matching P\" and \"some post matches P\" two readings of\n * one grammar rather than two grammars.\n *\n * `true` is accepted rather than required-object for parity with the ordinary\n * `countFilterFactory`; there is no reason for a polymorphic collection to be\n * spelled differently from an ordinary list at this key.\n */\nexport type PolymorphicCollectionCountFilterSchema<Getters> = PolymorphicSchema<\n true | { readonly where?: TaggedPredicateInput<Getters> },\n true | { readonly where?: TaggedPredicateOutput<Getters> }\n>;\n\nexport function polymorphicCollectionCountFilterFactory<\n State extends VariantRelationState,\n Getters extends PolymorphicTargetSchemaGetters<State>,\n>(\n state: State,\n targetSchemas: ExactPolymorphicTargetSchemaGetters<State, Getters>\n): PolymorphicCollectionCountFilterSchema<Getters> {\n const schemaGetters: PolymorphicTargetSchemaGetters<State> = targetSchemas;\n return v.union([\n v.literal(true),\n v.object({\n where: taggedTargetPredicate(state, schemaGetters),\n }),\n ]) as PolymorphicCollectionCountFilterSchema<Getters>;\n}\n\n/**\n * A to-one slot holds at most one membership, and `_count` is defined over\n * LISTS — Prisma's `<Model>CountOutputType` contains only list relations, and\n * the plan keeps that rule. Refused by name rather than omitted so the caller\n * reads the reason instead of \"Unknown key\".\n */\nexport const polymorphicToOneCountFilterRefusal = (): VibSchema<never, never> =>\n v.refused(\"A polymorphic to-one slot has no collection to count.\");\n","import type { VariantRelationState } from \"@schema/relation\";\nimport v from \"@validation/primitives/v\";\nimport type { InferInput, InferOutput, VibSchema } from \"@validation/types\";\nimport {\n type ToOneMutationSchema,\n toOneMutationSchema,\n} from \"../to-one-mutation-schema\";\nimport type {\n CoreInputAt,\n CoreOutputAt,\n ExactPolymorphicTargetSchemaGetters,\n PolymorphicTargetSchemaGetters,\n} from \"./types\";\nimport { polymorphicPublicTypes } from \"./types\";\n\n/**\n * A direct polymorphic payload carries its discriminator INSIDE each verb, so a verb\n * schema is a union over the configured public types and the type-to-selector\n * correlation is a property of that union — not of a projection the enclosing edge\n * applies (that owner, `nested-data-projection`, is for INVERSE edges).\n */\ntype ConnectInput<Getters> = {\n [PublicType in Extract<keyof Getters, string>]: {\n readonly type: PublicType;\n readonly where: CoreInputAt<Getters, PublicType, \"whereUnique\">;\n };\n}[Extract<keyof Getters, string>];\n\ntype ConnectOutput<Getters> = {\n [PublicType in Extract<keyof Getters, string>]: {\n readonly type: PublicType;\n readonly where: CoreOutputAt<Getters, PublicType, \"whereUnique\">;\n };\n}[Extract<keyof Getters, string>];\n\ntype CreateInput<Getters> = {\n [PublicType in Extract<keyof Getters, string>]: {\n readonly type: PublicType;\n readonly data: CoreInputAt<Getters, PublicType, \"create\">;\n };\n}[Extract<keyof Getters, string>];\n\ntype CreateOutput<Getters> = {\n [PublicType in Extract<keyof Getters, string>]: {\n readonly type: PublicType;\n readonly data: CoreOutputAt<Getters, PublicType, \"create\">;\n };\n}[Extract<keyof Getters, string>];\n\ntype ConnectOrCreateInput<Getters> = {\n [PublicType in Extract<keyof Getters, string>]: {\n readonly type: PublicType;\n readonly where: CoreInputAt<Getters, PublicType, \"whereUnique\">;\n readonly create: CoreInputAt<Getters, PublicType, \"create\">;\n };\n}[Extract<keyof Getters, string>];\n\ntype ConnectOrCreateOutput<Getters> = {\n [PublicType in Extract<keyof Getters, string>]: {\n readonly type: PublicType;\n readonly where: CoreOutputAt<Getters, PublicType, \"whereUnique\">;\n readonly create: CoreOutputAt<Getters, PublicType, \"create\">;\n };\n}[Extract<keyof Getters, string>];\n\n/** The supply verbs a fresh parent can name. Declaration order is the message order. */\nexport type PolymorphicCreateEntries<Getters> = {\n connect: VibSchema<ConnectInput<Getters>, ConnectOutput<Getters>>;\n create: VibSchema<CreateInput<Getters>, CreateOutput<Getters>>;\n connectOrCreate: VibSchema<\n ConnectOrCreateInput<Getters>,\n ConnectOrCreateOutput<Getters>\n >;\n};\n\nexport type PolymorphicCreateSchema<Getters> = ToOneMutationSchema<\n PolymorphicCreateEntries<Getters>,\n undefined,\n false,\n \"exactlyOne\"\n>;\n\nexport type PolymorphicCreateInput<Getters> = InferInput<\n PolymorphicCreateSchema<Getters>\n>;\n\nexport type PolymorphicCreateOutput<Getters> = InferOutput<\n PolymorphicCreateSchema<Getters>\n>;\n\nexport function polymorphicCreateFactory<\n State extends VariantRelationState,\n Getters extends PolymorphicTargetSchemaGetters<State>,\n>(\n state: State,\n targetSchemas: ExactPolymorphicTargetSchemaGetters<State, Getters>\n): PolymorphicCreateSchema<Getters> {\n const schemaGetters: PolymorphicTargetSchemaGetters<State> = targetSchemas;\n const publicTypes = polymorphicPublicTypes(state);\n return toOneMutationSchema(\n {\n connect: v.union(\n publicTypes.map((publicType) =>\n v.object(\n {\n type: v.literal(publicType),\n where: () => schemaGetters[publicType]().core.whereUnique,\n },\n { partial: false }\n )\n )\n ),\n create: v.union(\n publicTypes.map((publicType) =>\n v.object(\n {\n type: v.literal(publicType),\n data: () => schemaGetters[publicType]().core.create,\n },\n { partial: false }\n )\n )\n ),\n connectOrCreate: v.union(\n publicTypes.map((publicType) =>\n v.object(\n {\n type: v.literal(publicType),\n where: () => schemaGetters[publicType]().core.whereUnique,\n create: () => schemaGetters[publicType]().core.create,\n },\n { partial: false }\n )\n )\n ),\n },\n undefined,\n false,\n \"exactlyOne\"\n ) as unknown as PolymorphicCreateSchema<Getters>;\n}\n","import type { VariantRelationState } from \"@schema/relation\";\nimport v from \"@validation/primitives/v\";\nimport type {\n CoreInputAt,\n CoreOutputAt,\n ExactPolymorphicTargetSchemaGetters,\n PolymorphicSchema,\n PolymorphicTargetSchemaGetters,\n} from \"./types\";\nimport { polymorphicPublicTypes } from \"./types\";\n\ntype ConnectInput<Getters> = {\n [PublicType in Extract<keyof Getters, string>]: {\n readonly connect: {\n readonly type: PublicType;\n readonly where: CoreInputAt<Getters, PublicType, \"whereUnique\">;\n };\n };\n}[Extract<keyof Getters, string>];\n\ntype ConnectOutput<Getters> = {\n [PublicType in Extract<keyof Getters, string>]: {\n readonly connect: {\n readonly type: PublicType;\n readonly where: CoreOutputAt<Getters, PublicType, \"whereUnique\">;\n };\n };\n}[Extract<keyof Getters, string>];\n\nexport type PolymorphicCreateManySchema<Getters> = PolymorphicSchema<\n ConnectInput<Getters>,\n ConnectOutput<Getters>\n>;\n\nexport function polymorphicCreateManyFactory<\n State extends VariantRelationState,\n Getters extends PolymorphicTargetSchemaGetters<State>,\n>(\n state: State,\n targetSchemas: ExactPolymorphicTargetSchemaGetters<State, Getters>\n): PolymorphicCreateManySchema<Getters> {\n const schemas: PolymorphicTargetSchemaGetters<State> = targetSchemas;\n return v.union(\n polymorphicPublicTypes(state).map((publicType) =>\n v.object(\n {\n connect: v.object(\n {\n type: v.literal(publicType),\n where: () => schemas[publicType]().core.whereUnique,\n },\n { partial: false }\n ),\n },\n { partial: false }\n )\n )\n ) as unknown as PolymorphicCreateManySchema<Getters>;\n}\n","import type { VariantRelationState } from \"@schema/relation\";\nimport v from \"@validation/primitives/v\";\nimport { createSchema, fail, validateSchema } from \"../../primitives/helpers\";\nimport type { VibSchema } from \"../../types\";\nimport { isRecord } from \"../../value-guards\";\nimport type {\n TaggedPredicateInput,\n TaggedPredicateOutput,\n} from \"./tagged-predicate\";\nimport { taggedTargetPredicate } from \"./tagged-predicate\";\nimport type {\n ExactPolymorphicTargetSchemaGetters,\n PolymorphicSchema,\n PolymorphicTargetSchemaGetters,\n} from \"./types\";\n\ntype FilterInput<Getters> = TaggedPredicateInput<Getters>;\n\ntype FilterOutput<Getters> = TaggedPredicateOutput<Getters>;\n\ntype PresenceFilter =\n | { readonly is: null; readonly isNot?: never }\n | { readonly is?: never; readonly isNot: null };\n\nexport type PolymorphicFilterSchema<\n State extends VariantRelationState,\n Getters,\n> = PolymorphicSchema<\n | FilterInput<Getters>\n | (State[\"optional\"] extends true ? PresenceFilter | null : never),\n | FilterOutput<Getters>\n | (State[\"optional\"] extends true ? PresenceFilter : never)\n>;\n\nexport function polymorphicFilterFactory<\n State extends VariantRelationState,\n Getters extends PolymorphicTargetSchemaGetters<State>,\n>(\n state: State,\n targetSchemas: ExactPolymorphicTargetSchemaGetters<State, Getters>\n): PolymorphicFilterSchema<State, Getters> {\n const schemaGetters: PolymorphicTargetSchemaGetters<State> = targetSchemas;\n const targetFilter = taggedTargetPredicate(state, schemaGetters);\n const isNull = v.object({ is: v.literal(null) }, { partial: false });\n const isNotNull = v.object({ isNot: v.literal(null) }, { partial: false });\n const presenceMembers: readonly [typeof isNull, typeof isNotNull] = [\n isNull,\n isNotNull,\n ];\n const presenceFilter = v.union(presenceMembers);\n const nullShorthand = v.literal(null, {\n transform: (): { readonly is: null } => ({ is: null }),\n });\n const optional = state.optional === true;\n const options: readonly VibSchema<unknown, unknown>[] = optional\n ? [nullShorthand, presenceFilter, targetFilter]\n : [targetFilter];\n const schema = createSchema<unknown, unknown>(\"union\", (value) => {\n if (value === null) {\n return optional\n ? validateSchema(nullShorthand, value)\n : fail(\"Expected polymorphic filter with a type\");\n }\n if (!isRecord(value)) return fail(\"Expected object\");\n if (Object.hasOwn(value, \"type\")) {\n return validateSchema(targetFilter, value);\n }\n return optional\n ? validateSchema(presenceFilter, value)\n : fail(\"Expected polymorphic filter with a type\");\n });\n (schema as { options?: unknown }).options = options;\n return schema as PolymorphicFilterSchema<State, Getters>;\n}\n\n// =============================================================================\n// COLLECTION QUANTIFIERS — cardinality `\"many\"`\n// =============================================================================\n\n/**\n * `{ some | every | none }` over the SAME tagged predicate the to-one filter\n * uses, and nothing else.\n *\n * NO null-presence arm. A collection has no null state — an empty collection is\n * the empty array, not `null` — so `is: null` / `isNot: null` would be a second\n * spelling of \"empty\" that disagrees with the result type. Callers asking\n * \"is it empty\" write `none: { type: … }` or a `_count` filter.\n *\n * NO hand-written `Object.hasOwn(value, \"type\")` dispatcher either. That lives\n * in the to-one factory to disambiguate the bare-`null` shorthand from the\n * tagged form; with no shorthand and no presence arm there is nothing to\n * disambiguate, and the strict object's own \"Unknown key\" is already the right\n * message.\n *\n * Every quantifier carries a TYPE. `some: { type: \"post\", is: … }` asks about\n * post members specifically — the plan's §7.3 rule that `every` means \"every\n * member of the named variant satisfies the predicate AND no member of another\n * variant exists\", which the engine lowers as a conjunction rather than trusting\n * a `NOT EXISTS` spelling to mean it.\n */\nexport type PolymorphicCollectionFilterSchema<Getters> = PolymorphicSchema<\n {\n readonly some?: FilterInput<Getters>;\n readonly every?: FilterInput<Getters>;\n readonly none?: FilterInput<Getters>;\n },\n {\n readonly some?: FilterOutput<Getters>;\n readonly every?: FilterOutput<Getters>;\n readonly none?: FilterOutput<Getters>;\n }\n>;\n\nexport function polymorphicCollectionFilterFactory<\n State extends VariantRelationState,\n Getters extends PolymorphicTargetSchemaGetters<State>,\n>(\n slot: string,\n state: State,\n targetSchemas: ExactPolymorphicTargetSchemaGetters<State, Getters>\n): PolymorphicCollectionFilterSchema<Getters> {\n const schemaGetters: PolymorphicTargetSchemaGetters<State> = targetSchemas;\n const predicate = taggedTargetPredicate(state, schemaGetters);\n // A collection filter that names no quantifier is not a filter: the same\n // rule (and the same registered sentence) the to-one and to-many relation\n // filters own, on the third relation surface that spells quantifiers.\n // `where: { items: {} }` read as silence lowers to TRUE, which is how\n // `deleteMany({ where: { items: {} } })` came to delete every row.\n const refusal = `Polymorphic collection filter '${slot}' requires one of: some, every, none.`;\n return v.object(\n {\n some: predicate,\n every: predicate,\n none: predicate,\n },\n {\n refuse: (value) =>\n value.some !== undefined ||\n value.every !== undefined ||\n value.none !== undefined\n ? undefined\n : refusal,\n }\n ) as PolymorphicCollectionFilterSchema<Getters>;\n}\n","import v, { type V } from \"@validation/primitives/v\";\nimport type { VibSchema } from \"@validation/types\";\n\n/**\n * Ordering a parent BY a polymorphic slot.\n *\n * A COLLECTION offers exactly one thing to order by: how many members it has.\n * That is the same offer an ordinary to-many relation makes\n * (`toManyOrderByFactory`), and it is deliberately the same shape — the engine\n * lowers both through one summed-count expression, so a second spelling here\n * would be a second thing to keep in step.\n *\n * Ordering by a member's COLUMN is not offered and cannot be: which table the\n * column lives in is decided per row by the discriminator, so `orderBy:\n * { items: { title: \"asc\" } }` names a column that exists for some members and\n * not others. The plan does not add root ordering through a to-one slot either,\n * for the same reason — hence the named refusal below rather than an omitted\n * key, so the caller reads WHY instead of \"Unknown key\".\n */\nexport type PolymorphicCollectionOrderBySchema = V.Object<{\n _count: V.Enum<[\"asc\", \"desc\"]>;\n}>;\n\nexport const polymorphicCollectionOrderByFactory =\n (): PolymorphicCollectionOrderBySchema =>\n v.object({\n _count: v.enum([\"asc\", \"desc\"]),\n });\n\nexport const polymorphicToOneOrderByRefusal = (): VibSchema<never, never> =>\n v.refused(\n \"A polymorphic to-one slot cannot be ordered on: the target model is chosen per row, so there is no single column to sort by.\"\n );\n","import type { AnyModel } from \"@schema/model\";\nimport type { AnyRelation, VariantRelationState } from \"@schema/relation\";\nimport { withOmitProjection } from \"@validation/model/args/omit\";\nimport { rejectSelectInclude } from \"@validation/model/args/select-include-exclusivity\";\nimport { projectableScalarNames } from \"@validation/model/core/projection\";\nimport {\n createSchema,\n fail,\n ok,\n validateSchema,\n} from \"@validation/primitives/helpers\";\nimport type {\n ObjectOptions,\n ObjectSchema,\n} from \"@validation/primitives/object\";\nimport v from \"@validation/primitives/v\";\nimport type { InferInput, InferOutput, VibSchema } from \"@validation/types\";\nimport { isRecord } from \"@validation/value-guards\";\nimport { buildToManyNestedNode, defaultSelectionNode } from \"../select-include\";\nimport type {\n CoreInputAt,\n CoreOutputAt,\n ExactPolymorphicTargetSchemaGetters,\n PolymorphicSchema,\n PolymorphicTargetSchemaGetters,\n} from \"./types\";\nimport { polymorphicPublicTypes } from \"./types\";\n\ntype ProjectionInput<Schemas> = Schemas extends () => infer TargetSchemas\n ? TargetSchemas extends {\n readonly core: {\n readonly select: infer Select;\n readonly include: infer Include;\n readonly omit: infer Omit;\n };\n }\n ?\n | true\n | {\n readonly select: InferInput<Select>;\n readonly include?: never;\n readonly omit?: InferInput<Omit>;\n }\n | {\n readonly select?: never;\n readonly include?: InferInput<Include>;\n readonly omit?: InferInput<Omit>;\n }\n : never\n : never;\n\ntype ProjectionOutput<Schemas> = Schemas extends () => infer TargetSchemas\n ? TargetSchemas extends {\n readonly core: {\n readonly select: infer Select;\n readonly include: infer Include;\n };\n }\n ?\n | true\n | {\n readonly select?: InferOutput<Select>;\n readonly include?: InferOutput<Include>;\n }\n : never\n : never;\n\nexport type PolymorphicProjectionInput<Getters> = {\n readonly [PublicType in keyof Getters]?: ProjectionInput<Getters[PublicType]>;\n};\n\nexport type PolymorphicProjectionOutput<Getters> = {\n readonly [PublicType in keyof Getters]?: ProjectionOutput<\n Getters[PublicType]\n >;\n};\n\nexport type PolymorphicSelectSchema<Getters> = PolymorphicSchema<\n boolean | PolymorphicProjectionInput<Getters>,\n boolean | PolymorphicProjectionOutput<Getters>\n>;\n\nexport type PolymorphicIncludeSchema<Getters> =\n PolymorphicSelectSchema<Getters>;\n\nexport function polymorphicSelectFactory<\n State extends VariantRelationState,\n Getters extends PolymorphicTargetSchemaGetters<State>,\n>(\n relation: { readonly \"~\": { readonly state: State } } & AnyRelation,\n targetSchemas: ExactPolymorphicTargetSchemaGetters<State, Getters>\n): PolymorphicSelectSchema<Getters>;\nexport function polymorphicSelectFactory(\n relation: AnyRelation,\n targetSchemas: PolymorphicTargetSchemaGetters<VariantRelationState>\n): PolymorphicSelectSchema<\n PolymorphicTargetSchemaGetters<VariantRelationState>\n>;\nexport function polymorphicSelectFactory(\n relation: AnyRelation,\n targetSchemas: PolymorphicTargetSchemaGetters<VariantRelationState>\n): PolymorphicSelectSchema<\n PolymorphicTargetSchemaGetters<VariantRelationState>\n> {\n const state = relation[\"~\"].state as VariantRelationState;\n const schemaGetters = targetSchemas;\n const entries: Record<string, () => ReturnType<typeof v.union>> = {};\n for (const publicType of polymorphicPublicTypes(state)) {\n const schemas = schemaGetters[publicType]!;\n // `settleTarget` is the one sanctioned getter invocation, settled once per\n // declaration and shared by every schema graph that reuses this terminal.\n const target = relation[\"~\"].settleTarget(publicType) as AnyModel;\n entries[publicType] = () =>\n v.union([\n v.literal(true),\n v.lazy(() => {\n const targetSchemasAtParse = schemas();\n const targetModel = target;\n const node = withOmitProjection(\n rejectSelectInclude(\n v.object({\n select: () => targetSchemasAtParse.core.select,\n include: () => targetSchemasAtParse.core.include,\n omit: () => targetSchemasAtParse.core.omit,\n })\n ),\n targetModel,\n `polymorphic.${publicType}`\n );\n return v.coerce(node, (value) => {\n if (value.select !== undefined) return value;\n const select: Record<string, true> = {};\n for (const field of projectableScalarNames(targetModel)) {\n select[field] = true;\n }\n return Object.keys(select).length === 0\n ? value\n : { ...value, select };\n });\n }),\n ]);\n }\n return v.union([v.boolean(), v.object(entries)]) as PolymorphicSelectSchema<\n PolymorphicTargetSchemaGetters<VariantRelationState>\n >;\n}\n\nexport const polymorphicIncludeFactory = polymorphicSelectFactory;\n\n// =============================================================================\n// COLLECTION ENVELOPE — cardinality `\"many\"`\n// =============================================================================\n\n/**\n * THE CROSS-BOUNDARY CONTRACT with the query engine, in one place.\n *\n * A validated collection selection is one of exactly three things:\n *\n * - `true` — every configured variant, each at its default projection;\n * - `false` — no key in the result and no relation SQL at all;\n * - `{ only?, variants? }` — where `only` is a DEDUPED array in DECLARATION\n * order (never the caller's order) and `variants` maps a public\n * discriminator to that arm's to-many node.\n *\n * `true` / `false` are preserved VERBATIM rather than desugared into an\n * all-variants envelope: that keeps parity with the to-one factory and with\n * `booleanToSelect`'s `false` contract, and keeps \"`{ items: false }` emits no\n * key and no relation SQL\" a straight-through fact rather than something the\n * engine has to re-derive from an envelope full of arms.\n *\n * The engine reads `only` and `variants` and NOTHING else. Two keys, both\n * optional, both meaning the same thing when absent as when explicitly\n * `undefined` (the parse boundary's rule).\n */\n\ntype ArmProjectionKeys<Getters, PublicType extends keyof Getters> = {\n readonly where?: CoreInputAt<Getters, PublicType, \"where\">;\n readonly orderBy?:\n | CoreInputAt<Getters, PublicType, \"orderBy\">\n | readonly CoreInputAt<Getters, PublicType, \"orderBy\">[];\n readonly take?: number;\n readonly skip?: number;\n readonly cursor?: CoreInputAt<Getters, PublicType, \"whereUnique\">;\n readonly distinct?: readonly string[];\n readonly omit?: CoreInputAt<Getters, PublicType, \"omit\">;\n};\n\n/**\n * One arm: `true` (that variant at its default projection) or the ordinary\n * to-many node, `select` and `include` mutually exclusive as everywhere else.\n *\n * There is deliberately NO `false` arm. \"Do not read this variant\" already has\n * a spelling — leaving it out of `only` — and a second spelling of one fact is\n * the shape this codebase refuses.\n */\ntype ArmInput<Getters, PublicType extends keyof Getters> =\n | true\n | (ArmProjectionKeys<Getters, PublicType> & {\n readonly select: CoreInputAt<Getters, PublicType, \"select\">;\n readonly include?: never;\n })\n | (ArmProjectionKeys<Getters, PublicType> & {\n readonly select?: never;\n readonly include?: CoreInputAt<Getters, PublicType, \"include\">;\n });\n\ntype ArmOutput<Getters, PublicType extends keyof Getters> = {\n readonly where?: CoreOutputAt<Getters, PublicType, \"where\">;\n readonly orderBy?: unknown;\n readonly take?: number;\n readonly skip?: number;\n readonly cursor?: CoreOutputAt<Getters, PublicType, \"whereUnique\">;\n readonly distinct?: readonly string[];\n readonly select?: CoreOutputAt<Getters, PublicType, \"select\">;\n readonly include?: CoreOutputAt<Getters, PublicType, \"include\">;\n};\n\nexport type PolymorphicCollectionProjectionInput<Getters> = {\n readonly only?: readonly Extract<keyof Getters, string>[];\n readonly variants?: {\n readonly [PublicType in keyof Getters]?: ArmInput<Getters, PublicType>;\n };\n};\n\nexport type PolymorphicCollectionProjectionOutput<Getters> = {\n readonly only?: readonly Extract<keyof Getters, string>[];\n readonly variants?: {\n readonly [PublicType in keyof Getters]?: ArmOutput<Getters, PublicType>;\n };\n};\n\nexport type PolymorphicCollectionSelectSchema<Getters> = PolymorphicSchema<\n boolean | PolymorphicCollectionProjectionInput<Getters>,\n boolean | PolymorphicCollectionProjectionOutput<Getters>\n>;\n\nexport type PolymorphicCollectionIncludeSchema<Getters> =\n PolymorphicCollectionSelectSchema<Getters>;\n\n/**\n * `only` — an exact, DEDUPED, declaration-ordered allow-list.\n *\n * `v.enum(publicTypes, { array: true })` already answers membership and element\n * exactness, and it is the schema whose `values` the JSON-schema converter\n * reads. What it does NOT do is dedupe (it is a `Set.has` membership test), so\n * `[\"post\",\"post\"]` would sail through and then quietly cost an extra arm.\n *\n * CANONICALIZATION is not cosmetic. It makes \"the allow-list's order never\n * changes result order\" structurally true instead of a promise the read builder\n * has to keep, and it collapses `[\"a\",\"b\"]` and `[\"b\",\"a\"]` into ONE cache\n * entry — the cache key preserves array order, so without this the same query\n * spelled two ways compiles and caches twice. Duplicates are refused first, so\n * the canonical form is a pure reorder that loses nothing.\n *\n * `only: []` is accepted: \"no variants\" is a legal, if unusual, request, and it\n * has an exact result type (`readonly never[]`) and an exact runtime answer (a\n * fresh empty array) — while every arm's integrity facts are still computed.\n */\nconst onlyAllowList = (\n publicTypes: string[]\n): VibSchema<readonly string[], string[]> => {\n const membership = v.enum(publicTypes, { array: true });\n // `wrapped` is the membership list the JSON Schema export describes.\n return Object.assign(\n createSchema<readonly string[], string[]>(\"polymorphic_only\", (value) => {\n const result = validateSchema(membership, value);\n if (result.issues) return result;\n const seen = new Set<string>();\n for (const entry of result.value) {\n if (seen.has(entry)) {\n return fail(`Duplicate value in 'only': '${entry}'`);\n }\n seen.add(entry);\n }\n return ok(publicTypes.filter((publicType) => seen.has(publicType)));\n }),\n { wrapped: membership }\n );\n};\n\n/**\n * A CROSS-KEY rule, so it cannot live on either entry: naming a variant under\n * `variants` that `only` excludes is a contradiction, and answering it with the\n * arm's own error (\"Unknown key\") would name the wrong thing.\n *\n * Same shape as `rejectSelectInclude`: re-implement `~standard.validate` over\n * the object schema. It runs AFTER the wrapped schema, so a variant name that is\n * both unknown and outside `only` still gets the accurate \"Unknown key\" rather\n * than this cross-key message.\n *\n * The pair is read off the RAW payload even though the verdict is only issued\n * for a payload that validated. The two are the same fact: `only` is deduped\n * (a duplicate is refused outright) and reordered into declaration order, so\n * canonicalization cannot change which types the allow-list ADMITS. Reading the\n * raw object is what lets both shape checks below be guards over a value the\n * checker can actually narrow — the wrapped schema's output type is opaque\n * `TEntries`, and re-deciding \"is it a record\" on a result that has already\n * validated as an object is a guard with nothing left to catch.\n *\n * Parse-boundary only. There is no type-level mirror: the cost of one more\n * conditional inside an already-distributed mapped type is real, and the payoff\n * is a message TypeScript would phrase worse.\n */\nexport const rejectVariantsOutsideOnly = <\n TEntries,\n TOpts extends ObjectOptions | undefined,\n>(\n schema: ObjectSchema<TEntries, TOpts>\n): ObjectSchema<TEntries, TOpts> => {\n const standard = schema[\"~standard\"];\n const validate: typeof standard.validate = (value) => {\n if (!isRecord(value)) return standard.validate(value);\n const only = value.only;\n const variants = value.variants;\n // An absent `only` leaves `variants` unconstrained, and a malformed pair is\n // the wrapped schema's refusal to phrase, not this rule's.\n if (!(Array.isArray(only) && isRecord(variants))) {\n return standard.validate(value);\n }\n const result = standard.validate(value);\n if (result.issues) return result;\n const allowed = new Set<unknown>(only);\n const stray = Object.keys(variants).find(\n (publicType) => !allowed.has(publicType)\n );\n if (stray === undefined) return result;\n return {\n issues: [\n {\n message: `Variant '${stray}' is not in 'only'`,\n path: [\"variants\", stray],\n },\n ],\n };\n };\n\n return {\n ...schema,\n parse: validate,\n \"~standard\": {\n version: standard.version,\n vendor: standard.vendor,\n validate,\n get types() {\n return standard.types;\n },\n get jsonSchema() {\n return standard.jsonSchema;\n },\n },\n };\n};\n\nexport function polymorphicCollectionSelectFactory<\n State extends VariantRelationState,\n Getters extends PolymorphicTargetSchemaGetters<State>,\n>(\n relation: { readonly \"~\": { readonly state: State } } & AnyRelation,\n targetSchemas: ExactPolymorphicTargetSchemaGetters<State, Getters>\n): PolymorphicCollectionSelectSchema<Getters>;\nexport function polymorphicCollectionSelectFactory(\n relation: AnyRelation,\n targetSchemas: PolymorphicTargetSchemaGetters<VariantRelationState>\n): PolymorphicCollectionSelectSchema<\n PolymorphicTargetSchemaGetters<VariantRelationState>\n>;\nexport function polymorphicCollectionSelectFactory(\n relation: AnyRelation,\n targetSchemas: PolymorphicTargetSchemaGetters<VariantRelationState>\n): PolymorphicCollectionSelectSchema<\n PolymorphicTargetSchemaGetters<VariantRelationState>\n> {\n const state = relation[\"~\"].state as VariantRelationState;\n const publicTypes = polymorphicPublicTypes(state);\n\n const armEntries: Record<string, () => VibSchema<unknown, unknown>> = {};\n for (const publicType of publicTypes) {\n const schemas = targetSchemas[publicType]!;\n const target = relation[\"~\"].settleTarget(publicType) as AnyModel;\n armEntries[publicType] = () =>\n v.union([\n // A bare `true` desugars to the SAME shape a spelled-out arm parses to,\n // so the engine sees one arm shape rather than two.\n v.coerce(v.literal(true), () => defaultSelectionNode(target)),\n v.lazy(() =>\n buildToManyNestedNode({\n targetModel: target,\n label: `polymorphic.${publicType}`,\n core: () => schemas().core,\n scalarNames: Object.keys(target[\"~\"].state.scalars),\n })\n ),\n ]);\n }\n\n const envelope = rejectVariantsOutsideOnly(\n v.object({\n only: onlyAllowList(publicTypes),\n variants: v.object(armEntries),\n })\n );\n\n return v.union([v.boolean(), envelope]) as PolymorphicCollectionSelectSchema<\n PolymorphicTargetSchemaGetters<VariantRelationState>\n >;\n}\n\nexport const polymorphicCollectionIncludeFactory =\n polymorphicCollectionSelectFactory;\n","import type { VariantRelationState } from \"@schema/relation\";\nimport v, { type V } from \"@validation/primitives/v\";\nimport type { VibSchema } from \"@validation/types\";\nimport {\n type ToOneMutationSchema,\n toOneMutationSchema,\n} from \"../to-one-mutation-schema\";\nimport type {\n CoreInputAt,\n CoreOutputAt,\n ExactPolymorphicTargetSchemaGetters,\n PolymorphicTargetSchemaGetters,\n} from \"./types\";\nimport { polymorphicPublicTypes } from \"./types\";\n\ntype ConnectInput<Getters> = {\n [PublicType in Extract<keyof Getters, string>]: {\n readonly type: PublicType;\n readonly where: CoreInputAt<Getters, PublicType, \"whereUnique\">;\n };\n}[Extract<keyof Getters, string>];\n\ntype ConnectOutput<Getters> = {\n [PublicType in Extract<keyof Getters, string>]: {\n readonly type: PublicType;\n readonly where: CoreOutputAt<Getters, PublicType, \"whereUnique\">;\n };\n}[Extract<keyof Getters, string>];\n\ntype CreateInput<Getters> = {\n [PublicType in Extract<keyof Getters, string>]: {\n readonly type: PublicType;\n readonly data: CoreInputAt<Getters, PublicType, \"create\">;\n };\n}[Extract<keyof Getters, string>];\n\ntype CreateOutput<Getters> = {\n [PublicType in Extract<keyof Getters, string>]: {\n readonly type: PublicType;\n readonly data: CoreOutputAt<Getters, PublicType, \"create\">;\n };\n}[Extract<keyof Getters, string>];\n\ntype ConnectOrCreateInput<Getters> = {\n [PublicType in Extract<keyof Getters, string>]: {\n readonly type: PublicType;\n readonly where: CoreInputAt<Getters, PublicType, \"whereUnique\">;\n readonly create: CoreInputAt<Getters, PublicType, \"create\">;\n };\n}[Extract<keyof Getters, string>];\n\ntype ConnectOrCreateOutput<Getters> = {\n [PublicType in Extract<keyof Getters, string>]: {\n readonly type: PublicType;\n readonly where: CoreOutputAt<Getters, PublicType, \"whereUnique\">;\n readonly create: CoreOutputAt<Getters, PublicType, \"create\">;\n };\n}[Extract<keyof Getters, string>];\n\ntype UpdateInput<Getters> = {\n [PublicType in Extract<keyof Getters, string>]: {\n readonly type: PublicType;\n readonly where?: CoreInputAt<Getters, PublicType, \"where\">;\n readonly data: CoreInputAt<Getters, PublicType, \"update\">;\n };\n}[Extract<keyof Getters, string>];\n\ntype UpdateOutput<Getters> = {\n [PublicType in Extract<keyof Getters, string>]: {\n readonly type: PublicType;\n readonly where?: CoreOutputAt<Getters, PublicType, \"where\">;\n readonly data: CoreOutputAt<Getters, PublicType, \"update\">;\n };\n}[Extract<keyof Getters, string>];\n\ntype UpsertInput<Getters> = {\n [PublicType in Extract<keyof Getters, string>]: {\n readonly type: PublicType;\n readonly create: CoreInputAt<Getters, PublicType, \"create\">;\n readonly update: CoreInputAt<Getters, PublicType, \"update\">;\n };\n}[Extract<keyof Getters, string>];\n\ntype UpsertOutput<Getters> = {\n [PublicType in Extract<keyof Getters, string>]: {\n readonly type: PublicType;\n readonly create: CoreOutputAt<Getters, PublicType, \"create\">;\n readonly update: CoreOutputAt<Getters, PublicType, \"update\">;\n };\n}[Extract<keyof Getters, string>];\n\ntype DeleteTarget<Getters> = {\n [PublicType in Extract<keyof Getters, string>]: {\n readonly type: PublicType;\n };\n}[Extract<keyof Getters, string>];\n\ntype PolymorphicTargetedEntries<Getters> = {\n connect: VibSchema<ConnectInput<Getters>, ConnectOutput<Getters>>;\n create: VibSchema<CreateInput<Getters>, CreateOutput<Getters>>;\n connectOrCreate: VibSchema<\n ConnectOrCreateInput<Getters>,\n ConnectOrCreateOutput<Getters>\n >;\n update: VibSchema<UpdateInput<Getters>, UpdateOutput<Getters>>;\n upsert: VibSchema<UpsertInput<Getters>, UpsertOutput<Getters>>;\n};\n\n/**\n * Removal is a SLOT fact: only an optional membership may be emptied, so only there\n * do `delete` and `disconnect` exist as keys at all. `disconnect` stays a `true`\n * literal rather than a boolean — `false` is not an inactive spelling of a payload\n * that must carry exactly one intent, it is a value this verb never had.\n */\ntype PolymorphicRemovalEntries<Getters> = {\n delete: VibSchema<DeleteTarget<Getters>, DeleteTarget<Getters>>;\n disconnect: V.Literal<true>;\n};\n\nexport type PolymorphicUpdateEntries<\n State extends VariantRelationState,\n Getters,\n> = PolymorphicTargetedEntries<Getters> &\n (State[\"optional\"] extends true\n ? PolymorphicRemovalEntries<Getters>\n : Record<never, never>);\n\nexport type PolymorphicUpdateSchema<\n State extends VariantRelationState,\n Getters,\n> = ToOneMutationSchema<\n PolymorphicUpdateEntries<State, Getters>,\n undefined,\n false,\n \"exactlyOne\"\n>;\n\nexport function polymorphicUpdateFactory<\n State extends VariantRelationState,\n Getters extends PolymorphicTargetSchemaGetters<State>,\n>(\n state: State,\n targetSchemas: ExactPolymorphicTargetSchemaGetters<State, Getters>\n): PolymorphicUpdateSchema<State, Getters> {\n const schemaGetters: PolymorphicTargetSchemaGetters<State> = targetSchemas;\n const publicTypes = polymorphicPublicTypes(state);\n const typed = (publicType: (typeof publicTypes)[number]) => ({\n type: v.literal(publicType),\n });\n const targetedEntries = {\n connect: v.union(\n publicTypes.map((publicType) =>\n v.object(\n {\n ...typed(publicType),\n where: () => schemaGetters[publicType]().core.whereUnique,\n },\n { partial: false }\n )\n )\n ),\n create: v.union(\n publicTypes.map((publicType) =>\n v.object(\n {\n ...typed(publicType),\n data: () => schemaGetters[publicType]().core.create,\n },\n { partial: false }\n )\n )\n ),\n connectOrCreate: v.union(\n publicTypes.map((publicType) =>\n v.object(\n {\n ...typed(publicType),\n where: () => schemaGetters[publicType]().core.whereUnique,\n create: () => schemaGetters[publicType]().core.create,\n },\n { partial: false }\n )\n )\n ),\n update: v.union(\n publicTypes.map((publicType) =>\n v.object(\n {\n ...typed(publicType),\n where: () => schemaGetters[publicType]().core.where,\n data: () => schemaGetters[publicType]().core.update,\n },\n // `where` FILTERS the one connected record; the discriminator and the data\n // are what the engine needs to address it at all.\n { atLeast: [\"type\", \"data\"] }\n )\n )\n ),\n upsert: v.union(\n publicTypes.map((publicType) =>\n v.object(\n {\n ...typed(publicType),\n create: () => schemaGetters[publicType]().core.create,\n update: () => schemaGetters[publicType]().core.update,\n },\n { partial: false }\n )\n )\n ),\n };\n if (state.optional !== true) {\n return toOneMutationSchema(\n targetedEntries,\n undefined,\n false,\n \"exactlyOne\"\n ) as unknown as PolymorphicUpdateSchema<State, Getters>;\n }\n return toOneMutationSchema(\n {\n ...targetedEntries,\n delete: v.union(\n publicTypes.map((publicType) =>\n v.object(typed(publicType), { partial: false })\n )\n ),\n disconnect: v.literal(true),\n },\n undefined,\n false,\n \"exactlyOne\"\n ) as unknown as PolymorphicUpdateSchema<State, Getters>;\n}\n","import type { AnyModel } from \"@schema/model\";\nimport {\n type AnyRelation,\n isVariantRelationState,\n type VariantRelationState,\n} from \"@schema/relation\";\nimport type { VariantEntries } from \"@schema/relation/static-membership\";\nimport { lazyRecord } from \"@validation/lazy\";\nimport type { ModelSchemas } from \"@validation/model\";\nimport type { VibSchema } from \"@validation/types\";\n\nexport {\n type PolymorphicCollectionCreateInput,\n type PolymorphicCollectionCreateOutput,\n type PolymorphicCollectionCreateSchema,\n type PolymorphicCollectionUpdateInput,\n type PolymorphicCollectionUpdateOutput,\n type PolymorphicCollectionUpdateSchema,\n polymorphicCollectionCreateFactory,\n polymorphicCollectionUpdateFactory,\n} from \"./collection-mutation\";\nexport {\n type PolymorphicCollectionCountFilterSchema,\n polymorphicCollectionCountFilterFactory,\n} from \"./count-filter\";\nexport {\n type PolymorphicCreateInput,\n type PolymorphicCreateOutput,\n type PolymorphicCreateSchema,\n polymorphicCreateFactory,\n} from \"./create\";\nexport {\n type PolymorphicCreateManySchema,\n polymorphicCreateManyFactory,\n} from \"./create-many\";\nexport {\n type PolymorphicCollectionFilterSchema,\n type PolymorphicFilterSchema,\n polymorphicCollectionFilterFactory,\n polymorphicFilterFactory,\n} from \"./filter\";\nexport {\n type PolymorphicCollectionOrderBySchema,\n polymorphicCollectionOrderByFactory,\n} from \"./order-by\";\nexport {\n type PolymorphicCollectionIncludeSchema,\n type PolymorphicCollectionProjectionInput,\n type PolymorphicCollectionProjectionOutput,\n type PolymorphicCollectionSelectSchema,\n type PolymorphicIncludeSchema,\n type PolymorphicProjectionInput,\n type PolymorphicProjectionOutput,\n type PolymorphicSelectSchema,\n polymorphicCollectionIncludeFactory,\n polymorphicCollectionSelectFactory,\n polymorphicIncludeFactory,\n polymorphicSelectFactory,\n} from \"./select-include\";\nexport {\n type TaggedPredicateInput,\n type TaggedPredicateOutput,\n taggedTargetPredicate,\n} from \"./tagged-predicate\";\nexport type {\n ExactPolymorphicTargetSchemaGetters,\n PolymorphicTargetSchemaGetters,\n} from \"./types\";\nexport {\n type PolymorphicUpdateSchema,\n polymorphicUpdateFactory,\n} from \"./update\";\n\nimport {\n type PolymorphicCollectionCreateSchema,\n type PolymorphicCollectionUpdateSchema,\n polymorphicCollectionCreateFactory,\n polymorphicCollectionUpdateFactory,\n} from \"./collection-mutation\";\nimport {\n type PolymorphicCollectionCountFilterSchema,\n polymorphicCollectionCountFilterFactory,\n polymorphicToOneCountFilterRefusal,\n} from \"./count-filter\";\nimport {\n type PolymorphicCreateSchema,\n polymorphicCreateFactory,\n} from \"./create\";\nimport {\n type PolymorphicCreateManySchema,\n polymorphicCreateManyFactory,\n} from \"./create-many\";\nimport {\n type PolymorphicCollectionFilterSchema,\n type PolymorphicFilterSchema,\n polymorphicCollectionFilterFactory,\n polymorphicFilterFactory,\n} from \"./filter\";\nimport {\n type PolymorphicCollectionOrderBySchema,\n polymorphicCollectionOrderByFactory,\n polymorphicToOneOrderByRefusal,\n} from \"./order-by\";\nimport {\n type PolymorphicCollectionSelectSchema,\n type PolymorphicIncludeSchema,\n type PolymorphicSelectSchema,\n polymorphicCollectionIncludeFactory,\n polymorphicCollectionSelectFactory,\n polymorphicIncludeFactory,\n polymorphicSelectFactory,\n} from \"./select-include\";\nimport type { PolymorphicTargetSchemaGetters } from \"./types\";\nimport {\n type PolymorphicUpdateSchema,\n polymorphicUpdateFactory,\n} from \"./update\";\n\ntype TargetModel<\n State extends VariantRelationState,\n PublicType extends keyof VariantEntries<State>,\n> = VariantEntries<State>[PublicType] extends {\n readonly getter: () => infer Target;\n}\n ? Target extends AnyModel\n ? Target\n : never\n : never;\n\nexport type RegisteredPolymorphicTargetSchemas<\n State extends VariantRelationState,\n> = {\n readonly [PublicType in keyof VariantEntries<State>]: () => ModelSchemas<\n TargetModel<State, PublicType>\n >;\n};\n\n/** A family that exists so it can EXPLAIN itself, and accepts nothing. */\ntype RefusedFamily = VibSchema<never, never>;\n\n/** The eight families a polymorphic TO-ONE slot offers. */\nexport interface PolymorphicToOneRelationSchemas<\n State extends VariantRelationState,\n Getters extends PolymorphicTargetSchemaGetters<State>,\n> {\n readonly filter: PolymorphicFilterSchema<State, Getters>;\n readonly create: PolymorphicCreateSchema<Getters>;\n readonly createMany: PolymorphicCreateManySchema<Getters>;\n readonly update: PolymorphicUpdateSchema<State, Getters>;\n readonly select: PolymorphicSelectSchema<Getters>;\n readonly include: PolymorphicIncludeSchema<Getters>;\n readonly orderBy: RefusedFamily;\n readonly countFilter: RefusedFamily;\n}\n\n/** The eight families a polymorphic COLLECTION offers. */\nexport interface PolymorphicCollectionRelationSchemas<\n State extends VariantRelationState,\n Getters extends PolymorphicTargetSchemaGetters<State>,\n> {\n readonly filter: PolymorphicCollectionFilterSchema<Getters>;\n readonly create: PolymorphicCollectionCreateSchema<Getters>;\n /**\n * The ROOT-`createMany` ROW context. It is not the `createMany` VERB — that\n * lives inside the two bags above — it is the shape a bulk ROW may spell for\n * this key, and it is the SAME family `create` offers.\n *\n * A collection row is relation-BEARING (plan §9.6): `routing.ts`'s\n * `relationBearingRow` now answers true for a polymorphic collection key\n * through `isVariantCollectionRelation`, so the whole call routes to the\n * relation-bearing record series and the member junction inserts follow the\n * owner root. The direct polymorphic TO-ONE row keeps its narrower\n * connect-only union and its grouped INSERT.\n */\n readonly createMany: PolymorphicCollectionCreateSchema<Getters>;\n readonly update: PolymorphicCollectionUpdateSchema<Getters>;\n readonly select: PolymorphicCollectionSelectSchema<Getters>;\n readonly include: PolymorphicCollectionSelectSchema<Getters>;\n readonly orderBy: PolymorphicCollectionOrderBySchema;\n readonly countFilter: PolymorphicCollectionCountFilterSchema<Getters>;\n}\n\n/**\n * ONE dispatch, both levels: the declaration states its own slot cardinality\n * and both halves read that one fact.\n */\nexport type PolymorphicRelationSchemas<\n State extends VariantRelationState,\n Getters extends PolymorphicTargetSchemaGetters<State>,\n> = State[\"cardinality\"] extends \"many\"\n ? PolymorphicCollectionRelationSchemas<State, Getters>\n : PolymorphicToOneRelationSchemas<State, Getters>;\n\n/**\n * The variant-target half of one model's ONE relation map.\n *\n * The map holds both target domains (§5.2); this projection is the TARGET-KIND\n * step of the operation-schema dispatch (§8.2), and it is where a variant\n * slot's eight-family bundle parts company with a model slot's seven. Selecting\n * the keys is not a second topology view: `target.kind` is a declared fact, and\n * the two bundles genuinely differ in which families they own.\n */\nexport type GetPolymorphicRelationsSchemas<Source extends AnyModel> = {\n readonly [RelationKey in VariantRelationKeys<\n Source[\"~\"][\"state\"][\"relations\"]\n >]: Source[\"~\"][\"state\"][\"relations\"][RelationKey][\"~\"][\"state\"] extends infer State extends\n VariantRelationState\n ? PolymorphicRelationSchemas<\n State,\n RegisteredPolymorphicTargetSchemas<State>\n >\n : never;\n};\n\n/** The keys of a relation map whose target domain is a variant map. */\nexport type VariantRelationKeys<Relations> = {\n [Key in keyof Relations]: Relations[Key] extends {\n readonly \"~\": {\n readonly state: { readonly target: { readonly kind: \"variants\" } };\n };\n }\n ? Key\n : never;\n}[keyof Relations];\n\nfunction getTargetSchemas<State extends VariantRelationState>(\n relation: AnyRelation,\n state: VariantRelationState,\n resolve: (model: AnyModel) => ModelSchemas<AnyModel>\n): RegisteredPolymorphicTargetSchemas<State> {\n const getters: Record<string, () => ModelSchemas<AnyModel>> = {};\n for (const publicType of Object.keys(state.target.entries)) {\n // `settleTarget` is the ONE sanctioned getter invocation: it settles each\n // target once per declaration and hands every consumer — this schema\n // registry, another schema graph reusing the same terminal — the same\n // return or the same normalized Error.\n getters[publicType] = () =>\n resolve(relation[\"~\"].settleTarget(publicType) as AnyModel);\n }\n return getters as unknown as RegisteredPolymorphicTargetSchemas<State>;\n}\n\n/**\n * THE GRAMMAR OWNER of what a polymorphic slot offers, per cardinality.\n *\n * B3 built NO families at all for a collection group: `v.object` is strict, so\n * one omission turned every collection key into an unknown-key refusal on all\n * six surfaces at once. That was the right lock while no storage backed the\n * key. Package C changes the boundary, not the discipline:\n *\n * READS LAND. `where` takes `{ some | every | none }` over the tagged target\n * predicate; `select` / `include` take the collection envelope\n * (`{ only, variants }`); `orderBy` takes `{ _count }`; `_count` takes the\n * filtered count. All four are backed by the per-variant member junction\n * tables B2/B3 resolved at definition validation.\n *\n * PACKAGE D LANDS THE NESTED WRITES. `create` and `update` are now the real\n * tagged verb bags (`collection-mutation.ts`), so the relation-mutation parser\n * DOES see a collection payload — the fourth `ParsedRelationMutation` arm — and\n * the direct collection coordinator lowers it. `upsert` works transitively\n * through both halves.\n *\n * PACKAGE E LANDS THE ROOT-`createMany` ROW. The bulk row now mounts the SAME\n * `create` family, because `routing.ts`'s `relationBearingRow` answers true for\n * a collection key (through `isVariantCollectionRelation`) and sends the\n * whole call to the relation-bearing record series, where the member junction\n * inserts follow the owner root. The silent-drop hazard the old refusal closed\n * is now closed by the ROUTE; `bulk-polymorphic-connect.ts`'s narrowing throw\n * stays as the engine-side closer for a scope built directly.\n *\n * WHY THE FAMILY KEY SET STAYS AT EIGHT (D1), even though nothing here is\n * refused any more. The key set must be IDENTICAL across cardinalities:\n * `v.fromObject` throws at schema-build time when a non-empty source record\n * matches no entries, so a model whose only polymorphic relation is a collection\n * would break `create` / `createMany` / `update` the instant those paths ran\n * `fromObject` over a record that had a `select` family but no `create` one —\n * and symmetrically for `orderBy` / `countFilter` on an all-to-one model. Eight\n * families, always present, keeps `fromObject` total with no primitive changes.\n * The two remaining `v.refused` entries (to-one `orderBy` / `countFilter`) hold\n * that line for the other cardinality.\n *\n * ONE GUARD: the engine's own union-narrowing throws stay, but they own a\n * DIFFERENT invariant (\"no unvalidated storage enters SQL compilation\") and are\n * reachable only through a directly-built scope. Nothing downstream re-checks\n * cardinality on this axis.\n *\n * The TYPE half dispatches on the same declared slot cardinality, so the\n * type-advertises / runtime-refuses skew is closed: both halves say collection\n * reads AND collection writes work.\n */\n\nexport function getPolymorphicRelationsSchemas<Source extends AnyModel>(\n source: Source,\n resolve: (model: AnyModel) => ModelSchemas<AnyModel>\n): GetPolymorphicRelationsSchemas<Source> {\n const builders: Record<string, () => unknown> = {};\n const relations: Record<string, AnyRelation> = source[\"~\"].state.relations;\n for (const relationKey of Object.keys(relations)) {\n const relation = relations[relationKey]!;\n const state = relation[\"~\"].state;\n if (!isVariantRelationState(state)) continue;\n builders[relationKey] = () => {\n const targets = getTargetSchemas<typeof state>(relation, state, resolve);\n if (state.cardinality === \"many\") {\n return lazyRecord({\n filter: () =>\n polymorphicCollectionFilterFactory(relationKey, state, targets),\n create: () => polymorphicCollectionCreateFactory(state, targets),\n createMany: () => polymorphicCollectionCreateFactory(state, targets),\n update: () => polymorphicCollectionUpdateFactory(state, targets),\n select: () => polymorphicCollectionSelectFactory(relation, targets),\n include: () => polymorphicCollectionIncludeFactory(relation, targets),\n orderBy: () => polymorphicCollectionOrderByFactory(),\n countFilter: () =>\n polymorphicCollectionCountFilterFactory(state, targets),\n });\n }\n return lazyRecord({\n filter: () => polymorphicFilterFactory(state, targets),\n create: () => polymorphicCreateFactory(state, targets),\n createMany: () => polymorphicCreateManyFactory(state, targets),\n update: () => polymorphicUpdateFactory(state, targets),\n select: () => polymorphicSelectFactory(relation, targets),\n include: () => polymorphicIncludeFactory(relation, targets),\n orderBy: () => polymorphicToOneOrderByRefusal(),\n countFilter: () => polymorphicToOneCountFilterRefusal(),\n });\n };\n }\n return lazyRecord(builders) as GetPolymorphicRelationsSchemas<Source>;\n}\n","import type { ScalarState } from \"@schema/scalars/common\";\nimport type { IdDomain } from \"../primitives/id-codec\";\n\n/**\n * Interning for scalar filter/update schemas.\n *\n * A scalar's filter/update validation schema is a pure function of its base\n * schema, which — when the user has NOT attached a custom standard schema —\n * is fully determined by a handful of flags (nullable, array, withTimezone).\n * Two `s.string()` fields on different models therefore build structurally\n * identical filter trees; interning shares one instance across all of them.\n *\n * Shared instances are safe: filter schemas are immutable after construction,\n * contain no field/model identity (error paths are attached by the parent\n * object validator), and their only lazy mutations (object resolve() flag,\n * jsonSchema getter swap) are idempotent set-once operations.\n *\n * Fields with a custom standard schema (`state.schema !== undefined`) return\n * a null key and always build fresh — unknown validators are never interned.\n *\n * An IDENTIFIER DOMAIN is part of the key rather than a reason not to intern.\n * A domain field's filter tree embeds an operand that ADMITS and NORMALIZES —\n * `usr-` prefixed uuids and nothing else — so two fields may share one tree\n * exactly when they share one domain, and a `.uuid()` field must never be\n * handed a `.ulid()` field's validator. Excluding domain fields from interning\n * would be correct too, and larger: every uuid primary key in a schema builds\n * structurally identical filters.\n */\nexport const scalarInternKey = (\n state: ScalarState,\n idDomain?: IdDomain | undefined\n): string | null => {\n if (state.schema !== undefined) {\n return null;\n }\n const domain =\n idDomain === undefined\n ? \"\"\n : `:${idDomain.format}:${idDomain.prefix ?? \"\"}:${idDomain.length ?? \"\"}`;\n return `${state.nullable ? 1 : 0}${state.array ? 1 : 0}${\n state.withTimezone ? 1 : 0\n }${domain}`;\n};\n\n/**\n * Create a per-kind intern cache. Each scalar module owns its own instances\n * (one for filter, one for update), so the key space is just the flag bits.\n */\nexport const createScalarInterner = <T>(): ((\n key: string | null,\n build: () => T\n) => T) => {\n const cache = new Map<string, T>();\n return (key, build) => {\n if (key === null) {\n return build();\n }\n let value = cache.get(key);\n if (value === undefined) {\n value = build();\n cache.set(key, value);\n }\n return value;\n };\n};\n","import { limitFilterDepth } from \"../primitives/filter-depth\";\nimport type { ObjectEntries, ObjectSchema } from \"../primitives/object\";\nimport v, { type V } from \"../primitives/v\";\n\n/**\n * Shared shape for every scalar filter that supports `not`.\n *\n * `not` is LAZILY SELF-REFERENTIAL: its object arm is the very same filter\n * object, so `not: { not: { not: … } }` follows the same vocabulary at every\n * level. The shared filter-depth boundary bounds admission before recursion\n * can exhaust the process or produce an unbounded provider query plan.\n *\n * The cycle is tied with {@link v.lazyRef} rather than a direct reference so\n * the union can name the object that is still being constructed. `lazyRef`\n * only resolves when its validator is CALLED, and it sits inside a union (not\n * as a bare object entry), so the object validator never duck-types metadata\n * off it.\n */\n/**\n * `path` and `mode` SCOPE a filter; they do not state one. A JSON filter that\n * carries only a path asks nothing about the document, and a `mode` beside no\n * text operator folds nothing — which is why \"at least one key\" is not the\n * rule and \"at least one OPERATION\" is.\n */\nconst FILTER_MODIFIER_KEYS: ReadonlySet<string> = new Set([\"path\", \"mode\"]);\n\n/**\n * The sentence an empty filter object answers.\n *\n * The lowerer spelled the field (`Filter for field 'name' must contain at\n * least one operation.`) because it held the field name. This owner is the\n * per-scalar filter object, INTERNED per scalar type, so it validates every\n * `string` field of every model from one instance and cannot name one. The\n * field is not lost: the refusal is a {@link ValidationError} issue whose\n * `path` is `where.name`, which is where an admission refusal names its\n * subject.\n */\nexport const FILTER_WITHOUT_OPERATION =\n \"Filter must contain at least one operation.\";\n\n/**\n * The whole-object refusal every scalar filter object carries: `{}`,\n * `{ equals: undefined }` and `{ path: [...] }` state no operation and must\n * not lower to TRUE — `updateMany({ where: { name: {} } })` would touch every\n * row. `where: {}` (no field at all) still matches everything; this is a rule\n * about a FILTER, not about a `where`.\n *\n * The operator vocabulary is not restated here: the object is STRICT, so every\n * key it admits is one of its own, and the rule is \"a key that is not a\n * modifier, with a value\". That is what keeps the rule true for the objects\n * that are EXTENDED later — a list filter extended with `_count`/`_avg` for\n * `having` (`model/args/aggregate.ts`) states an operation through the\n * extension, and an operator list captured at build time would refuse it.\n */\nexport const requireFilterOperation = (\n value: Record<string, unknown>\n): string | undefined =>\n Object.entries(value).some(\n ([key, member]) => !FILTER_MODIFIER_KEYS.has(key) && member !== undefined\n )\n ? undefined\n : FILTER_WITHOUT_OPERATION;\n\nexport interface NegatableFilter<\n S extends V.Schema,\n TBase extends ObjectEntries,\n> extends V.Object<TBase & { not: NegatableFilterSchema<S, TBase> }> {}\n\n/**\n * The scalar filter surface: the shorthand value (`\"foo\"` → `{ equals: \"foo\" }`)\n * or the filter object. Also the type of `not` itself — negating a filter\n * accepts exactly what filtering accepts, which is what makes it recursive.\n */\nexport type NegatableFilterSchema<\n S extends V.Schema,\n TBase extends ObjectEntries,\n> = V.Union<readonly [V.ShorthandFilter<S>, NegatableFilter<S, TBase>]>;\n\n/**\n * Builds the union above from a filter-object schema that does NOT yet carry\n * `not`; the returned schema carries it at every depth.\n *\n * @param base - the operator object for this scalar (`equals`/`in`/`lt`/…)\n * @param schema - the scalar's base schema, used for the shorthand arm\n */\nexport const buildNegatableFilterSchema = <\n S extends V.Schema,\n TBase extends ObjectEntries,\n>(\n base: ObjectSchema<TBase>,\n schema: S\n): NegatableFilterSchema<S, TBase> => {\n const negatable: NegatableFilter<S, TBase> = v.object(\n {\n ...base.entries,\n not: v.union([v.shorthandFilter(schema), v.lazyRef(() => negatable)]),\n },\n { refuse: requireFilterOperation }\n ) as unknown as NegatableFilter<S, TBase>;\n return v.union([v.shorthandFilter(schema), limitFilterDepth(negatable)]);\n};\n","import type { ScalarState, ScalarType } from \"@schema/scalars/common\";\nimport { lazyScalarSchemas, type ScalarVariantSchemas } from \"../lazy\";\nimport { createSchema, fail, ok, validateSchema } from \"../primitives/helpers\";\nimport type { UnionSchema } from \"../primitives/union\";\nimport v, { type V } from \"../primitives/v\";\nimport { createScalarInterner, scalarInternKey } from \"./intern\";\nimport {\n buildNegatableFilterSchema,\n type NegatableFilterSchema,\n} from \"./negatable-filter\";\n\n/**\n * The shapes every scalar kind shares, spelled ONCE.\n *\n * Eight of the fourteen scalar modules used to carry their own copy of the same\n * four families — the ordered comparison filter, the list filter, one of the\n * two update bags, and the interned builder tail — differing only in the kind\n * name and the two primitive schemas that kind is made of. This module is the\n * single owner of those four shapes; a kind module names its primitives and\n * calls the family, and keeps its own code only where its language really\n * differs: boolean has no ordering, blob, vector and point have no list arm,\n * enum refuses ordering, decimal and json speak their own, and string's ordered\n * comparisons take the FIELD schema rather than the member schema while its\n * entry order appends `equals` after the text predicates — the\n * compact-identifier narrowing is a third, further difference.\n *\n * ENTRY ORDER IS PART OF THE CONTRACT. The object validator iterates entries in\n * insertion order and returns the FIRST issue, and `toJsonSchema` emits\n * `properties` in that order, so a payload with two invalid operators reports a\n * different key if the order moves. The families therefore keep the\n * `base.extend({ equals })` sequencing that produced today's order rather than\n * spelling one canonical literal: the module-level operator bag first, the\n * field-dependent `equals` appended after it, `not` appended last by\n * {@link buildNegatableFilterSchema}. `tests/unit/scalars/_scalar-shape-census.ts`\n * records the resulting order for all twenty-four cases.\n *\n * A kind's MEMBER and LIST schemas — `v.integer()` and\n * `v.integer({ array: true })`, and so on — carry no nullability and no arity\n * of their own. The FIELD's schema is what `equals`, `set` and the shorthand\n * take, so only those arms accept a `null`; `in`, the ordered comparisons and\n * the list operators compare against a plain value.\n *\n * Each family is a FACTORY that closes over its kind's primitives and returns\n * the per-field builder. That keeps the module-level bag built exactly once per\n * kind, as it was when each module declared its own, and it keeps every\n * validator built inside the factory that hands it to a `v.union` — the\n * capture rule of validation AGENTS Rule 4.\n */\n\n// =============================================================================\n// FILTER SHAPES\n// =============================================================================\n\n/**\n * `equals` over the FIELD schema, `in`/`notIn` over the kind's list, and the\n * four ordered comparisons over the kind's member schema.\n */\nexport type ComparisonFilterBase<\n K extends ScalarType,\n S extends V.Schema,\n M extends V.Schema,\n L extends V.Schema,\n C extends V.Operand<any>,\n> = {\n equals: V.ComparisonOperand<K, S, C>;\n in: L;\n notIn: L;\n lt: V.ComparisonOperand<K, M, C>;\n lte: V.ComparisonOperand<K, M, C>;\n gt: V.ComparisonOperand<K, M, C>;\n gte: V.ComparisonOperand<K, M, C>;\n};\n\nexport type ComparisonFilterSchema<\n K extends ScalarType,\n S extends V.Schema,\n M extends V.Schema,\n L extends V.Schema,\n C extends V.Operand<any>,\n> = NegatableFilterSchema<\n V.ComparisonOperand<K, S, C>,\n ComparisonFilterBase<K, S, M, L, C>\n>;\n\n/** `has`/`hasEvery`/`hasSome`/`isEmpty`, then `equals` over the field schema. */\nexport type ListFilterBase<\n S extends V.Schema,\n M extends V.Schema,\n L extends V.Schema,\n> = {\n equals: S;\n has: M;\n hasEvery: L;\n hasSome: L;\n isEmpty: V.Boolean;\n};\n\nexport type ListFilterSchema<\n S extends V.Schema,\n M extends V.Schema,\n L extends V.Schema,\n> = NegatableFilterSchema<S, ListFilterBase<S, M, L>>;\n\n/**\n * The ordered comparison filter of one kind.\n *\n * `in`/`notIn` take the kind's LIST schema and the four comparisons its MEMBER\n * schema, because neither reads the field's own nullability or arity: only the\n * whole-value arms (`equals`, and the shorthand) take `null`.\n */\nexport const comparisonFilterFamily = <\n K extends ScalarType,\n M extends V.Schema,\n L extends V.Schema,\n>(\n kind: K,\n member: () => M,\n list: () => L\n) => {\n // Built on the kind's first filter, not at import: a schema that never\n // filters this kind never constructs it.\n const createBase = () =>\n v.object({\n in: list(),\n notIn: list(),\n lt: v.comparisonOperand(kind, member()),\n lte: v.comparisonOperand(kind, member()),\n gt: v.comparisonOperand(kind, member()),\n gte: v.comparisonOperand(kind, member()),\n });\n let base: ReturnType<typeof createBase> | undefined;\n return <S extends V.Schema, C extends V.Operand<any> = V.Operand<any>>(\n schema: S\n ): ComparisonFilterSchema<K, S, M, L, C> => {\n base ??= createBase();\n const operand = v.comparisonOperand<K, S, C>(kind, schema);\n return buildNegatableFilterSchema<\n V.ComparisonOperand<K, S, C>,\n ComparisonFilterBase<K, S, M, L, C>\n >(base.extend({ equals: operand }), operand);\n };\n};\n\n/**\n * The list filter of one kind.\n *\n * `equals` compares the WHOLE list and therefore takes the field schema; the\n * membership operators take the kind's member and list schemas.\n */\nexport const listFilterFamily = <M extends V.Schema, L extends V.Schema>(\n member: () => M,\n list: () => L\n) => {\n const createBase = () =>\n v.object({\n has: member(),\n hasEvery: list(),\n hasSome: list(),\n isEmpty: v.boolean(),\n });\n let base: ReturnType<typeof createBase> | undefined;\n return <S extends V.Schema>(schema: S): ListFilterSchema<S, M, L> => {\n base ??= createBase();\n return buildNegatableFilterSchema<S, ListFilterBase<S, M, L>>(\n base.extend({ equals: schema }),\n schema\n );\n };\n};\n\n// =============================================================================\n// UPDATE SHAPES\n// =============================================================================\n\nexport type ArithmeticOperand<\n F extends ScalarState,\n M extends V.Schema,\n> = F[\"schema\"] extends undefined ? M : ReturnType<typeof v.refused>;\n\n/** `set` plus the four arithmetic operations, for the numeric kinds. */\nexport type ArithmeticUpdateSchema<\n S extends V.Schema,\n M extends V.Schema,\n> = V.Union<\n readonly [\n V.ShorthandUpdate<S>,\n V.Object<{\n set: S;\n increment: M;\n decrement: M;\n multiply: M;\n divide: M;\n }>,\n ]\n>;\n\n/** `set` and nothing else, for every kind with no arithmetic. */\nexport type SetUpdateSchema<S extends V.Schema> = V.Union<\n readonly [V.ShorthandUpdate<S>, V.Object<{ set: S }, { partial: false }>]\n>;\n\n/**\n * One value or a whole list, the operand of `push` and `unshift`.\n *\n * Spelled with its input and output written out rather than left to\n * `V.Union`'s defaults: those defaults are an indexed access over the union of\n * the arms, and TypeScript compares a DEFERRED indexed access in target\n * position by intersection, so the family's own construction would not be\n * assignable to it while `M` and `L` are still type parameters. At a concrete\n * kind the two spellings are the same type in both directions.\n */\nexport type PushSchema<M extends V.Schema, L extends V.Schema> = UnionSchema<\n readonly [V.ShorthandArray<M>, L],\n L[\" vibInferred\"][\"0\"] | M[\" vibInferred\"][\"0\"],\n [M[\" vibInferred\"][\"1\"]] | L[\" vibInferred\"][\"1\"]\n>;\n\n/**\n * `set`, `push` and `unshift`, each taking one value or a whole list.\n *\n * The arm tuple is `readonly`, which is what `v.union`'s `const` type parameter\n * infers and what every kind but one already spelled for itself. String's\n * private `StringListUpdateSchema` wrote the tuple mutable, so a string LIST\n * field's `update` is the one type this consolidation respelled — an internal\n * one: `StringSchemas` is reachable from no package entry, and the inferred\n * input and output are identical either way, pinned by\n * `tests/types/scalars/scalar-family-spellings.core.types.ts`.\n */\nexport type ListUpdateSchema<\n S extends V.Schema,\n M extends V.Schema,\n L extends V.Schema,\n> = V.Union<\n readonly [\n V.ShorthandUpdate<S>,\n V.Object<{\n set: S;\n push: PushSchema<M, L>;\n unshift: PushSchema<M, L>;\n }>,\n ]\n>;\n\n/** The arithmetic update bag of one kind, held to that kind's member schema. */\nconst nonzeroDivisor = createSchema<unknown, unknown>(\n \"nonzero_divisor\",\n (value) =>\n value === 0 || value === 0n\n ? fail(\"Division by zero is not allowed\")\n : ok(value)\n);\n\nexport const arithmeticUpdateFamily =\n <M extends V.Schema>(member: () => M) =>\n <S extends V.Schema>(\n schema: S,\n refined = false\n ): ArithmeticUpdateSchema<S, M> =>\n v.union([\n v.shorthandUpdate(schema),\n v.object({\n set: schema,\n increment: refined ? v.refused(REFINED_ARITHMETIC_REFUSAL) : member(),\n decrement: refined ? v.refused(REFINED_ARITHMETIC_REFUSAL) : member(),\n multiply: refined ? v.refused(REFINED_ARITHMETIC_REFUSAL) : member(),\n divide: refined\n ? v.refused(REFINED_ARITHMETIC_REFUSAL)\n : withScalarOutputDomain(member(), nonzeroDivisor),\n }),\n ]) as never;\n\nexport const REFINED_ARITHMETIC_REFUSAL =\n \"Arithmetic on a field with .schema() cannot validate the resulting stored value; use set with a validated value.\";\n\n/** ORM write output must remain in the stored domain; primitive v.* transforms stay open. */\nexport function withScalarOutputDomain<S extends V.Schema>(\n schema: S,\n domain: V.Schema\n): S {\n const validate = schema[\"~standard\"].validate;\n const result = { ...schema };\n Object.defineProperties(result, Object.getOwnPropertyDescriptors(schema));\n const descriptors = Object.getOwnPropertyDescriptors(schema[\"~standard\"]);\n Reflect.deleteProperty(descriptors, \"validate\");\n const standard = Object.defineProperties({}, descriptors);\n Object.defineProperty(standard, \"validate\", {\n value: (value: unknown) => {\n const admitted = validate(value);\n if (admitted.issues) return admitted;\n const physical = validateSchema(domain, admitted.value);\n return physical;\n },\n });\n Object.defineProperty(result, \"~standard\", { value: standard });\n return result;\n}\n\n/**\n * The set-only update.\n *\n * `{ partial: false }` is what makes the bare `{}` a refusal rather than a\n * no-op: with exactly one entry, partial would admit an update that names no\n * value at all.\n */\nexport const buildSetUpdate = <S extends V.Schema>(\n schema: S\n): SetUpdateSchema<S> =>\n v.union([\n v.shorthandUpdate(schema),\n v.object({ set: schema }, { partial: false }),\n ]);\n\n/** The list update bag of one kind, held to that kind's member and list. */\nexport const listUpdateFamily =\n <M extends V.Schema, L extends V.Schema>(member: () => M, list: () => L) =>\n <S extends V.Schema>(schema: S): ListUpdateSchema<S, M, L> =>\n v.union([\n v.shorthandUpdate(schema),\n v.object({\n set: schema,\n push: v.union([v.shorthandArray(member()), list()]),\n unshift: v.union([v.shorthandArray(member()), list()]),\n }),\n ]);\n\n/**\n * One value built on first use and kept. A kind's member and list schemas are\n * built this way so that importing the validation layer constructs nothing\n * for a kind no schema uses.\n */\nexport const once = <T>(build: () => T): (() => T) => {\n let value: T | undefined;\n return () => {\n value ??= build();\n return value;\n };\n};\n\n// =============================================================================\n// THE INTERNED BUILDER TAIL\n// =============================================================================\n\n/** One filter cache and one update cache, private to one scalar kind. */\nexport interface ScalarInterners {\n readonly update: (key: string | null, build: () => unknown) => unknown;\n readonly filter: (key: string | null, build: () => unknown) => unknown;\n}\n\n/**\n * The intern caches of ONE kind.\n *\n * Per kind, never shared: {@link scalarInternKey} spells only the flag bits, so\n * an `s.int()` and an `s.number()` with the same flags produce the same key and\n * would otherwise collide on one cache.\n */\nexport const createScalarInterners = (): ScalarInterners => ({\n update: createScalarInterner<unknown>(),\n filter: createScalarInterner<unknown>(),\n});\n\n/**\n * One variant's interned thunk, built in a scope of its OWN.\n *\n * Each call captures one cache, one key and one factory and nothing else. A\n * thunk written inline beside its siblings would instead capture the whole\n * builder record, and an unresolved variant would keep its resolved siblings'\n * factories reachable — the release half of the invariant `lazy.ts` states.\n *\n * The `as never` is the one place the interner's `unknown` value meets a kind's\n * CONDITIONAL variant type (`F[\"array\"] extends true ? … : …`), which no\n * ternary can be proved to inhabit. That seam already existed; it was spelled\n * twice per kind, sixteen times over, and is spelled once here.\n */\nconst internedVariant =\n (\n intern: (key: string | null, build: () => unknown) => unknown,\n key: string | null,\n build: () => unknown\n ): (() => never) =>\n () =>\n intern(key, build) as never;\n\n/**\n * The tail every interned kind shares: pay-per-use materialization of the three\n * variants, with `update` and `filter` interned under the field's key.\n *\n * `create` is NOT interned — it carries the field's own default, nullability\n * and arity, so two fields share nothing there, and it keeps its exact type.\n */\nexport const internedScalarSchemas = <T extends ScalarVariantSchemas>(\n interners: ScalarInterners,\n key: string | null,\n builders: {\n base: T[\"base\"];\n create: () => T[\"create\"];\n update: () => unknown;\n filter: () => unknown;\n }\n) =>\n lazyScalarSchemas<T>({\n base: builders.base,\n create: builders.create,\n update: internedVariant(interners.update, key, builders.update),\n filter: internedVariant(interners.filter, key, builders.filter),\n });\n\n// =============================================================================\n// THE COMPARABLE KINDS\n// =============================================================================\n\n/**\n * One ordered kind, whole: int, number and bigint with arithmetic, date, time\n * and datetime with `set` alone.\n *\n * The six kinds differed only in their name, their primitive and that one\n * update choice, so each module is a row naming them. Every call builds its\n * own member and list schemas and its own interners: the intern key spells\n * only flag bits, so a kind that shared another's cache would be handed the\n * other's validators.\n *\n * The returned builder is typed `never` because no ternary over `state.array`\n * can be proved to inhabit a kind's CONDITIONAL variant types; each row\n * declares its kind's exact `XSchemas` signature, which `never` satisfies. It\n * is the seam {@link internedVariant} already names, spelled once more here\n * instead of once per kind.\n */\nexport const comparableScalar = <K extends ScalarType>(\n kind: K,\n primitive: (\n options?:\n | ScalarState<K>\n | { nullable?: boolean; array: boolean; disallowZero?: boolean }\n ) => V.Schema,\n arithmetic: boolean\n) => {\n const member = once(() => primitive());\n const list = once(() => primitive({ array: true }));\n const filter = comparisonFilterFamily(kind, member, list);\n const listFilter = listFilterFamily(member, list);\n const update: (schema: V.Schema, refined?: boolean) => unknown = arithmetic\n ? arithmeticUpdateFamily(member)\n : buildSetUpdate;\n const listUpdate = listUpdateFamily(member, list);\n const interners = createScalarInterners();\n return (state: ScalarState<K>): never => {\n // The stored domain, from the intern key's flags alone. Only create adds an\n // increment's refused zero, on the value a `.schema()` hands it to write.\n const storedDomain = (disallowZero = false) =>\n primitive({ nullable: state.nullable, array: state.array, disallowZero });\n const base =\n state.schema === undefined\n ? state.base\n : withScalarOutputDomain(state.base, storedDomain());\n const refinedListUpdate = () =>\n listUpdateFamily(\n () =>\n withScalarOutputDomain(\n primitive({\n ...state,\n array: false,\n nullable: false,\n optional: false,\n default: undefined,\n }),\n member()\n ),\n () =>\n withScalarOutputDomain(\n primitive({\n ...state,\n array: true,\n nullable: false,\n optional: false,\n default: undefined,\n }),\n list()\n )\n )(base);\n return internedScalarSchemas(interners, scalarInternKey(state), {\n base,\n create: () =>\n state.schema === undefined\n ? primitive(state)\n : withScalarOutputDomain(\n primitive(state),\n storedDomain(state.disallowZero)\n ),\n update: () =>\n state.array\n ? state.schema === undefined\n ? listUpdate(state.base)\n : refinedListUpdate()\n : update(base, state.schema !== undefined),\n filter: () =>\n state.array ? listFilter(storedDomain()) : filter(storedDomain()),\n }) as never;\n };\n};\n","import type { ScalarState } from \"@schema/scalars/common\";\nimport v, { type V } from \"../primitives/v\";\nimport {\n type ArithmeticUpdateSchema,\n type ComparisonFilterSchema,\n comparableScalar,\n type ListFilterSchema,\n type ListUpdateSchema,\n type SetUpdateSchema,\n} from \"./family\";\n\ntype BigIntList = V.BigInt<{ array: true }>;\n\nexport interface BigIntSchemas<\n F extends ScalarState<\"bigint\">,\n C extends V.Operand<any> = V.Operand<any>,\n> {\n base: F[\"base\"];\n create: V.BigInt<F>;\n update: F[\"array\"] extends true\n ? ListUpdateSchema<F[\"base\"], V.BigInt, BigIntList>\n : F[\"schema\"] extends undefined\n ? ArithmeticUpdateSchema<F[\"base\"], V.BigInt>\n : SetUpdateSchema<F[\"base\"]>;\n filter: F[\"array\"] extends true\n ? ListFilterSchema<F[\"base\"], V.BigInt, BigIntList>\n : ComparisonFilterSchema<\"bigint\", F[\"base\"], V.BigInt, BigIntList, C>;\n}\n\nexport const buildBigIntSchema: <\n F extends ScalarState<\"bigint\">,\n C extends V.Operand<any> = V.Operand<any>,\n>(\n state: F\n) => BigIntSchemas<F, C> = comparableScalar(\"bigint\", v.bigint, true);\n","import type { ScalarState } from \"@schema/scalars/common\";\nimport { lazyScalarSchemas } from \"../lazy\";\nimport v, { type V } from \"../primitives/v\";\nimport { buildSetUpdate, type SetUpdateSchema } from \"./family\";\nimport {\n buildNegatableFilterSchema,\n type NegatableFilterSchema,\n} from \"./negatable-filter\";\n\n// =============================================================================\n// FILTER TYPES\n// =============================================================================\n\n// `in`/`notIn` elements are plain (non-nullable) blobs even when the field\n// itself is nullable — a null can never be a member of a set under SQL's\n// three-valued logic, which is also how Prisma types `BytesNullableFilter`.\nconst blobList = v.blob({ array: true });\n\ntype BlobFilterBase<S extends V.Schema> = {\n equals: S;\n in: V.Blob<{ array: true }>;\n notIn: V.Blob<{ array: true }>;\n};\n\ntype BlobFilterSchema<S extends V.Schema> = NegatableFilterSchema<\n S,\n BlobFilterBase<S>\n>;\n\n// =============================================================================\n// SCHEMA BUILDERS\n// =============================================================================\n\nconst buildBlobFilterSchema = <S extends V.Schema>(\n schema: S\n): BlobFilterSchema<S> => {\n const filter = v.object({\n equals: schema,\n in: blobList,\n notIn: blobList,\n });\n return buildNegatableFilterSchema<S, BlobFilterBase<S>>(filter, schema);\n};\n\n// =============================================================================\n// BLOB SCHEMA BUILDER\n// =============================================================================\n\nexport interface BlobSchemas<F extends ScalarState<\"blob\">> {\n base: F[\"base\"];\n create: V.Blob<F>;\n update: SetUpdateSchema<F[\"base\"]>;\n filter: BlobFilterSchema<F[\"base\"]>;\n}\n\nexport const buildBlobSchema = <F extends ScalarState<\"blob\">>(\n state: F\n): BlobSchemas<F> => {\n return lazyScalarSchemas<BlobSchemas<F>>({\n base: state.base,\n create: () => v.blob(state),\n update: () => buildSetUpdate<F[\"base\"]>(state.base),\n filter: () => buildBlobFilterSchema<F[\"base\"]>(state.base),\n });\n};\n","import type { ScalarState } from \"@schema/scalars/common\";\nimport v, { type V } from \"../primitives/v\";\nimport {\n buildSetUpdate,\n createScalarInterners,\n internedScalarSchemas,\n type ListFilterSchema,\n type ListUpdateSchema,\n listFilterFamily,\n listUpdateFamily,\n once,\n type SetUpdateSchema,\n} from \"./family\";\nimport { scalarInternKey } from \"./intern\";\nimport {\n buildNegatableFilterSchema,\n type NegatableFilterSchema,\n} from \"./negatable-filter\";\n\nconst booleanBase = once(() => v.boolean());\nconst booleanList = once(() => v.boolean({ array: true }));\n\n/**\n * Equality operand: a literal, a field reference to another boolean column, an\n * SQL fragment, or a callback returning one of the latter two.\n */\ntype BooleanOperand<\n S extends V.Schema,\n C extends V.Operand<any>,\n> = V.ComparisonOperand<\"boolean\", S, C>;\n\n/**\n * `equals` and nothing else.\n *\n * A boolean has no ORDER, so `lt`/`lte`/`gt`/`gte` have no meaning, and over\n * two values set membership says nothing equality does not: `in: [true, false]`\n * is every row and `in: [true]` is `equals: true`. That is the whole reason\n * this filter is spelled here rather than built by the comparison family — the\n * LIST arm below is the family's, unchanged.\n */\ntype BooleanFilterBase<S extends V.Schema, C extends V.Operand<any>> = {\n equals: BooleanOperand<S, C>;\n};\n\ntype BooleanFilterSchema<\n S extends V.Schema,\n C extends V.Operand<any>,\n> = NegatableFilterSchema<BooleanOperand<S, C>, BooleanFilterBase<S, C>>;\n\nconst buildBooleanFilterSchema = <S extends V.Schema, C extends V.Operand<any>>(\n schema: S\n): BooleanFilterSchema<S, C> => {\n const operand = v.comparisonOperand(\"boolean\", schema);\n const filter = v.object({\n equals: operand,\n });\n return buildNegatableFilterSchema<\n BooleanOperand<S, C>,\n BooleanFilterBase<S, C>\n >(filter, operand);\n};\n\nconst buildBooleanListFilterSchema = listFilterFamily(booleanBase, booleanList);\nconst buildBooleanListUpdateSchema = listUpdateFamily(booleanBase, booleanList);\n\nexport interface BooleanSchemas<\n F extends ScalarState<\"boolean\">,\n C extends V.Operand<any> = V.Operand<any>,\n> {\n base: F[\"base\"];\n create: V.Boolean<F>;\n update: F[\"array\"] extends true\n ? ListUpdateSchema<F[\"base\"], V.Boolean, V.Boolean<{ array: true }>>\n : SetUpdateSchema<F[\"base\"]>;\n filter: F[\"array\"] extends true\n ? ListFilterSchema<F[\"base\"], V.Boolean, V.Boolean<{ array: true }>>\n : BooleanFilterSchema<F[\"base\"], C>;\n}\n\nconst interners = createScalarInterners();\n\nexport const buildBooleanSchema = <\n F extends ScalarState<\"boolean\">,\n C extends V.Operand<any> = V.Operand<any>,\n>(\n state: F\n): BooleanSchemas<F, C> =>\n internedScalarSchemas<BooleanSchemas<F, C>>(\n interners,\n scalarInternKey(state),\n {\n base: state.base,\n create: () => v.boolean(state),\n update: () =>\n state.array\n ? buildBooleanListUpdateSchema(state.base)\n : buildSetUpdate(state.base),\n filter: () =>\n state.array\n ? buildBooleanListFilterSchema(state.base)\n : buildBooleanFilterSchema(state.base),\n }\n );\n","import type { ScalarState } from \"@schema/scalars/common\";\nimport v, { type V } from \"../primitives/v\";\nimport {\n type ComparisonFilterSchema,\n comparableScalar,\n type ListFilterSchema,\n type ListUpdateSchema,\n type SetUpdateSchema,\n} from \"./family\";\n\ntype IsoDateList = V.IsoDate<{ array: true }>;\n\nexport interface DateSchemas<\n F extends ScalarState<\"date\">,\n C extends V.Operand<any> = V.Operand<any>,\n> {\n base: F[\"base\"];\n create: V.IsoDate<F>;\n update: F[\"array\"] extends true\n ? ListUpdateSchema<F[\"base\"], V.IsoDate, IsoDateList>\n : SetUpdateSchema<F[\"base\"]>;\n filter: F[\"array\"] extends true\n ? ListFilterSchema<F[\"base\"], V.IsoDate, IsoDateList>\n : ComparisonFilterSchema<\"date\", F[\"base\"], V.IsoDate, IsoDateList, C>;\n}\n\nexport const buildDateSchema: <\n F extends ScalarState<\"date\">,\n C extends V.Operand<any> = V.Operand<any>,\n>(\n state: F\n) => DateSchemas<F, C> = comparableScalar(\"date\", v.isoDate, false);\n","import type { ScalarState } from \"@schema/scalars/common\";\nimport v, { type V } from \"../primitives/v\";\nimport {\n type ComparisonFilterSchema,\n comparableScalar,\n type ListFilterSchema,\n type ListUpdateSchema,\n type SetUpdateSchema,\n} from \"./family\";\n\ntype IsoTimestampList = V.IsoTimestamp<{ array: true }>;\n\nexport interface DateTimeSchemas<\n F extends ScalarState<\"datetime\">,\n C extends V.Operand<any> = V.Operand<any>,\n> {\n base: F[\"base\"];\n create: V.IsoTimestamp<F>;\n update: F[\"array\"] extends true\n ? ListUpdateSchema<F[\"base\"], V.IsoTimestamp, IsoTimestampList>\n : SetUpdateSchema<F[\"base\"]>;\n filter: F[\"array\"] extends true\n ? ListFilterSchema<F[\"base\"], V.IsoTimestamp, IsoTimestampList>\n : ComparisonFilterSchema<\n \"datetime\",\n F[\"base\"],\n V.IsoTimestamp,\n IsoTimestampList,\n C\n >;\n}\n\nexport const buildDateTimeSchema: <\n F extends ScalarState<\"datetime\">,\n C extends V.Operand<any> = V.Operand<any>,\n>(\n state: F\n) => DateTimeSchemas<F, C> = comparableScalar(\n \"datetime\",\n v.isoTimestamp,\n false\n);\n","import type { FieldRef } from \"@schema/field-ref\";\nimport type { ScalarState } from \"@schema/scalars/common\";\nimport { isSql } from \"@sql\";\nimport { lazyScalarSchemas } from \"../lazy\";\nimport type { DecimalDescriptor } from \"../primitives/decimal-codec\";\nimport {\n createSchema,\n fail,\n ok,\n standardSchemaFailure,\n validateSchema,\n} from \"../primitives/helpers\";\nimport type { ObjectEntries, ObjectSchema } from \"../primitives/object\";\nimport v, { type V } from \"../primitives/v\";\nimport type { InferInput, InferOutput, VibSchema } from \"../types\";\nimport { isRecord } from \"../value-guards\";\nimport { type ArithmeticOperand, REFINED_ARITHMETIC_REFUSAL } from \"./family\";\nimport {\n buildNegatableFilterSchema,\n type NegatableFilterSchema,\n} from \"./negatable-filter\";\n\n// =============================================================================\n// PER-FIELD OPERAND SCHEMAS\n// =============================================================================\n//\n// Every decimal schema on this page is built from the FIELD's declared domain.\n// There are no module-level shared bases: an operand that does not know the\n// precision and scale it is being compared or added to cannot refuse a value\n// outside them, and a filter that silently accepts `1.005` against a scale-2\n// column is a query whose answer no provider agrees on.\n\n/** The domain, in the shape `v.decimal` reads it. */\ntype DomainOptions = { decimal: DecimalDescriptor | undefined };\n\nconst domainOf = (state: ScalarState<\"decimal\">): DomainOptions => ({\n decimal: state.decimal,\n});\n\n// =============================================================================\n// FILTER TYPES\n// =============================================================================\n\n/**\n * A decimal comparison operand: a literal, a field reference to another decimal\n * column, or a callback returning one — but NEVER a generic typed `Sql`\n * fragment.\n *\n * A fragment carries no trusted precision or scale, so on SQLite, where the\n * column holds an unscaled integer coefficient, `gt: sql\\`100\\`` would compare a\n * coefficient against a logical number and quietly answer a different question\n * per provider. Raw SQL remains the escape; every other scalar keeps fragments.\n */\ninterface DecimalComparisonOperandSchema<\n TSchema extends V.Schema,\n C extends V.Operand<any> = V.Operand<any>,\n> extends VibSchema<\n | InferInput<TSchema>\n | FieldRef<string, \"decimal\">\n | ((ctx: C) => FieldRef<string, \"decimal\">),\n InferOutput<TSchema> | FieldRef<string, \"decimal\">\n > {\n readonly type: \"comparison_operand\";\n readonly fieldType: \"decimal\";\n readonly wrapped: TSchema;\n readonly acceptsUndefined: boolean;\n}\n\ntype DecimalFilterBase<\n S extends V.Schema,\n O extends V.Schema,\n L extends V.Schema,\n C extends V.Operand<any>,\n> = {\n equals: DecimalComparisonOperandSchema<S, C>;\n in: L;\n notIn: L;\n lt: DecimalComparisonOperandSchema<O, C>;\n lte: DecimalComparisonOperandSchema<O, C>;\n gt: DecimalComparisonOperandSchema<O, C>;\n gte: DecimalComparisonOperandSchema<O, C>;\n};\n\ntype DecimalFilterSchema<\n S extends V.Schema,\n O extends V.Schema,\n L extends V.Schema,\n C extends V.Operand<any>,\n> = NegatableFilterSchema<\n DecimalComparisonOperandSchema<S, C>,\n DecimalFilterBase<S, O, L, C>\n>;\n\ntype DecimalListFilterBase<\n S extends V.Schema,\n O extends V.Schema,\n L extends V.Schema,\n> = {\n equals: S;\n has: O;\n hasEvery: L;\n hasSome: L;\n isEmpty: V.Boolean;\n in: DecimalListRefusalSchema;\n notIn: DecimalListRefusalSchema;\n lt: DecimalListRefusalSchema;\n lte: DecimalListRefusalSchema;\n gt: DecimalListRefusalSchema;\n gte: DecimalListRefusalSchema;\n};\n\ntype DecimalListRefusalSchema = VibSchema<never, never>;\n\ntype DecimalListFilterSchema<\n S extends V.Schema,\n O extends V.Schema,\n L extends V.Schema,\n> = NegatableFilterSchema<S, DecimalListFilterBase<S, O, L>>;\n\n// =============================================================================\n// UPDATE TYPES\n// =============================================================================\n\n/**\n * EXACTLY one operation.\n *\n * `?: never` on the keys an arm does not carry is what makes a second DECLARED\n * key unrepresentable even when the payload is held in a variable —\n * excess-property checking only fires on a fresh object literal — and building\n * the union out of the arms rather than a partial bag is what makes `{}`\n * unrepresentable at all. The query engine therefore has no precedence to\n * arbitrate for decimals; the ladder in `set-builder.ts` still serves int,\n * number and bigint, whose bags this rule deliberately does not touch.\n */\ntype ExactlyOne<Allowed> = {\n [K in keyof Allowed]: { [P in K]-?: Allowed[P] } & {\n [P in Exclude<keyof Allowed, K>]?: never;\n };\n}[keyof Allowed];\n\n/** An object schema that admits exactly one of its entries. */\nexport interface ExactlyOneSchema<TEntries extends ObjectEntries>\n extends VibSchema<\n ExactlyOne<InferInput<ObjectSchema<TEntries>>>,\n ExactlyOne<InferOutput<ObjectSchema<TEntries>>>\n > {\n readonly type: \"exact_one\";\n readonly entries: TEntries;\n}\n\n/** The operations a decimal SCALAR update declares, named once. */\ntype DecimalOperations<S extends V.Schema, O extends V.Schema> = {\n set: S;\n increment: O;\n decrement: O;\n multiply: O;\n divide: O;\n};\n\ntype DecimalUpdateSchema<S extends V.Schema, O extends V.Schema> = V.Union<\n readonly [V.ShorthandUpdate<S>, ExactlyOneSchema<DecimalOperations<S, O>>]\n> extends infer Schema extends VibSchema\n ? VibSchema<\n InferInput<Schema>,\n ExactlyOne<{\n set: InferOutput<S>;\n increment: InferOutput<O>;\n decrement: InferOutput<O>;\n multiply: InferOutput<O>;\n divide: InferOutput<O>;\n }>\n > & {\n readonly type: \"union\";\n readonly options: readonly [\n V.ShorthandUpdate<S>,\n ExactlyOneSchema<DecimalOperations<S, O>>,\n ];\n }\n : never;\n\ntype DecimalPushSchema<O extends V.Schema, L extends V.Schema> = V.Union<\n readonly [V.ShorthandArray<O>, L]\n>;\n\ntype DecimalListUpdateSchema<\n S extends V.Schema,\n O extends V.Schema,\n L extends V.Schema,\n> = V.Union<\n readonly [\n V.ShorthandUpdate<S>,\n ExactlyOneSchema<DecimalListOperations<S, O, L>>,\n ]\n> extends infer Schema extends VibSchema\n ? VibSchema<\n InferInput<Schema>,\n ExactlyOne<{\n set: InferOutput<S>;\n push: InferOutput<DecimalPushSchema<O, L>>;\n unshift: InferOutput<DecimalPushSchema<O, L>>;\n increment: never;\n decrement: never;\n multiply: never;\n divide: never;\n }>\n > & {\n readonly type: \"union\";\n readonly options: readonly [\n V.ShorthandUpdate<S>,\n ExactlyOneSchema<DecimalListOperations<S, O, L>>,\n ];\n }\n : never;\n\n// =============================================================================\n// SCHEMA BUILDERS\n// =============================================================================\n\n/**\n * `comparisonOperand`, closed to fragments.\n *\n * Wrapping is what keeps the accepted spellings — a value, a reference, a\n * callback returning one — and their exact messages, while refusing the one\n * kind the descriptor cannot vouch for. The validator is built inside this\n * factory, before the schema object exists, because every filter that holds it\n * is a union and a union captures each member's validate at construction.\n */\nconst decimalComparisonOperand = <\n TSchema extends V.Schema,\n C extends V.Operand<any> = V.Operand<any>,\n>(\n wrapped: TSchema\n): DecimalComparisonOperandSchema<TSchema, C> => {\n const operand = v.comparisonOperand(\"decimal\", wrapped);\n const validateOperand = operand[\"~standard\"].validate;\n const schema = createSchema<\n InferInput<DecimalComparisonOperandSchema<TSchema, C>>,\n InferOutput<DecimalComparisonOperandSchema<TSchema, C>>\n >(\"comparison_operand\", (value) => {\n const result = validateOperand(value);\n if (result.issues) return standardSchemaFailure(result.issues);\n return isSql(result.value)\n ? fail(\n \"An SQL fragment is not a decimal operand: it carries no precision or scale, so the comparison would mean something different on each provider. Use a field reference or raw SQL.\"\n )\n : ok(result.value);\n });\n const metadata: Pick<\n DecimalComparisonOperandSchema<TSchema, C>,\n \"type\" | \"fieldType\" | \"wrapped\" | \"acceptsUndefined\"\n > = {\n type: \"comparison_operand\",\n fieldType: \"decimal\",\n wrapped,\n acceptsUndefined: operand.acceptsUndefined,\n };\n\n // `createSchema` owns the Standard Schema carrier. The metadata is the\n // comparison-operand surface its JSON converter reads lazily.\n return Object.assign(schema, metadata);\n};\n\nconst OPERATION_REFUSAL = (keys: readonly string[]) =>\n `A decimal update takes exactly one operation: ${keys.join(\", \")}`;\n\nconst OBJECT_PROTOTYPE_KEYS: ReadonlySet<string> = new Set([\n \"__defineGetter__\",\n \"__defineSetter__\",\n \"__lookupGetter__\",\n \"__lookupSetter__\",\n \"__proto__\",\n \"constructor\",\n \"hasOwnProperty\",\n \"isPrototypeOf\",\n \"propertyIsEnumerable\",\n \"toLocaleString\",\n \"toString\",\n \"valueOf\",\n]);\n\ntype OperationName<TEntries extends ObjectEntries> = Extract<\n keyof TEntries,\n string\n>;\n\n/**\n * Exactly one operation, owned by one hostile-object preflight.\n *\n * `Reflect.ownKeys` sees symbols and non-enumerable declarations that an object\n * schema's string enumeration cannot. The prototype walk rejects every key on\n * a caller-supplied prototype. `Object.prototype` itself is the language\n * intrinsic, so only its fixed built-in surface is ignored. Only then is the\n * selected operand read once, by its own entry. An operand's issue is rooted\n * at its operation; a refused operation's reason stands alone, since it names\n * the operation itself. The output's null prototype prevents prototype\n * pollution from adding an operation downstream.\n */\nconst exactlyOneOperation = <TEntries extends Record<string, VibSchema>>(\n entries: TEntries\n): ExactlyOneSchema<TEntries> => {\n const keys = Object.keys(entries);\n const keySet = new Set(keys);\n const isOperation = (\n operation: string\n ): operation is OperationName<TEntries> => keySet.has(operation);\n const schema = createSchema<\n InferInput<ExactlyOneSchema<TEntries>>,\n InferOutput<ExactlyOneSchema<TEntries>>\n >(\"exact_one\", (value) => {\n let selected: {\n operation: OperationName<TEntries>;\n operand: unknown;\n };\n try {\n if (!isRecord(value)) return fail(\"Expected object\");\n\n const ownKeys = Reflect.ownKeys(value);\n if (ownKeys.length !== 1) return fail(OPERATION_REFUSAL(keys));\n const [operation] = ownKeys;\n if (typeof operation !== \"string\" || !isOperation(operation)) {\n return fail(OPERATION_REFUSAL(keys));\n }\n\n // Any key on a caller-supplied prototype is a second declaration.\n // Object.prototype's built-ins are language machinery, but any added\n // string or symbol key still is not.\n const visited = new Set<object>();\n let prototype = Reflect.getPrototypeOf(value);\n while (prototype !== null) {\n if (visited.has(prototype)) return fail(OPERATION_REFUSAL(keys));\n visited.add(prototype);\n const isLanguageIntrinsic = prototype === Object.prototype;\n for (const inherited of Reflect.ownKeys(prototype)) {\n if (\n !isLanguageIntrinsic ||\n typeof inherited !== \"string\" ||\n !OBJECT_PROTOTYPE_KEYS.has(inherited)\n ) {\n return fail(OPERATION_REFUSAL(keys));\n }\n }\n prototype = Reflect.getPrototypeOf(prototype);\n }\n\n // Read a caller accessor once. The selected validator never re-enters\n // the hostile object.\n const operand = Reflect.get(value, operation);\n if (operand === undefined) return fail(OPERATION_REFUSAL(keys));\n selected = { operation, operand };\n } catch {\n return fail(OPERATION_REFUSAL(keys));\n }\n // Carrier reflection is hostile input and is contained above. The selected\n // validator is a different trust boundary: an external `.schema()` failure\n // must reach SchemaRegistry so it can retain the sanitized cause instead of\n // being mislabeled as an exact-one carrier refusal.\n const { operation, operand } = selected;\n const entry = entries[operation]!;\n const result = validateSchema(entry, operand);\n if (result.issues) {\n if (entry.type === \"refused\") return result;\n const [issue] = result.issues;\n return fail(issue!.message, [operation, ...(issue!.path ?? [])]);\n }\n const output = Object.create(null);\n output[operation] = result.value;\n return ok(output);\n });\n const metadata: Pick<ExactlyOneSchema<TEntries>, \"type\" | \"entries\"> = {\n type: \"exact_one\",\n entries,\n };\n\n return Object.assign(schema, metadata);\n};\n\ntype DecimalListOperations<\n S extends V.Schema,\n O extends V.Schema,\n L extends V.Schema,\n> = {\n set: S;\n push: DecimalPushSchema<O, L>;\n unshift: DecimalPushSchema<O, L>;\n increment: DecimalListRefusalSchema;\n decrement: DecimalListRefusalSchema;\n multiply: DecimalListRefusalSchema;\n divide: DecimalListRefusalSchema;\n};\n\n/**\n * The operation names declared by the one exact-one decimal update owner.\n *\n * The public client uses this projection to seal only a direct decimal update\n * leaf after it has inferred the caller's concrete object keys. Keeping the\n * names derived from these maps prevents the type boundary from restating a\n * second decimal operation language.\n */\nexport type DecimalUpdateOperationKeys<State extends ScalarState<\"decimal\">> =\n State[\"array\"] extends true\n ? keyof DecimalListOperations<V.Schema, V.Schema, V.Schema>\n : true extends State[\"array\"]\n ?\n | keyof DecimalOperations<V.Schema, V.Schema>\n | keyof DecimalListOperations<V.Schema, V.Schema, V.Schema>\n : keyof DecimalOperations<V.Schema, V.Schema>;\n\n// =============================================================================\n// DECIMAL SCHEMA BUILDER\n// =============================================================================\n\nexport interface DecimalSchemas<\n F extends ScalarState<\"decimal\">,\n C extends V.Operand<any> = V.Operand<any>,\n> {\n base: F[\"base\"];\n create: DecimalCreateSchema<F>;\n update: F[\"array\"] extends true\n ? DecimalListUpdateSchema<F[\"base\"], V.Decimal, V.Decimal<{ array: true }>>\n : DecimalUpdateSchema<F[\"base\"], ArithmeticOperand<F, V.Decimal>>;\n filter: F[\"array\"] extends true\n ? DecimalListFilterSchema<F[\"base\"], V.Decimal, V.Decimal<{ array: true }>>\n : DecimalFilterSchema<F[\"base\"], V.Decimal, V.Decimal<{ array: true }>, C>;\n}\n\ntype DecimalCreateSchema<F extends ScalarState<\"decimal\">> =\n F[\"hasDefault\"] extends true\n ? F[\"default\"] extends (...args: never[]) => unknown\n ? V.Decimal<F>\n : F[\"array\"] extends true\n ? V.Optional<F[\"base\"], () => InferOutput<F[\"base\"]>>\n : V.Optional<F[\"base\"], F[\"default\"]>\n : V.Decimal<F>;\n\nconst buildDecimalCreateSchema = (state: ScalarState<\"decimal\">) => {\n if (!state.hasDefault || typeof state.default === \"function\") {\n return v.decimal(state);\n }\n if (state.array && Array.isArray(state.default)) {\n const retained = state.default;\n return v.optional(state.base, () => retained.slice());\n }\n return v.optional(state.base, state.default);\n};\n\nexport function buildDecimalSchema<\n F extends ScalarState<\"decimal\">,\n C extends V.Operand<any> = V.Operand<any>,\n>(state: F): DecimalSchemas<F, C>;\nexport function buildDecimalSchema(state: ScalarState<\"decimal\">) {\n const domain = domainOf(state);\n // One MEMBER schema and one LIST schema per field, both holding the declared\n // domain. `state.base` carries the field's own nullability and arity, which\n // an operand must not inherit: only the whole-value arms take `null`.\n const member = () => v.decimal(domain);\n const list = () => v.decimal({ ...domain, array: true });\n const writeMember = () => v.decimal({ ...domain, schema: state.schema });\n const writeList = () =>\n v.decimal({ ...domain, array: true, schema: state.schema });\n const arithmeticMember = () =>\n state.schema === undefined\n ? member()\n : v.refused(REFINED_ARITHMETIC_REFUSAL);\n const filterBase = () =>\n v.decimal({ ...domain, nullable: state.nullable, array: state.array });\n\n return lazyScalarSchemas({\n base: state.base,\n // Literal decimal defaults already crossed the complete field codec at\n // declaration. Apply that trusted canonical output directly; explicit\n // input still delegates to `state.base`. The list path returns a fresh\n // container so operation output cannot mutate retained schema metadata. A\n // factory remains untrusted until each invocation and keeps the full codec.\n create: () => buildDecimalCreateSchema(state),\n update: () =>\n state.array\n ? v.union([\n v.shorthandUpdate(state.base),\n exactlyOneOperation({\n set: state.base,\n push: v.union([v.shorthandArray(writeMember()), writeList()]),\n unshift: v.union([v.shorthandArray(writeMember()), writeList()]),\n increment: v.refused(\n \"A decimal list update does not support 'increment'.\"\n ),\n decrement: v.refused(\n \"A decimal list update does not support 'decrement'.\"\n ),\n multiply: v.refused(\n \"A decimal list update does not support 'multiply'.\"\n ),\n divide: v.refused(\n \"A decimal list update does not support 'divide'.\"\n ),\n }),\n ])\n : v.union([\n v.shorthandUpdate(state.base),\n // All five operands are held to the field's own domain: the SQL\n // rounding rule works in coefficient space at the field scale, so\n // a finer `multiply` operand has no representation to be exact in.\n // Only derived RESULTS round; no input ever does.\n exactlyOneOperation({\n set: state.base,\n increment: arithmeticMember(),\n decrement: arithmeticMember(),\n multiply: arithmeticMember(),\n divide: arithmeticMember(),\n }),\n ]),\n filter: () =>\n state.array\n ? buildNegatableFilterSchema(\n v.object({\n equals: filterBase(),\n has: member(),\n hasEvery: list(),\n hasSome: list(),\n isEmpty: v.boolean(),\n in: v.refused(\"A decimal list filter does not support 'in'.\"),\n notIn: v.refused(\n \"A decimal list filter does not support 'notIn'.\"\n ),\n lt: v.refused(\"A decimal list filter does not support 'lt'.\"),\n lte: v.refused(\"A decimal list filter does not support 'lte'.\"),\n gt: v.refused(\"A decimal list filter does not support 'gt'.\"),\n gte: v.refused(\"A decimal list filter does not support 'gte'.\"),\n }),\n filterBase()\n )\n : buildDecimalFilterSchema(filterBase(), member, list),\n });\n}\n\nconst buildDecimalFilterSchema = <S extends V.Schema>(\n base: S,\n member: () => V.Decimal,\n list: () => V.Decimal<{ array: true }>\n) => {\n const operand = decimalComparisonOperand(base);\n return buildNegatableFilterSchema(\n v.object({\n equals: operand,\n in: list(),\n notIn: list(),\n lt: decimalComparisonOperand(member()),\n lte: decimalComparisonOperand(member()),\n gt: decimalComparisonOperand(member()),\n gte: decimalComparisonOperand(member()),\n }),\n operand\n );\n};\n","import type { ScalarState } from \"@schema/scalars/common\";\nimport type { EnumSchema, EnumValues } from \"@validation/primitives/enum\";\nimport { lazyScalarSchemas } from \"../lazy\";\nimport v, { type V } from \"../primitives/v\";\nimport {\n buildSetUpdate,\n type ListFilterSchema,\n type ListUpdateSchema,\n listFilterFamily,\n listUpdateFamily,\n type SetUpdateSchema,\n} from \"./family\";\nimport {\n buildNegatableFilterSchema,\n type NegatableFilterSchema,\n} from \"./negatable-filter\";\n\n// =============================================================================\n// FILTER TYPES\n// =============================================================================\n\n/**\n * Equality operand: a literal, a field reference to another enum column, an SQL\n * fragment, or a callback returning one of the latter two.\n */\ntype EnumOperand<\n S extends V.Schema,\n C extends V.Operand<any>,\n> = V.ComparisonOperand<\"enum\", S, C>;\n\ntype EnumFilterBase<\n S extends V.Schema,\n Values extends readonly string[],\n C extends V.Operand<any>,\n> = {\n equals: EnumOperand<S, C>;\n in: V.Enum<Values, { array: true }>;\n notIn: V.Enum<Values, { array: true }>;\n lt: V.Schema<never, never>;\n lte: V.Schema<never, never>;\n gt: V.Schema<never, never>;\n gte: V.Schema<never, never>;\n};\n\ntype EnumFilterSchema<\n S extends V.Schema,\n Values extends readonly string[],\n C extends V.Operand<any>,\n> = NegatableFilterSchema<EnumOperand<S, C>, EnumFilterBase<S, Values, C>>;\n\n/**\n * The list arms are the shared family, built PER FIELD: an enum's member and\n * list schemas are a function of that field's declared values, so unlike every\n * other kind there is no module-level pair to close over — and, for the same\n * reason, no interning (a key would have to carry the whole value list).\n */\ntype EnumListFilterSchema<\n S extends V.Schema,\n Values extends readonly string[],\n> = ListFilterSchema<S, V.Enum<Values>, V.Enum<Values, { array: true }>>;\n\ntype EnumListUpdateSchema<\n S extends V.Schema,\n Values extends readonly string[],\n> = ListUpdateSchema<S, V.Enum<Values>, V.Enum<Values, { array: true }>>;\n\n// =============================================================================\n// SCHEMA BUILDERS\n// =============================================================================\n\n/**\n * Ordered comparison on an enum has no portable answer, so it is refused —\n * loudly, rather than by being quietly absent.\n *\n * PostgreSQL stores an enum as its own type and orders it by DECLARATION\n * order; MySQL's `ENUM` compares as text once either side is coerced, and\n * SQLite stores plain text. `role > 'moderator'` would therefore select\n * different rows per provider, which is exactly the silent divergence a\n * portable ORM must not ship. `equals`/`not`/`in`/`notIn` are unaffected:\n * equality agrees everywhere.\n */\nconst orderedEnumRefusal = (operator: string) =>\n v.refused(\n `Filter operation '${operator}' is not supported on an enum field: PostgreSQL orders enum values by their declaration order while MySQL and SQLite compare them as text, so the same query would answer differently per provider. Use 'equals'/'in', or model the field as a string or int if you need ordering.`\n );\n\nconst enumBase = <Values extends readonly string[]>(values: Values) =>\n v.enum(values);\n\nconst enumList = <Values extends readonly string[]>(values: Values) =>\n v.enum(values, { array: true });\n\nconst buildEnumFilterSchema = <\n S extends V.Schema,\n Values extends readonly string[],\n C extends V.Operand<any>,\n>(\n schema: S,\n values: Values\n): EnumFilterSchema<S, Values, C> => {\n const list = enumList(values);\n const operand = v.comparisonOperand(\"enum\", schema);\n const filter = v.object({\n equals: operand,\n in: list,\n notIn: list,\n lt: orderedEnumRefusal(\"lt\"),\n lte: orderedEnumRefusal(\"lte\"),\n gt: orderedEnumRefusal(\"gt\"),\n gte: orderedEnumRefusal(\"gte\"),\n });\n return buildNegatableFilterSchema<\n EnumOperand<S, C>,\n EnumFilterBase<S, Values, C>\n >(filter, operand);\n};\n\nconst buildEnumListFilterSchema = <\n S extends V.Schema,\n Values extends readonly string[],\n>(\n schema: S,\n values: Values\n): EnumListFilterSchema<S, Values> =>\n listFilterFamily(\n () => enumBase(values),\n () => enumList(values)\n )(schema);\n\nconst buildEnumListUpdateSchema = <\n S extends V.Schema,\n Values extends readonly string[],\n>(\n schema: S,\n values: Values\n): EnumListUpdateSchema<S, Values> =>\n listUpdateFamily(\n () => enumBase(values),\n () => enumList(values)\n )(schema);\n\n// =============================================================================\n// ENUM SCHEMA BUILDER\n// =============================================================================\n\nexport interface EnumSchemas<\n Values extends readonly string[],\n F extends ScalarState<\"enum\">,\n C extends V.Operand<any> = V.Operand<any>,\n> {\n base: F[\"base\"];\n create: V.Enum<Values, F>;\n update: F[\"array\"] extends true\n ? EnumListUpdateSchema<F[\"base\"], Values>\n : SetUpdateSchema<F[\"base\"]>;\n filter: F[\"array\"] extends true\n ? EnumListFilterSchema<F[\"base\"], Values>\n : EnumFilterSchema<F[\"base\"], Values, C>;\n}\n\nexport const buildEnumSchema = <\n F extends ScalarState<\"enum\">,\n C extends V.Operand<any> = V.Operand<any>,\n>(\n state: F\n): EnumSchemas<EnumValues<F[\"base\"]>, F, C> => {\n const values = (state.base as EnumSchema<EnumValues<F[\"base\"]>>).values;\n return lazyScalarSchemas<EnumSchemas<EnumValues<F[\"base\"]>, F, C>>({\n base: state.base,\n create: () => v.enum(values, state),\n update: () =>\n (state.array\n ? buildEnumListUpdateSchema(state.base, values)\n : buildSetUpdate(state.base)) as never,\n filter: () =>\n (state.array\n ? buildEnumListFilterSchema(state.base, values)\n : buildEnumFilterSchema(state.base, values)) as never,\n });\n};\n","import type { ScalarState } from \"@schema/scalars/common\";\nimport v, { type V } from \"../primitives/v\";\nimport {\n type ArithmeticUpdateSchema,\n type ComparisonFilterSchema,\n comparableScalar,\n type ListFilterSchema,\n type ListUpdateSchema,\n type SetUpdateSchema,\n} from \"./family\";\n\ntype IntegerList = V.Integer<{ array: true }>;\n\nexport interface IntSchemas<\n F extends ScalarState<\"int\">,\n C extends V.Operand<any> = V.Operand<any>,\n> {\n base: F[\"base\"];\n create: V.Integer<F>;\n update: F[\"array\"] extends true\n ? ListUpdateSchema<F[\"base\"], V.Integer, IntegerList>\n : F[\"schema\"] extends undefined\n ? ArithmeticUpdateSchema<F[\"base\"], V.Integer>\n : SetUpdateSchema<F[\"base\"]>;\n filter: F[\"array\"] extends true\n ? ListFilterSchema<F[\"base\"], V.Integer, IntegerList>\n : ComparisonFilterSchema<\"int\", F[\"base\"], V.Integer, IntegerList, C>;\n}\n\nexport const buildIntSchema: <\n F extends ScalarState<\"int\">,\n C extends V.Operand<any> = V.Operand<any>,\n>(\n state: F\n) => IntSchemas<F, C> = comparableScalar(\"int\", v.integer, true);\n","import { JsonNull, type JsonNullKind, jsonNullKindOf } from \"@schema/json-null\";\nimport type { ScalarState } from \"@schema/scalars/common\";\nimport { lazyScalarSchemas } from \"../lazy\";\nimport { createSchema, fail, ok, validateSchema } from \"../primitives/helpers\";\nimport v, { type V } from \"../primitives/v\";\nimport type { VibSchema } from \"../types\";\nimport { isRecord } from \"../value-guards\";\nimport { requireFilterOperation } from \"./negatable-filter\";\n\n// =============================================================================\n// FILTER TYPES\n// =============================================================================\n\n/**\n * lt/lte/gt/gte take a number OR a string operand; the operand's class picks\n * numeric vs lexicographic comparison at the path (see json-filter-builder).\n */\ntype JsonComparisonOperand = V.Union<readonly [V.Number, V.String]>;\n\n/**\n * Prisma spells a JSON path two ways: the portable array form and\n * Prisma-MySQL's '$.a.b' string form. ADMISSION parses the string form into\n * the array form, so a prepared filter carries segments and nothing else —\n * the one place the two spellings become one fact.\n */\ntype JsonPathOperand = VibSchema<readonly string[] | string, string[]>;\n\n/**\n * A whole-document JSON operand, re-closed to field references.\n *\n * JSON is the only surface in the schema layer that accepts an ARBITRARY\n * object, so it is the only one where a field-reference token type-checks as a\n * legal value: `{ [FIELD_REF_BRAND]: true, model, field, type, list }` is a\n * perfectly ordinary JSON document as far as `v.json` is concerned. Left\n * unguarded, `where: { data: { equals: <a field reference> } }` bound the ORM's\n * internal token as a parameter and quietly matched nothing, and\n * `create({ data: { data: ref } })` PERSISTED it as user data.\n *\n * References are not opened here for a reason, so the wrapper is a closure and\n * not a gap: an operand of `equals`/`array_*` is compared as a whole JSON\n * VALUE (`@>`, `#>`, `JSON_CONTAINS`), not as a column expression, so there is\n * nothing for a column reference to mean. Failing closed is the doctrine;\n * silently binding an ORM-internal object is the opposite of it.\n */\ntype JsonOperand<S extends V.Schema> = V.NoFieldRef<S>;\n\n/**\n * Every JSON null sentinel is legal in a filter operand: `equals: DbNull`\n * asks for the SQL NULL, `equals: JsonNull` for the JSON null document, and\n * `equals: AnyNull` for either. `not` takes the same three, spelled on the\n * `not` key itself (`not: DbNull`) exactly as Prisma spells it.\n */\ntype JsonFilterNullOperand<S extends V.Schema> = V.JsonNullOr<\n JsonNullKind,\n JsonOperand<S>\n>;\n\ntype JsonFilterBase<S extends V.Schema> = {\n equals: JsonFilterNullOperand<S>;\n path: JsonPathOperand;\n mode: V.Enum<[\"default\", \"insensitive\"]>;\n lt: JsonComparisonOperand;\n lte: JsonComparisonOperand;\n gt: JsonComparisonOperand;\n gte: JsonComparisonOperand;\n string_contains: V.String;\n string_starts_with: V.String;\n string_ends_with: V.String;\n array_contains: JsonOperand<S>;\n array_starts_with: JsonOperand<S>;\n array_ends_with: JsonOperand<S>;\n};\n\n/** Where a refused reference is reported from, in the filter and write paths. */\nconst JSON_FILTER_SITE = \"a JSON filter operand\";\nconst JSON_DATA_SITE = \"JSON write data\";\n\n/** Every sentinel is a legal filter question. */\nconst FILTER_SENTINELS: readonly JsonNullKind[] = [\n \"DbNull\",\n \"JsonNull\",\n \"AnyNull\",\n];\n\n/**\n * `AnyNull` is FILTER-ONLY, as in Prisma: \"either null\" is a question, not a\n * value, so a write has nothing to store for it. `DbNull` additionally needs a\n * column that can hold the SQL NULL, so a non-nullable JSON field accepts only\n * `JsonNull` — the refusal names the reason instead of deferring to a NOT NULL\n * constraint violation from the database.\n */\nconst NULLABLE_WRITE_SENTINELS: readonly JsonNullKind[] = [\n \"DbNull\",\n \"JsonNull\",\n];\nconst NON_NULLABLE_WRITE_SENTINELS: readonly JsonNullKind[] = [\"JsonNull\"];\n\ntype JsonWriteSentinels<F extends ScalarState<\"json\">> =\n F[\"nullable\"] extends true ? \"DbNull\" | \"JsonNull\" : \"JsonNull\";\n\ntype JsonFilterSchema<S extends V.Schema> = V.Object<\n JsonFilterBase<S> & {\n not: V.JsonNullOr<JsonNullKind, V.Object<JsonFilterBase<S>>>;\n }\n>;\n\n// =============================================================================\n// UPDATE TYPES\n// =============================================================================\n\ntype JsonWriteOperand<\n F extends ScalarState<\"json\">,\n S extends V.Schema,\n> = V.JsonWrite<JsonWriteSentinels<F>, V.NoFieldRef<S>>;\n\ntype JsonUpdateSchema<\n F extends ScalarState<\"json\">,\n S extends V.Schema,\n> = V.Union<\n readonly [\n V.Object<{ set: JsonWriteOperand<F, S> }, { partial: false }>,\n V.Coerce<\n JsonWriteOperand<F, S>,\n { set: JsonWriteOperand<F, S>[\" vibInferred\"][\"1\"] }\n >,\n ]\n>;\n\n/**\n * The create schema reads the same envelope (see {@link isSetEnvelope}), so it\n * takes what an update takes and yields the value it stores.\n */\ntype JsonCreateSchema<\n F extends ScalarState<\"json\">,\n S extends V.Schema,\n> = VibSchema<\n | V.Input<JsonWriteOperand<F, S>>\n | { set: Exclude<V.Input<JsonWriteOperand<F, S>>, undefined> },\n V.Output<JsonWriteOperand<F, S>>\n>;\n\n// =============================================================================\n// JSON PATH GRAMMAR (admission owns both spellings)\n// =============================================================================\n\nconst JSON_PATH_ARRAY_INDEX = /^\\d+$/;\n\nconst JSON_PATH_GRAMMAR =\n \"The supported grammar is '$', '$.key', '$.key[0]' and nothing else; use the array form (path: ['a', 'b']) for keys containing '.', '[' or ']'.\";\n\nconst unsupportedPathString = (raw: string, reason: string): string =>\n `JSON filter has an unsupported path string '${raw}': ${reason}. ${JSON_PATH_GRAMMAR}`;\n\n/**\n * Parse Prisma-MySQL's string path form ('$.a.b', '$.arr[0]') into the array\n * form the preparer, the adapters and every dialect already speak.\n *\n * The grammar is DELIBERATELY small: '$' root, '.key' object steps, '[N]'\n * array indices. Quoted labels ('$.\"a b\"'), wildcards ('$.*', '[*]'),\n * '[last]' and negative indices are REFUSED rather than half-supported —\n * SQLite's path grammar has no escape syntax inside quoted labels, so a\n * larger grammar could not stay portable. A '.' inside a key is a separator\n * here and can only be spelled with the array form (path: ['weird.key']).\n * A segment carrying '\"' or '\\\\' falls through to the portability rule\n * below, which refuses it exactly as it does for the array form.\n */\nconst parseJsonStringPath = (raw: string): string[] | string => {\n if (!raw.startsWith(\"$\")) {\n return unsupportedPathString(raw, \"a path string must start with '$'\");\n }\n const segments: string[] = [];\n let index = 1;\n while (index < raw.length) {\n const char = raw[index];\n if (char === \".\") {\n index += 1;\n const start = index;\n while (index < raw.length && raw[index] !== \".\" && raw[index] !== \"[\") {\n index += 1;\n }\n const key = raw.slice(start, index);\n if (key.length === 0) {\n return unsupportedPathString(raw, \"an object key may not be empty\");\n }\n if (key.includes(\"*\")) {\n // '$.*' means \"any member\" in MySQL's JSONPath. Reading it as a key\n // literally named '*' would silently answer a different question,\n // so refuse it; a real '*' key is addressable via the array form.\n return unsupportedPathString(raw, \"wildcards are not supported\");\n }\n segments.push(key);\n continue;\n }\n if (char === \"[\") {\n const close = raw.indexOf(\"]\", index);\n if (close === -1) {\n return unsupportedPathString(raw, \"an unclosed '['\");\n }\n const digits = raw.slice(index + 1, close);\n if (!JSON_PATH_ARRAY_INDEX.test(digits)) {\n return unsupportedPathString(\n raw,\n `'[${digits}]' is not a non-negative integer array index`\n );\n }\n segments.push(digits);\n index = close + 1;\n continue;\n }\n return unsupportedPathString(raw, `unexpected '${char}'`);\n }\n return segments;\n};\n\n/**\n * ONE portability rule for BOTH spellings, asked on every dialect.\n *\n * A segment carrying '\"' or '\\\\' cannot be addressed portably: SQLite's\n * `json_extract` path grammar has no escape syntax inside a quoted label, so\n * the key is unaddressable there and binding it silently on PostgreSQL and\n * MySQL would make one question answer three ways. The SQLite adapter's own\n * throw stays what it says it is — a defensive backstop.\n */\nconst portablePathRefusal = (\n segments: readonly string[]\n): string | undefined =>\n segments.some((segment) => segment.includes('\"') || segment.includes(\"\\\\\"))\n ? \"JSON filter requires a portable JSON path; segments containing '\\\"' or '\\\\' are not supported.\"\n : undefined;\n\nconst jsonPathSegments = v.array(v.string());\nconst jsonPathString = v.string();\n\nconst buildJsonPathSchema = (): JsonPathOperand => {\n const schema = createSchema<readonly string[] | string, string[]>(\n \"union\",\n (value) => {\n if (Array.isArray(value)) {\n const segments = value.map(String);\n const refusal = portablePathRefusal(segments);\n return refusal ? fail(refusal) : ok(segments);\n }\n if (typeof value !== \"string\") {\n return fail(\"Expected string or array of strings\");\n }\n const parsed = parseJsonStringPath(value);\n if (typeof parsed === \"string\") return fail(parsed);\n const refusal = portablePathRefusal(parsed);\n return refusal ? fail(refusal) : ok(parsed);\n }\n );\n // `type`/`options` mirror `v.union` so introspection (JSON Schema\n // conversion) sees the two spellings it expects.\n (schema as { options?: unknown }).options = [\n jsonPathSegments,\n jsonPathString,\n ];\n return schema;\n};\n\n/**\n * The operators `mode: \"insensitive\"` governs. `equals`/`not`/`array_*`\n * compare whole JSON values, not text, so folding them would be meaningless\n * — which is why an inert `mode` is refused rather than ignored.\n */\nconst MODE_GOVERNED_OPERATORS = [\n \"string_contains\",\n \"string_starts_with\",\n \"string_ends_with\",\n] as const;\n\nconst INERT_MODE_REFUSAL =\n \"JSON filter sets mode: 'insensitive' but has no string_contains/string_starts_with/string_ends_with operation for it to apply to.\";\n\n/**\n * Fail closed on an inert `mode: \"insensitive\"`. A mode declared on THIS\n * object must govern a string operator here, or a nested `not` that inherits\n * it; otherwise the engine would accept the key and silently do nothing.\n * Inherited modes are exempt — `{ mode, string_contains, not: { equals } }`\n * is legitimate, and only the arm that spelled `mode` has to justify it.\n *\n * A SENTINEL `not` (`not: DbNull`) is not an exemption: it inherits nothing\n * and case-folds nothing, so a mode declared beside it governs exactly\n * nothing and has to be refused like any other inert one.\n */\nconst inertModeRefusal = (\n value: Record<string, unknown>\n): string | undefined => {\n if (value.mode !== \"insensitive\") return undefined;\n if (value.not !== undefined && jsonNullKindOf(value.not) === undefined) {\n return undefined;\n }\n return MODE_GOVERNED_OPERATORS.some(\n (operator) => value[operator] !== undefined\n )\n ? undefined\n : INERT_MODE_REFUSAL;\n};\n\n/**\n * A sentinel names the database NULL or the JSON null of the WHOLE column, so\n * under a `path` (the filter's own, which also scopes its `not`) it means\n * nothing; `equals: null` is the JSON null at that path.\n */\nconst pathSentinelRefusal = (\n value: Record<string, unknown>\n): string | undefined => {\n if (value.path === undefined) return undefined;\n const { equals, not } = value;\n const sentinel =\n jsonNullKindOf(equals) ??\n jsonNullKindOf(not) ??\n (isRecord(not) ? jsonNullKindOf(not.equals) : undefined);\n return (\n sentinel &&\n `JSON filter cannot combine 'path' with the ${sentinel} sentinel: the sentinels distinguish the database NULL from the JSON null value of the WHOLE column. Use 'path' with 'equals: null' to test for a JSON null at that path.`\n );\n};\n\n// =============================================================================\n// SCHEMA BUILDERS\n// =============================================================================\n\nconst buildJsonFilterSchema = <S extends V.Schema>(\n schema: S\n): JsonFilterSchema<S> => {\n const comparisonOperand = v.union([v.number(), v.string()]);\n const operand = v.noFieldRef(schema, JSON_FILTER_SITE);\n const nullOperand = v.jsonNullOr(FILTER_SENTINELS, operand, JSON_FILTER_SITE);\n const entries = {\n equals: nullOperand,\n path: buildJsonPathSchema(),\n mode: v.enum([\"default\", \"insensitive\"]),\n lt: comparisonOperand,\n lte: comparisonOperand,\n gt: comparisonOperand,\n gte: comparisonOperand,\n string_contains: v.string(),\n string_starts_with: v.string(),\n string_ends_with: v.string(),\n array_contains: operand,\n array_starts_with: operand,\n array_ends_with: operand,\n };\n // `path` and `mode` SCOPE the filter; the refusal below is what makes\n // `{ path: ['status'] }` fail closed instead of comparing the whole\n // document, and what makes a declared `mode` justify itself.\n const refuse = (value: Record<string, unknown>): string | undefined =>\n requireFilterOperation(value) ??\n inertModeRefusal(value) ??\n pathSentinelRefusal(value);\n const filter = v.object(entries, { refuse });\n const jsonFilter = v.object(\n {\n ...entries,\n // `not: DbNull` / `not: JsonNull` / `not: AnyNull` are the sentinel\n // spellings Prisma uses; the nested filter object stays available for\n // everything else (`not: { equals: … }`).\n not: v.jsonNullOr(FILTER_SENTINELS, filter, JSON_FILTER_SITE),\n },\n { refuse }\n );\n // A sentinel is an operand: in the field's own position it compares\n // nothing, so it is refused by name there instead of read as an object.\n const validate = jsonFilter[\"~standard\"].validate;\n Object.defineProperty(jsonFilter[\"~standard\"], \"validate\", {\n value: (value: unknown) => {\n const sentinel = jsonNullKindOf(value);\n return sentinel\n ? fail(\n `${sentinel} is an operand, not a JSON filter; compare with { equals: ${sentinel} }.`\n )\n : validate(value);\n },\n });\n return jsonFilter as unknown as JsonFilterSchema<S>;\n};\n\n/**\n * The refusal a bare top-level `null` gets in write position, spelled per\n * field so it can only recommend sentinels the field can actually store.\n */\nconst nullWriteRefusal = (nullable: boolean): string =>\n nullable\n ? \"null is ambiguous in JSON write data: it could mean the database NULL or the JSON value null. Use DbNull for the database NULL, or JsonNull for the JSON value null.\"\n : \"null is ambiguous in JSON write data: it could mean the database NULL or the JSON value null. This field is not nullable, so use JsonNull to write the JSON value null.\";\n\nconst buildJsonWriteOperand = <\n F extends ScalarState<\"json\">,\n S extends V.Schema,\n>(\n state: F,\n schema: S\n): JsonWriteOperand<F, S> =>\n v.jsonWrite(\n state.nullable ? NULLABLE_WRITE_SENTINELS : NON_NULLABLE_WRITE_SENTINELS,\n // `create`/`update` are closed to field references for the same reason the\n // filter operands are, with a worse failure mode: an unguarded token is not\n // merely bound and ignored, it is WRITTEN — the ORM's own\n // `{ model, field, type, list }` record lands in the user's JSON column as\n // if it were their data.\n v.noFieldRef(schema, JSON_DATA_SITE),\n JSON_DATA_SITE,\n nullWriteRefusal(state.nullable)\n ) as JsonWriteOperand<F, S>;\n\n/**\n * A one-key `{ set }` object is the write ENVELOPE on every JSON write path —\n * create, createMany, both arms of upsert and nested creates as on update\n * (decision 5) — so `{ set: v }` stores `v`. It is unwrapped once: a literal\n * one-key `set` document is written `{ set: { set: v } }`, and an invalid\n * envelope value is refused, never retried as a document.\n */\nconst isSetEnvelope = (value: unknown): value is { set: unknown } =>\n isRecord(value) &&\n Object.hasOwn(value, \"set\") &&\n Object.keys(value).length === 1;\n\nconst buildJsonUpdateSchema = <\n F extends ScalarState<\"json\">,\n S extends V.Schema,\n>(\n state: F,\n schema: S\n): JsonUpdateSchema<F, S> => {\n const operand = buildJsonWriteOperand(state, schema);\n const explicit = v.object({ set: operand }, { partial: false });\n const direct = v.shorthandUpdate(operand);\n const update = v.union([explicit, direct]);\n Object.defineProperty(update[\"~standard\"], \"validate\", {\n value: (value: unknown) =>\n isSetEnvelope(value)\n ? validateSchema(explicit, value)\n : validateSchema(direct, value),\n });\n return update;\n};\n\n// =============================================================================\n// JSON SCHEMA BUILDER\n// =============================================================================\n\nexport interface JsonSchemas<F extends ScalarState<\"json\">> {\n base: F[\"base\"];\n create: JsonCreateSchema<F, V.Json<F>>;\n update: JsonUpdateSchema<F, F[\"base\"]>;\n filter: JsonFilterSchema<V.Json>;\n}\n\nexport const buildJsonSchema = <F extends ScalarState<\"json\">>(\n state: F\n): JsonSchemas<F> => {\n return lazyScalarSchemas<JsonSchemas<F>>({\n base: state.base,\n create: () => {\n const operand = buildJsonWriteOperand(state, v.json(state));\n const validate = operand[\"~standard\"].validate;\n const admit = (value: unknown) => {\n if (value !== undefined || !state.hasDefault) return validate(value);\n let defaultValue: unknown;\n try {\n defaultValue =\n typeof state.default === \"function\"\n ? state.default()\n : state.default;\n } catch {\n return fail(\"JSON default failed\");\n }\n if (defaultValue === undefined)\n return fail(\"JSON default must resolve to a value\");\n // Omission preserves SQL NULL for nullable fields; an explicit JSON\n // null default uses the same sentinel admitted by ordinary writes.\n if (defaultValue === null)\n return state.nullable ? ok(null) : validate(JsonNull);\n return validate(defaultValue);\n };\n Object.defineProperty(operand[\"~standard\"], \"validate\", {\n value: (value: unknown) => {\n if (!isSetEnvelope(value)) return admit(value);\n const result = admit(value.set);\n // Rooted under `set`, as the update's envelope reports them.\n return result.issues\n ? {\n issues: result.issues.map(({ message, path }) => ({\n message,\n path: [\"set\", ...(path ?? [])],\n })),\n }\n : result;\n },\n });\n return operand as JsonCreateSchema<F, V.Json<F>>;\n },\n update: () => buildJsonUpdateSchema<F, F[\"base\"]>(state, state.base),\n filter: () => buildJsonFilterSchema(v.json()),\n });\n};\n","import type { ScalarState } from \"@schema/scalars/common\";\nimport v, { type V } from \"../primitives/v\";\nimport {\n type ArithmeticUpdateSchema,\n type ComparisonFilterSchema,\n comparableScalar,\n type ListFilterSchema,\n type ListUpdateSchema,\n type SetUpdateSchema,\n} from \"./family\";\n\ntype NumberList = V.Number<{ array: true }>;\n\nexport interface NumberSchemas<\n F extends ScalarState<\"number\">,\n C extends V.Operand<any> = V.Operand<any>,\n> {\n base: F[\"base\"];\n create: V.Number<F>;\n update: F[\"array\"] extends true\n ? ListUpdateSchema<F[\"base\"], V.Number, NumberList>\n : F[\"schema\"] extends undefined\n ? ArithmeticUpdateSchema<F[\"base\"], V.Number>\n : SetUpdateSchema<F[\"base\"]>;\n filter: F[\"array\"] extends true\n ? ListFilterSchema<F[\"base\"], V.Number, NumberList>\n : ComparisonFilterSchema<\"number\", F[\"base\"], V.Number, NumberList, C>;\n}\n\nexport const buildNumberSchema: <\n F extends ScalarState<\"number\">,\n C extends V.Operand<any> = V.Operand<any>,\n>(\n state: F\n) => NumberSchemas<F, C> = comparableScalar(\"number\", v.number, true);\n","import type { ScalarState } from \"@schema/scalars/common\";\nimport { lazyScalarSchemas } from \"../lazy\";\nimport { geoAreaSchema } from \"../primitives/geo-area-codec\";\nimport { createSchema, fail, ok } from \"../primitives/helpers\";\nimport { validateNumber } from \"../primitives/number\";\nimport v, { type V } from \"../primitives/v\";\nimport { buildSetUpdate, type SetUpdateSchema } from \"./family\";\nimport {\n buildNegatableFilterSchema,\n type NegatableFilterSchema,\n} from \"./negatable-filter\";\n\n// =============================================================================\n// FILTER TYPES\n// =============================================================================\n\ntype PointFilterBase<S extends V.Schema> = {\n equals: S;\n distance: ReturnType<typeof pointDistanceSchema>;\n within: ReturnType<typeof geoAreaSchema>;\n};\n\ntype PointFilterSchema<S extends V.Schema> = NegatableFilterSchema<\n S,\n PointFilterBase<S>\n>;\n\n// =============================================================================\n// SCHEMA BUILDERS\n// =============================================================================\n\nconst meters = createSchema<number, number>(\"number\", (value) => {\n const result = validateNumber(value);\n if (result.issues) return result;\n return result.value < 0\n ? fail(\"Distance comparisons must use non-negative meters\")\n : ok(result.value);\n});\n\nconst pointDistanceSchema = () =>\n v.object(\n {\n to: v.point(),\n lt: meters,\n lte: meters,\n gt: meters,\n gte: meters,\n },\n {\n atLeast: [\"to\"],\n requiresOneOf: [[\"lt\", \"lte\", \"gt\", \"gte\"]],\n }\n );\n\nconst buildPointFilterSchema = <S extends V.Schema>(\n schema: S\n): PointFilterSchema<S> => {\n const filter = v.object({\n equals: schema,\n distance: pointDistanceSchema(),\n within: geoAreaSchema(),\n });\n return buildNegatableFilterSchema<S, PointFilterBase<S>>(filter, schema);\n};\n\n// =============================================================================\n// POINT SCHEMA BUILDER\n// =============================================================================\n\nexport interface PointSchemas<F extends ScalarState<\"point\">> {\n base: F[\"base\"];\n create: V.Point<F>;\n update: SetUpdateSchema<F[\"base\"]>;\n filter: PointFilterSchema<F[\"base\"]>;\n}\n\nexport const buildPointSchema = <F extends ScalarState<\"point\">>(\n state: F\n): PointSchemas<F> => {\n return lazyScalarSchemas<PointSchemas<F>>({\n base: state.base,\n create: () => v.point(state),\n update: () => buildSetUpdate<F[\"base\"]>(state.base),\n filter: () => buildPointFilterSchema<F[\"base\"]>(state.base),\n });\n};\n","import type { ScalarState } from \"@schema/scalars/common\";\nimport {\n idDomainOfState,\n idMemberDomainOfState,\n} from \"@schema/scalars/string/id-domain\";\nimport { type IdDomain, isCompactIdFormat } from \"../primitives/id-codec\";\nimport v, { type V } from \"../primitives/v\";\nimport {\n buildSetUpdate,\n createScalarInterners,\n internedScalarSchemas,\n type ListFilterSchema,\n type ListUpdateSchema,\n listFilterFamily,\n listUpdateFamily,\n once,\n type SetUpdateSchema,\n withScalarOutputDomain,\n} from \"./family\";\nimport { scalarInternKey } from \"./intern\";\nimport {\n buildNegatableFilterSchema,\n type NegatableFilterSchema,\n} from \"./negatable-filter\";\n\n// Base schemas\nconst stringBase = once(() => v.string());\nconst stringList = once(() => v.string({ array: true }));\n\n// Internal filter base\nconst stringFilterBase = once(() =>\n v.object({\n in: stringList(),\n notIn: stringList(),\n contains: v.fieldRefOr(\"string\", stringBase()),\n startsWith: v.fieldRefOr(\"string\", stringBase()),\n endsWith: v.fieldRefOr(\"string\", stringBase()),\n mode: v.enum([\"default\", \"insensitive\"]),\n })\n);\n\n/**\n * The filter base of a COMPACTLY STORED identifier: equality, set membership\n * and ordering, and nothing that reads the value as text.\n *\n * `contains`, `startsWith`, `endsWith` and `mode` are gone because the column\n * does not hold the text they would search. A `uuid` column holds sixteen\n * bytes and a PostgreSQL `uuid`; `startsWith: \"a0ee\"` against it is a question\n * about a spelling the database never stored, and answering it would mean\n * rendering every row back to text at query time. Ordering survives: the byte\n * order of all four compact formats IS their canonical text order.\n */\nconst compactIdFilterBase = once(() =>\n v.object({\n in: stringList(),\n notIn: stringList(),\n })\n);\n\n/**\n * Comparison operand: a literal, a field reference to another string column, an\n * SQL fragment, or a callback returning one of the latter two.\n */\ntype StringOperand<\n S extends V.Schema,\n C extends V.Operand<any>,\n> = V.ComparisonOperand<\"string\", S, C>;\n\n/**\n * The text-predicate operand: a literal or a field reference, and nothing else.\n *\n * `contains` / `startsWith` / `endsWith` compile a referenced column fine (the\n * builder uses exact substring predicates, never LIKE patterns), so the\n * reference stays. The fragment — and with it the callback that returns one —\n * is drawn at the comparison operators only, where the builder's operand\n * handling is uniform. Acceptance that outran the builder would be\n * accept-and-ignore with extra steps.\n */\ntype StringTextOperand = V.FieldRefOr<\"string\", V.String>;\n\ntype StringFilterBase<S extends V.Schema, C extends V.Operand<any>> = {\n equals: StringOperand<S, C>;\n lt: StringOperand<S, C>;\n lte: StringOperand<S, C>;\n gt: StringOperand<S, C>;\n gte: StringOperand<S, C>;\n in: V.String<{ array: true }>;\n notIn: V.String<{ array: true }>;\n contains: StringTextOperand;\n startsWith: StringTextOperand;\n endsWith: StringTextOperand;\n mode: V.Enum<[\"default\", \"insensitive\"]>;\n};\n\ntype StringFilterSchema<\n S extends V.Schema,\n C extends V.Operand<any>,\n> = NegatableFilterSchema<StringOperand<S, C>, StringFilterBase<S, C>>;\n\n/** {@link StringFilterBase} without the four text predicates. */\ntype CompactIdFilterBase<S extends V.Schema, C extends V.Operand<any>> = {\n equals: StringOperand<S, C>;\n lt: StringOperand<S, C>;\n lte: StringOperand<S, C>;\n gt: StringOperand<S, C>;\n gte: StringOperand<S, C>;\n in: V.String<{ array: true }>;\n notIn: V.String<{ array: true }>;\n};\n\ntype CompactIdFilterSchema<\n S extends V.Schema,\n C extends V.Operand<any>,\n> = NegatableFilterSchema<StringOperand<S, C>, CompactIdFilterBase<S, C>>;\n\n/** The four formats a column stores compactly, and therefore cannot search. */\ntype CompactIdKind = \"uuid\" | \"uuidv7\" | \"ulid\" | \"ksuid\";\n\n/**\n * Whether this state NAMES one of the four compact identifier formats.\n *\n * Three arms, and each one is a real case:\n *\n * - No generator at all. `NonNullable<undefined>` is `never`, and `never`\n * vacuously extends everything, so a plain `s.string()` would otherwise be\n * handed the narrowed filter its column has no reason for.\n * - `.id()`'s implicit ULID. It declares a KEY, not a format, so the field\n * keeps text storage and every string operator; narrowing here would offer\n * a type the runtime schema does not enforce.\n * - A named format, which is the only `true`.\n *\n * Each check is wrapped in a tuple so it cannot distribute: an undeclared field\n * carries the whole `AutoGenerateType` union, and a distributing conditional\n * answers `boolean` for it — neither arm.\n */\ntype DeclaresCompactId<F extends ScalarState<\"string\">> = [\n NonNullable<F[\"autoGenerate\"]>,\n] extends [never]\n ? false\n : [NonNullable<F[\"autoGenerate\"]>[\"implicit\"]] extends [true]\n ? false\n : [NonNullable<F[\"autoGenerate\"]>[\"kind\"]] extends [CompactIdKind]\n ? true\n : false;\n\nconst buildStringFilterSchema = <S extends V.Schema, C extends V.Operand<any>>(\n schema: S,\n members: V.String<{ array: true }>\n): StringFilterSchema<S, C> => {\n const operand = v.comparisonOperand(\"string\", schema);\n const filter = stringFilterBase().extend({\n equals: operand,\n lt: operand,\n lte: operand,\n gt: operand,\n gte: operand,\n in: members,\n notIn: members,\n });\n return buildNegatableFilterSchema<\n StringOperand<S, C>,\n StringFilterBase<S, C>\n >(filter, operand);\n};\n\nconst buildCompactIdFilterSchema = <\n S extends V.Schema,\n C extends V.Operand<any>,\n>(\n schema: S,\n members: V.String<{ array: true }>\n): CompactIdFilterSchema<S, C> => {\n const operand = v.comparisonOperand(\"string\", schema);\n const filter = compactIdFilterBase().extend({\n equals: operand,\n lt: operand,\n lte: operand,\n gt: operand,\n gte: operand,\n in: members,\n notIn: members,\n });\n return buildNegatableFilterSchema<\n StringOperand<S, C>,\n CompactIdFilterBase<S, C>\n >(filter, operand);\n};\n\n/**\n * An unformatted string list uses the shared family. A named member domain\n * supplies the same family with canonicalizing primitives, keeping plain string\n * physical storage and the ordinary list operator language.\n */\nconst buildStringListFilterSchema = listFilterFamily(stringBase, stringList);\nconst buildStringListUpdateSchema = listUpdateFamily(stringBase, stringList);\n\nexport interface StringSchemas<\n F extends ScalarState<\"string\">,\n C extends V.Operand<any> = V.Operand<any>,\n> {\n base: F[\"base\"];\n create: V.String<F>;\n update: F[\"array\"] extends true\n ? ListUpdateSchema<F[\"base\"], V.String, V.String<{ array: true }>>\n : SetUpdateSchema<F[\"base\"]>;\n filter: F[\"array\"] extends true\n ? ListFilterSchema<F[\"base\"], V.String, V.String<{ array: true }>>\n : DeclaresCompactId<F> extends true\n ? CompactIdFilterSchema<F[\"base\"], C>\n : StringFilterSchema<F[\"base\"], C>;\n}\n\nconst interners = createScalarInterners();\n\n/**\n * The field's base schema, with its identifier domain admitted.\n *\n * A domain field's base is the schema EVERY operand is built from — filter\n * comparisons, `set`, list members, the compound-key member schemas — so\n * admitting and normalizing here is what makes one policy cover create,\n * update, where, cursors, unique selectors and nested-write keys at once. A\n * field without a domain keeps the base the scalar already froze: no domain,\n * no second schema.\n */\nconst domainBaseOf = <F extends ScalarState<\"string\">>(\n state: F,\n idDomain: IdDomain | undefined\n): F[\"base\"] => {\n if (idDomain === undefined) return state.base;\n const options = {\n nullable: state.nullable,\n array: state.array,\n schema: state.schema,\n idDomain,\n };\n return v.string(options);\n};\n\n/**\n * The SET-MEMBERSHIP operand — `in` / `notIn`, and the negated arm with them.\n *\n * A member of `in` is an identifier exactly as `equals`'s operand is, so it\n * crosses the same admission and the same alias folding. The module-level\n * `stringList` cannot carry a field's domain, and a set built from it admitted\n * a value outside the domain (refused later, at the wrong boundary, as a\n * `QueryEngineError`) and left an alias unfolded — which hashed ONE identifier\n * to two cache keys, the exact failure normalizing at the args boundary exists\n * to prevent.\n */\nconst domainMembersOf = (\n idDomain: IdDomain | undefined\n): V.String<{ array: true }> =>\n idDomain === undefined ? stringList() : v.string({ array: true, idDomain });\n\n/** The create options, which differ from the state only by the domain. */\nconst domainStateOf = <F extends ScalarState<\"string\">>(\n state: F,\n idDomain: IdDomain | undefined\n): F => (idDomain === undefined ? state : { ...state, idDomain });\n\n/**\n * The schemas of one string field.\n *\n * `derived` is the domain a FOREIGN-KEY member inherits from the key it\n * references — resolved once in L5 and threaded here by the registry, because\n * an FK carries no generator of its own and its state is deliberately left\n * untouched. A field that declares its own domain reads it from that\n * declaration; nothing merges the two, because a declared domain that\n * disagrees with its target is a schema error, refused before any schema is\n * built.\n */\nexport const buildStringSchema = <\n F extends ScalarState<\"string\">,\n C extends V.Operand<any> = V.Operand<any>,\n>(\n state: F,\n derived?: IdDomain\n): StringSchemas<F, C> => {\n const idDomain =\n state.array === true\n ? idMemberDomainOfState(state)\n : (idDomainOfState(state) ?? derived);\n const filterBase = () =>\n v.string({ nullable: state.nullable, array: state.array, idDomain });\n const declaredBase = domainBaseOf(state, idDomain);\n const base =\n state.schema === undefined || idDomain !== undefined\n ? declaredBase\n : withScalarOutputDomain(declaredBase, filterBase());\n const refinedListUpdate = () =>\n listUpdateFamily(\n () =>\n idDomain === undefined\n ? withScalarOutputDomain(\n v.string({ schema: state.schema }),\n stringBase()\n )\n : v.string({ schema: state.schema, idDomain }),\n () =>\n idDomain === undefined\n ? withScalarOutputDomain(\n v.string({ array: true, schema: state.schema }),\n stringList()\n )\n : v.string({ array: true, schema: state.schema, idDomain })\n )(base);\n return internedScalarSchemas<StringSchemas<F, C>>(\n interners,\n scalarInternKey(state, idDomain),\n {\n base,\n create: () =>\n state.schema === undefined || idDomain !== undefined\n ? v.string(domainStateOf(state, idDomain))\n : withScalarOutputDomain(\n v.string(domainStateOf(state, idDomain)),\n filterBase()\n ),\n update: () =>\n state.array\n ? state.schema === undefined && idDomain === undefined\n ? buildStringListUpdateSchema(base)\n : refinedListUpdate()\n : buildSetUpdate(base),\n filter: () =>\n state.array\n ? idDomain === undefined\n ? buildStringListFilterSchema(filterBase())\n : listFilterFamily(\n () => v.string({ idDomain }),\n () => domainMembersOf(idDomain)\n )(filterBase())\n : idDomain !== undefined && isCompactIdFormat(idDomain.format)\n ? buildCompactIdFilterSchema(\n filterBase(),\n domainMembersOf(idDomain)\n )\n : buildStringFilterSchema(filterBase(), domainMembersOf(idDomain)),\n }\n );\n};\n","import type { ScalarState } from \"@schema/scalars/common\";\nimport v, { type V } from \"../primitives/v\";\nimport {\n type ComparisonFilterSchema,\n comparableScalar,\n type ListFilterSchema,\n type ListUpdateSchema,\n type SetUpdateSchema,\n} from \"./family\";\n\ntype IsoTimeList = V.IsoTime<{ array: true }>;\n\nexport interface TimeSchemas<\n F extends ScalarState<\"time\">,\n C extends V.Operand<any> = V.Operand<any>,\n> {\n base: F[\"base\"];\n create: V.IsoTime<F>;\n update: F[\"array\"] extends true\n ? ListUpdateSchema<F[\"base\"], V.IsoTime, IsoTimeList>\n : SetUpdateSchema<F[\"base\"]>;\n filter: F[\"array\"] extends true\n ? ListFilterSchema<F[\"base\"], V.IsoTime, IsoTimeList>\n : ComparisonFilterSchema<\"time\", F[\"base\"], V.IsoTime, IsoTimeList, C>;\n}\n\nexport const buildTimeSchema: <\n F extends ScalarState<\"time\">,\n C extends V.Operand<any> = V.Operand<any>,\n>(\n state: F\n) => TimeSchemas<F, C> = comparableScalar(\"time\", v.isoTime, false);\n","import type { ScalarState } from \"@schema/scalars/common\";\nimport { lazyScalarSchemas } from \"../lazy\";\nimport v, { type V } from \"../primitives/v\";\nimport { buildSetUpdate, type SetUpdateSchema } from \"./family\";\nimport {\n buildNegatableFilterSchema,\n type NegatableFilterSchema,\n} from \"./negatable-filter\";\n\n// =============================================================================\n// FILTER TYPES\n// =============================================================================\n\n// Similarity operators (l2/cosine) are deliberately absent: the query\n// engine rejects them, so the types must not offer them. The PG adapter\n// implementations stay reserved for a future opt-in.\ntype VectorFilterBase<S extends V.Schema> = {\n equals: S;\n};\n\ntype VectorFilterSchema<S extends V.Schema> = NegatableFilterSchema<\n S,\n VectorFilterBase<S>\n>;\n\n// =============================================================================\n// SCHEMA BUILDERS\n// =============================================================================\n\nconst buildVectorFilterSchema = <S extends V.Schema>(\n schema: S\n): VectorFilterSchema<S> => {\n const filter = v.object({\n equals: schema,\n });\n return buildNegatableFilterSchema<S, VectorFilterBase<S>>(filter, schema);\n};\n\n// =============================================================================\n// VECTOR SCHEMA BUILDER\n// =============================================================================\n\nexport interface VectorSchemas<F extends ScalarState<\"vector\">> {\n base: F[\"base\"];\n create: V.Vector<F>;\n update: SetUpdateSchema<F[\"base\"]>;\n filter: VectorFilterSchema<F[\"base\"]>;\n}\n\nexport const buildVectorSchema = <F extends ScalarState<\"vector\">>(\n state: F\n): VectorSchemas<F> => {\n return lazyScalarSchemas<VectorSchemas<F>>({\n base: state.base,\n create: () => v.vector(state.dimension, state),\n update: () => buildSetUpdate<F[\"base\"]>(state.base),\n filter: () => buildVectorFilterSchema<F[\"base\"]>(state.base),\n });\n};\n","/**\n * Scalar Schemas\n *\n * Validation schemas for create, update, and filter operations on all scalar types.\n */\n\nimport type { AnyModel } from \"@schema/model\";\nimport type { ScalarState } from \"@schema/scalars\";\nimport {\n currentTemporalValue,\n type TemporalKind,\n} from \"@schema/scalars/datetime/current\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { inferred } from \"@validation/inferred\";\nimport type { EnumValues } from \"@validation/primitives/enum\";\nimport { createSchema, validateSchema } from \"@validation/primitives/helpers\";\nimport type { IdDomain } from \"@validation/primitives/id-codec\";\nimport type { OperandCtx } from \"@validation/primitives/operand\";\nimport type { VibSchema } from \"@validation/types\";\nimport {\n lazyRecord,\n lazyScalarSchemas,\n type ScalarVariantSchemas,\n} from \"../lazy\";\nimport { type BigIntSchemas, buildBigIntSchema } from \"./bigint\";\nimport { type BlobSchemas, buildBlobSchema } from \"./blob\";\nimport { type BooleanSchemas, buildBooleanSchema } from \"./boolean\";\nimport { buildDateSchema, type DateSchemas } from \"./date\";\nimport { buildDateTimeSchema, type DateTimeSchemas } from \"./datetime\";\nimport { buildDecimalSchema, type DecimalSchemas } from \"./decimal\";\nimport { buildEnumSchema, type EnumSchemas } from \"./enum\";\nimport { buildIntSchema, type IntSchemas } from \"./int\";\nimport { buildJsonSchema, type JsonSchemas } from \"./json\";\nimport { buildNumberSchema, type NumberSchemas } from \"./number\";\nimport { buildPointSchema, type PointSchemas } from \"./point\";\nimport { buildStringSchema, type StringSchemas } from \"./string\";\nimport { buildTimeSchema, type TimeSchemas } from \"./time\";\nimport { buildVectorSchema, type VectorSchemas } from \"./vector\";\n\n// Re-export only the build functions and schema interfaces\nexport { type BigIntSchemas, buildBigIntSchema } from \"./bigint\";\nexport { type BlobSchemas, buildBlobSchema } from \"./blob\";\nexport { type BooleanSchemas, buildBooleanSchema } from \"./boolean\";\nexport { buildDateSchema, type DateSchemas } from \"./date\";\nexport { buildDateTimeSchema, type DateTimeSchemas } from \"./datetime\";\nexport {\n buildDecimalSchema,\n type DecimalSchemas,\n type DecimalUpdateOperationKeys,\n} from \"./decimal\";\nexport { buildEnumSchema, type EnumSchemas } from \"./enum\";\nexport { buildIntSchema, type IntSchemas } from \"./int\";\nexport { buildJsonSchema, type JsonSchemas } from \"./json\";\nexport { buildNumberSchema, type NumberSchemas } from \"./number\";\nexport { buildPointSchema, type PointSchemas } from \"./point\";\nexport { buildStringSchema, type StringSchemas } from \"./string\";\nexport { buildTimeSchema, type TimeSchemas } from \"./time\";\nexport { buildVectorSchema, type VectorSchemas } from \"./vector\";\n\n/**\n * `C` is the operand-callback context of the model these schemas belong to —\n * `{ fields, sql }` keyed to that model's scalars. It is threaded at the TYPE\n * level only: at runtime the filter schemas stay model-blind and interned\n * across models (see `intern.ts`), and a callback resolves its context from the\n * model scope the `where` schema pushes (see `primitives/operand.ts`). Types are\n * erased, so per-model operand types cost the runtime nothing.\n */\nexport type GetScalarSchemas<\n F extends ScalarState,\n C extends OperandCtx<any> = OperandCtx<any>,\n> = F extends ScalarState<\"bigint\">\n ? BigIntSchemas<F, C>\n : F extends ScalarState<\"blob\">\n ? BlobSchemas<F>\n : F extends ScalarState<\"boolean\">\n ? BooleanSchemas<F, C>\n : F extends ScalarState<\"datetime\">\n ? DateTimeSchemas<F, C>\n : F extends ScalarState<\"decimal\">\n ? DecimalSchemas<F, C>\n : F extends ScalarState<\"enum\">\n ? EnumSchemas<EnumValues<F[\"base\"]>, F, C>\n : F extends ScalarState<\"int\">\n ? IntSchemas<F, C>\n : F extends ScalarState<\"json\">\n ? JsonSchemas<F>\n : F extends ScalarState<\"number\">\n ? NumberSchemas<F, C>\n : F extends ScalarState<\"point\">\n ? PointSchemas<F>\n : F extends ScalarState<\"string\">\n ? StringSchemas<F, C>\n : F extends ScalarState<\"vector\">\n ? VectorSchemas<F>\n : F extends ScalarState<\"date\">\n ? DateSchemas<F, C>\n : F extends ScalarState<\"time\">\n ? TimeSchemas<F, C>\n : never;\n\n/**\n * `derived` is the identifier domain a FOREIGN-KEY member inherits from the key\n * it references. Only a string scalar can have one, and only when it declares\n * none of its own — an FK that declares a domain disagreeing with its target is\n * refused before any schema is built.\n */\nexport const getScalarSchemas = <F extends ScalarState>(\n scalar: F,\n derived?: IdDomain\n): GetScalarSchemas<F> =>\n (\n SCALAR_SCHEMA_BUILDERS[scalar.type] as (\n state: F,\n derived?: IdDomain\n ) => unknown\n )(scalar, derived) as GetScalarSchemas<F>;\n\n// A table rather than a switch: a schema with three scalar types compiles three\n// builders' call sites, not all fourteen.\nconst SCALAR_SCHEMA_BUILDERS: {\n readonly [K in ScalarState[\"type\"]]: (\n state: ScalarState<K>,\n derived?: IdDomain\n ) => unknown;\n} = {\n bigint: buildBigIntSchema,\n blob: buildBlobSchema,\n boolean: buildBooleanSchema,\n datetime: buildDateTimeSchema,\n decimal: buildDecimalSchema,\n enum: buildEnumSchema,\n int: buildIntSchema,\n json: buildJsonSchema,\n number: buildNumberSchema,\n point: buildPointSchema,\n string: buildStringSchema,\n vector: buildVectorSchema,\n date: buildDateSchema,\n time: buildTimeSchema,\n};\n\n/**\n * Get all scalars schemas for a given model\n */\nexport const getScalarsSchemas = <Source extends AnyModel>(\n source: Source,\n derived?: ReadonlyMap<string, IdDomain>\n) => {\n // Build each field's schemas lazily: a field's create/update/filter schemas\n // are only constructed when that field is first referenced (e.g. via\n // `v.fromObject(scalars, \"filter\")` reading `scalars[field].filter`). This\n // keeps `buildModelSchemas` — which runs on the first query per model per\n // isolate — from eagerly materializing every field's validators up front.\n const builders: Record<string, () => unknown> = {};\n const scalars = source[\"~\"].state.scalars;\n for (const scalar in scalars) {\n const state = scalars[scalar]![\"~\"].state;\n builders[scalar] = () => {\n const schemas = getScalarSchemas(state, derived?.get(scalar));\n if (state.autoGenerate?.kind === \"now\") return insertOnly(schemas);\n if (state.autoGenerate?.kind === \"updatedAt\" && !state.array)\n return updatesAt(schemas, state.type);\n return schemas;\n };\n }\n return lazyRecord(builders) as GetScalarsSchemas<Source>;\n};\n\n/**\n * A `.now()` creation timestamp is INSERT-ONLY: its record keeps `base`,\n * `create` and `filter`, and its `update` is `undefined`.\n *\n * The rule is read here, once per model field, from the field's EFFECTIVE\n * generator: `autoGenerate` is the declaration standing after every modifier,\n * so `.now().updatedAt()` stays updatable, `.updatedAt().now()` does not, and a\n * modifier that keeps the generator (`.nullable()`, `.map()`, `.default(v)`)\n * keeps the restriction. `.default(v)` alone declares no generator.\n *\n * Omission is the whole mechanism. `fromObject(scalars, \"update\")` builds no\n * entry for an `undefined` member, so the strict update object refuses the key\n * as `Unknown key` — beside a valid key, inside `{ set }`, and spelled\n * `undefined`, which a present entry would skip as absent — and the kind's\n * interned value validators are never consulted, so access order between two\n * fields with the same flags cannot hand one the other's permission.\n *\n * It restricts what the typed ORM assigns, not the column: raw SQL, other\n * writers and database cascades are not blocked.\n */\nconst insertOnly = <T extends object>(schemas: T): T =>\n Object.defineProperty(schemas, \"update\", {\n value: undefined,\n enumerable: true,\n });\n\ntype DefaultedUpdate<Input, Output> = VibSchema<Input | undefined, Output> & {\n readonly acceptsUndefined: true;\n};\n\n/**\n * Give one field's update schema its `.updatedAt()` omission default without\n * putting field-specific state into the kind-wide update interner.\n *\n * The wrapper is the admission lifetime: every missing field occurrence reads\n * the wall clock once, then passes that value through the same update schema as\n * an explicit value. The shorthand arm therefore validates and normalizes it\n * into `{ set: value }` exactly once. A caller-supplied value bypasses the\n * clock, and a replay of admitted data never reaches this wrapper again.\n */\nconst updatedAtUpdate = <S extends VibSchema>(\n update: S,\n kind: TemporalKind\n): DefaultedUpdate<\n StandardSchemaV1.InferInput<S>,\n StandardSchemaV1.InferOutput<S>\n> => {\n const metadata = {\n acceptsUndefined: true,\n wrapped: update,\n } satisfies {\n readonly acceptsUndefined: true;\n readonly wrapped: S;\n };\n return Object.assign(\n createSchema<\n StandardSchemaV1.InferInput<S> | undefined,\n StandardSchemaV1.InferOutput<S>\n >(\"optional\", (value) =>\n validateSchema(\n update,\n value === undefined ? currentTemporalValue(kind) : value\n )\n ),\n metadata\n );\n};\n\ntype UpdatedAtSchemas<Base, Create, Input, Output, Filter> = {\n readonly base: Base;\n readonly create: Create;\n readonly update: DefaultedUpdate<Input, Output>;\n readonly filter: Filter;\n};\n\ntype UpdatedAtSchemasOf<\n T extends ScalarVariantSchemas & { readonly update: VibSchema },\n> = UpdatedAtSchemas<\n T[\"base\"],\n T[\"create\"],\n StandardSchemaV1.InferInput<T[\"update\"]>,\n StandardSchemaV1.InferOutput<T[\"update\"]>,\n T[\"filter\"]\n>;\n\nconst updatesAt = <\n T extends ScalarVariantSchemas & { readonly update: VibSchema },\n>(\n schemas: T,\n kind: TemporalKind\n): UpdatedAtSchemasOf<T> =>\n lazyScalarSchemas<UpdatedAtSchemasOf<T>>({\n base: schemas.base,\n create: () => schemas.create,\n update: () => updatedAtUpdate(schemas.update, kind),\n filter: () => schemas.filter,\n });\n\n/**\n * The type half of {@link insertOnly}. Its `update` is `undefined`, which\n * `V.FromObject` turns into a `never` entry: the update input still NAMES the\n * key, as `?: never`, so a payload held in a variable is refused too — a key\n * that is merely absent refuses only a fresh literal.\n *\n * It is also the type half of {@link updatesAt}. That arm destructures the\n * record by `infer` and reads the update schema's input and output from its\n * `[inferred]` brand, the channel `InferInput`/`InferOutput` already read.\n * Asking instead whether the record `extends ScalarVariantSchemas & { update:\n * VibSchema }` relates every field's update schema to `VibSchema`\n * structurally, once per field per model and again inside every generic body\n * that reaches this alias: it raised the instrumentation layer's type program\n * from 0.91M to 1.38M types (4.9M to 7.6M instantiations) and out of its\n * 1280 MB shard heap. The record this arm yields is pinned in\n * `tests/types/operation-schemas/updated-at.core.types.ts`.\n */\ntype UpdateAdmission<Schemas, State> = State extends {\n readonly autoGenerate: { readonly kind: \"now\" };\n}\n ? Omit<Schemas, \"update\"> & { readonly update: undefined }\n : State extends { readonly array: true }\n ? Schemas\n : State extends {\n readonly autoGenerate: { readonly kind: \"updatedAt\" };\n }\n ? Schemas extends {\n readonly base: infer Base;\n readonly create: infer Create;\n readonly update: { readonly [inferred]: [infer Input, infer Output] };\n readonly filter: infer Filter;\n }\n ? UpdatedAtSchemas<Base, Create, Input, Output, Filter>\n : Schemas\n : Schemas;\n\nexport type GetScalarsSchemas<Source extends AnyModel> = {\n [F in keyof Source[\"~\"][\"state\"][\"scalars\"]]: UpdateAdmission<\n GetScalarSchemas<\n Source[\"~\"][\"state\"][\"scalars\"][F][\"~\"][\"state\"],\n OperandCtx<Source>\n >,\n Source[\"~\"][\"state\"][\"scalars\"][F][\"~\"][\"state\"]\n >;\n};\n","/**\n * Centralized Schema Builder\n *\n * Builds all validation schemas (scalars, relations, models) from a central registry.\n * Uses lazy evaluation (thunks) to handle circular dependencies between models.\n *\n * Key insight: Using Model object as Map key allows direct lookup via the\n * relation's settled target (RelationInternal.settleTarget)\n */\n\nimport { ValidationError } from \"@errors\";\nimport { hydrateSchemaNames } from \"@schema/hydration\";\nimport type { AnyModel, Model } from \"@schema/model\";\nimport type { AnyRelation } from \"@schema/relation\";\nimport type { RelationState } from \"@schema/relation/types\";\nimport { resolveSchemaOrThrow } from \"@schema/validation\";\nimport { idDomainsOf } from \"@schema/validation/id-domains\";\nimport type {\n ResolvedRelationIndex,\n ResolvedSlot,\n} from \"@schema/validation/relation-resolution\";\nimport { getModelSchemas, type ModelSchemas } from \"./model\";\nimport { validateSchema } from \"./primitives/helpers\";\nimport { getRelationsSchemas } from \"./relations\";\nimport type { GetTargetSchemas } from \"./relations/helpers\";\nimport { getPolymorphicRelationsSchemas } from \"./relations/polymorphic\";\nimport { getScalarsSchemas } from \"./scalars\";\nimport type { SchemaRegistryLookup, SchemaRegistryOperation } from \"./types\";\nimport { isString } from \"./value-guards\";\n\n// =============================================================================\n// SCHEMA REGISTRY\n// =============================================================================\n\nclass SchemaRegistry<S extends Record<string, AnyModel>>\n implements SchemaRegistryLookup<S>\n{\n readonly #cache = new Map<AnyModel, ModelSchemas<AnyModel>>();\n readonly #schema: S;\n /**\n * The one trusted topology, by identity. The operation schemas this registry\n * builds decide which mutation verbs a caller may spell and which keys a\n * nested payload owns — both are topology answers, so the registry consumes\n * the resolved index rather than re-deriving anything from declarations.\n */\n readonly #index: ResolvedRelationIndex;\n readonly proxy: {\n [K in keyof S]: ModelSchemas<S[K]>;\n };\n\n constructor(schema: S, index: ResolvedRelationIndex) {\n this.#schema = schema;\n this.#index = index;\n\n this.proxy = new Proxy(\n {},\n {\n get: (_target, prop) => {\n if (\n !(isString(prop) && Object.hasOwn(schema, prop) && schema[prop])\n ) {\n const property = String(prop);\n throw new ValidationError({ kind: \"registry\", property }, [\n { path: property, message: `${property} does not exist` },\n ]);\n }\n return this.getModelSchemas(schema[prop]);\n },\n }\n ) as {\n [K in keyof S]: ModelSchemas<S[K]>;\n };\n }\n\n readonly #createSchemasGetter = <S extends RelationState>(\n relation: AnyRelation\n ) => {\n return () => {\n // `settleTarget` is the one sanctioned getter invocation (§11.1.16b).\n const targetModel = relation[\"~\"].settleTarget() as AnyModel;\n return this.getModelSchemas(\n targetModel\n ) as unknown as GetTargetSchemas<S>;\n };\n };\n\n readonly #buildModelSchemas = (\n model: AnyModel\n ): ModelSchemas<AnyModel> => {\n // The identifier domains a foreign-key member DERIVES, from the same\n // resolved index the registry already threads. A field that declares its\n // own reads it from the declaration; this is only the inheritance.\n const scalars = getScalarsSchemas(\n model,\n idDomainsOf(this.#index).get(model)\n );\n // `createResolvedSchemaRegistry` accepts the index resolved for this exact\n // schema. Every registered model therefore has one slot map, including an\n // empty map for a model with no relations.\n const slots: ReadonlyMap<string, ResolvedSlot> = this.#index.get(model)!;\n const relations = getRelationsSchemas(\n model,\n this.#createSchemasGetter,\n slots\n );\n const polymorphic = getPolymorphicRelationsSchemas(\n model,\n this.getModelSchemas\n );\n const { args, core } = getModelSchemas(\n model,\n { scalars, relations, polymorphic },\n slots\n );\n return {\n scalars,\n relations,\n polymorphic,\n args,\n core,\n } as unknown as ModelSchemas<AnyModel>;\n };\n\n getModelSchemas = (model: AnyModel): ModelSchemas<AnyModel> => {\n let schemas = this.#cache.get(model);\n if (!schemas) {\n schemas = this.#buildModelSchemas(model);\n this.#cache.set(model, schemas);\n }\n return schemas as ModelSchemas<AnyModel>;\n };\n\n validate = (\n modelName: string,\n operation: SchemaRegistryOperation,\n payload: unknown\n ): Record<string, unknown> => {\n const model = Object.hasOwn(this.#schema, modelName)\n ? this.#schema[modelName]\n : undefined;\n if (!model) {\n const modelLabel = String(modelName);\n throw new ValidationError(\n { kind: \"operation\", operation, model: modelLabel },\n [{ path: modelLabel, message: `${modelLabel} does not exist` }],\n { meta: { model: modelLabel } }\n );\n }\n const schemas = this.getModelSchemas(model);\n if (!Object.hasOwn(schemas.args, operation)) {\n throw new ValidationError(\n { kind: \"registry\", model: modelName, property: String(operation) },\n [\n {\n path: \"operation\",\n message: `${String(operation)} does not exist`,\n },\n ]\n );\n }\n try {\n const result = validateSchema(schemas.args[operation], payload);\n if (result.issues) {\n const issues = result.issues.map((issue) => ({\n path: issue.path?.map((part) => part).join(\".\") ?? \"\",\n message: issue.message,\n }));\n throw new ValidationError(operation, issues, {\n meta: { model: modelName },\n });\n }\n return result.value ?? {};\n } catch (cause) {\n if (cause instanceof ValidationError) throw cause;\n throw new ValidationError(\n { kind: \"operation\", operation, model: modelName },\n [\n {\n path: \"\",\n message: \"The external schema validator threw unexpectedly\",\n },\n ],\n {\n ...(cause instanceof Error ? { cause } : {}),\n meta: { model: modelName },\n }\n );\n }\n };\n}\n\n/**\n * Compose a registry over an ALREADY RESOLVED schema.\n *\n * The index is a parameter, not a side effect: client construction resolves\n * once and shares that exact instance with the registry, the omit rewriting and\n * the query engine (§11.4.10). A standalone registry has no such owner, so it\n * resolves once for its own lifecycle — which is also the mandatory definition\n * gate for this boundary (§7.3): operation schemas may not be built over a\n * schema whose topology was never proven.\n */\nexport const createResolvedSchemaRegistry = <\n S extends Record<string, Model<any>>,\n>(\n schema: S,\n index: ResolvedRelationIndex\n): SchemaRegistryLookup<S> => {\n return new SchemaRegistry(schema, index);\n};\n\n/** Public standalone boundary: prepare and resolve its own schema. */\nexport const createSchemaRegistry = <S extends Record<string, Model<any>>>(\n schema: S\n): SchemaRegistryLookup<S> => {\n hydrateSchemaNames(schema);\n return createResolvedSchemaRegistry(schema, resolveSchemaOrThrow(schema));\n};\n"],"mappings":"8rBAgDA,MAAa,eAAkB,GAAoC,CACjE,IAAM,EAAO,EAAS,KAStB,OARI,EAAK,OAAS,YAAc,EAAK,OAAS,yBACrC,GAEL,EAAK,OAAS,oBACT,OAAO,EAAK,QAAS,EAAS,KAAK,CACtC,EAAK,QAAQ,WAAW,SACxB,GAEC,OAAO,EAAK,MAAO,E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