viborm 1.14.2 → 1.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapter-namespace-DwFnfpED.mjs +2 -0
- package/dist/{adapter-namespace-DaRiTIIf.mjs.map → adapter-namespace-DwFnfpED.mjs.map} +1 -1
- package/dist/adapters.d.mts +26 -10
- package/dist/adapters.mjs +1 -1
- package/dist/args-7WgBFd_f.mjs +2 -0
- package/dist/{args-764KdWMr.mjs.map → args-7WgBFd_f.mjs.map} +1 -1
- package/dist/array-literal-BOzj0E2u.mjs +2 -0
- package/dist/{array-literal-DHinAnVs.mjs.map → array-literal-BOzj0E2u.mjs.map} +1 -1
- package/dist/base-17NSFtrA.mjs +2 -0
- package/dist/base-17NSFtrA.mjs.map +1 -0
- package/dist/batch-refs-Bd8HvwUc.mjs +2 -0
- package/dist/{batch-refs-C-gx7A4-.mjs.map → batch-refs-Bd8HvwUc.mjs.map} +1 -1
- package/dist/better-auth.d.mts +116 -0
- package/dist/better-auth.mjs +6 -0
- package/dist/better-auth.mjs.map +1 -0
- package/dist/bind-parameter-capacity-BAFQM9Jt.mjs +2 -0
- package/dist/{bind-parameter-capacity-BMD-bxMO.mjs.map → bind-parameter-capacity-BAFQM9Jt.mjs.map} +1 -1
- package/dist/bun-sql.d.mts +1 -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/bun-sqlite.mjs.map +1 -1
- package/dist/cache/cloudflare-kv.d.mts +1 -1
- package/dist/cache/cloudflare-kv.mjs +1 -1
- package/dist/cache/cloudflare-kv.mjs.map +1 -1
- package/dist/cache/memory.d.mts +1 -1
- package/dist/cache/memory.mjs +1 -1
- package/dist/cache/memory.mjs.map +1 -1
- package/dist/cache.d.mts +2 -2
- package/dist/cache.mjs +1 -1
- package/dist/cache.mjs.map +1 -1
- package/dist/call-0bd_B9Vp.mjs +2 -0
- package/dist/{call-Cz8XUmrl.mjs.map → call-0bd_B9Vp.mjs.map} +1 -1
- package/dist/cli.mjs +6 -6
- package/dist/cli.mjs.map +1 -1
- package/dist/client-D7sWgUt2.mjs +2 -0
- package/dist/client-D7sWgUt2.mjs.map +1 -0
- package/dist/client-DEfFqv4S.mjs +9 -0
- package/dist/client-DEfFqv4S.mjs.map +1 -0
- package/dist/{client-CRxfhw2y.d.mts → client-Dlz3-2JC.d.mts} +3 -3
- package/dist/client.d.mts +3 -3
- package/dist/client.mjs +1 -1
- package/dist/client.mjs.map +1 -1
- package/dist/config.d.mts +2 -2
- package/dist/config.mjs +1 -1
- package/dist/confine-CyI9IwjC.mjs +2 -0
- package/dist/{confine-DqFBTUw6.mjs.map → confine-CyI9IwjC.mjs.map} +1 -1
- package/dist/coordination-BxMskOgi.mjs +2 -0
- package/dist/coordination-BxMskOgi.mjs.map +1 -0
- package/dist/d1.d.mts +2 -30
- package/dist/d1.mjs +1 -1
- package/dist/d1.mjs.map +1 -1
- package/dist/{database-adapter-BGqvjeEy.d.mts → database-adapter-BMjJiBFm.d.mts} +8476 -8386
- package/dist/datetime-physical-codec-DAF7WJpy.mjs +2 -0
- package/dist/datetime-physical-codec-DAF7WJpy.mjs.map +1 -0
- package/dist/defaults-DAPb-tJ4.mjs +2 -0
- package/dist/{defaults-DwOHWI_M.mjs.map → defaults-DAPb-tJ4.mjs.map} +1 -1
- package/dist/{document-BVTQ-cF-.d.mts → document-CHaVF7Vn.d.mts} +36 -2
- package/dist/{driver-BBEmaJZy.d.mts → driver-BvTixv-m.d.mts} +1 -1
- package/dist/driver-diagnostics-aQ54bArn.mjs +2 -0
- package/dist/{driver-diagnostics-DW9NdckJ.mjs.map → driver-diagnostics-aQ54bArn.mjs.map} +1 -1
- package/dist/driver-kiIQS_Fd.mjs +2 -0
- package/dist/driver-kiIQS_Fd.mjs.map +1 -0
- package/dist/driver-lShUkDmf.mjs +2 -0
- package/dist/driver-lShUkDmf.mjs.map +1 -0
- package/dist/driver.d.mts +1 -1
- package/dist/driver.mjs +1 -1
- package/dist/durable-object.d.mts +1 -1
- package/dist/durable-object.mjs +2 -2
- package/dist/durable-object.mjs.map +1 -1
- package/dist/error-mapping-B9rSvgG9.mjs +2 -0
- package/dist/error-mapping-B9rSvgG9.mjs.map +1 -0
- package/dist/every-JpbiHdMb.mjs +2 -0
- package/dist/{every-tOgQmaIE.mjs.map → every-JpbiHdMb.mjs.map} +1 -1
- package/dist/execution-context-couU2tgh.mjs +2 -0
- package/dist/execution-context-couU2tgh.mjs.map +1 -0
- package/dist/{exports-COCJ8f2f.d.mts → exports-DYnTfvQo.d.mts} +1 -1
- package/dist/extension-Dh1ddrlA.mjs +2 -0
- package/dist/{extension-CGepsF-p.mjs.map → extension-Dh1ddrlA.mjs.map} +1 -1
- package/dist/fs-estate-n-QpsFqb.mjs +2 -0
- package/dist/{fs-estate-D1Nsg9G1.mjs.map → fs-estate-n-QpsFqb.mjs.map} +1 -1
- package/dist/geo-area-codec-Bti2PA2i.mjs +2 -0
- package/dist/geo-area-codec-Bti2PA2i.mjs.map +1 -0
- package/dist/id-domain-Cg65TLZ-.mjs +2 -0
- package/dist/id-domain-Cg65TLZ-.mjs.map +1 -0
- package/dist/identifier-conversion-BTDxDwDB.mjs +2 -0
- package/dist/identifier-conversion-BTDxDwDB.mjs.map +1 -0
- package/dist/identifiers-BxOf57qy.mjs +2 -0
- package/dist/identifiers-BxOf57qy.mjs.map +1 -0
- package/dist/identity-CJlRQA-m.mjs +2 -0
- package/dist/identity-CJlRQA-m.mjs.map +1 -0
- 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/instrumentation.mjs.map +1 -1
- package/dist/introspect-q3Rf_Xv8.mjs +2 -0
- package/dist/introspect-q3Rf_Xv8.mjs.map +1 -0
- package/dist/json-CsAdz9pg.mjs +2 -0
- package/dist/json-CsAdz9pg.mjs.map +1 -0
- package/dist/json-number-C09rsm1g.mjs +2 -0
- package/dist/{json-number-AI-SdUUn.mjs.map → json-number-C09rsm1g.mjs.map} +1 -1
- package/dist/json-parameter-D7hDrVKw.mjs +2 -0
- package/dist/{json-parameter-oQ8nGaKr.mjs.map → json-parameter-D7hDrVKw.mjs.map} +1 -1
- package/dist/judge-words-k5GCc4cV.mjs +2 -0
- package/dist/judge-words-k5GCc4cV.mjs.map +1 -0
- package/dist/key-BDH6oTyC.mjs +2 -0
- package/dist/key-BDH6oTyC.mjs.map +1 -0
- package/dist/keys-CIal55WQ.mjs +2 -0
- package/dist/{keys-BQxM4c_a.mjs.map → keys-CIal55WQ.mjs.map} +1 -1
- package/dist/keys-DZdKAd4n.mjs +2 -0
- package/dist/keys-DZdKAd4n.mjs.map +1 -0
- package/dist/libsql-DEZ0uhK2.mjs +3 -0
- package/dist/libsql-DEZ0uhK2.mjs.map +1 -0
- package/dist/libsql.d.mts +2 -20
- package/dist/libsql.mjs +1 -1
- package/dist/libsql.mjs.map +1 -1
- package/dist/light-D2wNSbzY.mjs +2 -0
- package/dist/{light-BkJe3-yW.mjs.map → light-D2wNSbzY.mjs.map} +1 -1
- package/dist/memory-BaGWNdvk.mjs +2 -0
- package/dist/{memory-G4cSuc6A.mjs.map → memory-BaGWNdvk.mjs.map} +1 -1
- package/dist/methods-part-BaNx3o7b.mjs +2 -0
- package/dist/methods-part-BaNx3o7b.mjs.map +1 -0
- 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/snowflake.d.mts +5 -5
- package/dist/migrations/snowflake.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/durable-object.mjs.map +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/storage/r2.mjs.map +1 -1
- package/dist/migrations/surrealdb.d.mts +5 -5
- package/dist/migrations/surrealdb.mjs +1 -1
- package/dist/migrations/tenant.d.mts +3 -3
- package/dist/migrations/tenant.mjs +1 -1
- package/dist/migrations/tenant.mjs.map +1 -1
- package/dist/migrations-DIUltjr3.mjs +2 -0
- package/dist/{migrations-BMiRjR-N.mjs.map → migrations-DIUltjr3.mjs.map} +1 -1
- package/dist/migrations.d.mts +5 -5
- package/dist/migrations.mjs +1 -1
- package/dist/model-Dtd37Sky.mjs +2 -0
- package/dist/model-Dtd37Sky.mjs.map +1 -0
- package/dist/mysql-BFPF8xyv.mjs +9 -0
- package/dist/mysql-BFPF8xyv.mjs.map +1 -0
- package/dist/mysql-adapter-BFWYPoM0.mjs +2 -0
- package/dist/mysql-adapter-BFWYPoM0.mjs.map +1 -0
- package/dist/mysql2.d.mts +2 -27
- package/dist/mysql2.mjs +1 -1
- package/dist/mysql2.mjs.map +1 -1
- package/dist/named-statements-CkOOD__I.mjs +2 -0
- package/dist/named-statements-CkOOD__I.mjs.map +1 -0
- package/dist/named-statements-NF7Iycjk.d.mts +13 -0
- package/dist/native-types-1ewJXVks.mjs +2 -0
- package/dist/native-types-1ewJXVks.mjs.map +1 -0
- package/dist/neon-http.d.mts +1 -1
- package/dist/neon-http.mjs +1 -1
- package/dist/neon-http.mjs.map +1 -1
- package/dist/normalized-result-D7nVkF36.mjs +2 -0
- package/dist/normalized-result-D7nVkF36.mjs.map +1 -0
- package/dist/{object-store-B_YMoW8u.d.mts → object-store-C4qmW7xf.d.mts} +4 -4
- package/dist/object-store-Chq1PMYz.mjs +2 -0
- package/dist/object-store-Chq1PMYz.mjs.map +1 -0
- package/dist/on-ZkOVmE4-.mjs +2 -0
- package/dist/{on-ylYaKuRu.mjs.map → on-ZkOVmE4-.mjs.map} +1 -1
- package/dist/on.d.mts +1 -1
- package/dist/on.mjs +1 -1
- package/dist/on.mjs.map +1 -1
- package/dist/ordering/keys.mjs +1 -1
- package/dist/ordering.d.mts +9 -3
- package/dist/ordering.mjs +10 -10
- package/dist/ordering.mjs.map +1 -1
- package/dist/pending-operation-D4gUKMxD.mjs +2 -0
- package/dist/pending-operation-D4gUKMxD.mjs.map +1 -0
- package/dist/permissions.d.mts +1 -1
- package/dist/permissions.mjs +1 -1
- package/dist/permissions.mjs.map +1 -1
- package/dist/pg.d.mts +16 -99
- 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-DO4PEYcc.mjs +2 -0
- package/dist/physical-DO4PEYcc.mjs.map +1 -0
- package/dist/pinned-session-Y7-2pRBJ.mjs +2 -0
- package/dist/pinned-session-Y7-2pRBJ.mjs.map +1 -0
- package/dist/planetscale.d.mts +1 -1
- package/dist/planetscale.mjs +1 -1
- package/dist/planetscale.mjs.map +1 -1
- package/dist/{planner-DHjdvjwk.d.mts → planner-C-zjj19U.d.mts} +123 -1
- package/dist/postgres-DQQE2ys_.mjs +34 -0
- package/dist/postgres-DQQE2ys_.mjs.map +1 -0
- package/dist/postgres-adapter-BpLizOaK.mjs +2 -0
- package/dist/{postgres-adapter-axapXX8d.mjs.map → postgres-adapter-BpLizOaK.mjs.map} +1 -1
- package/dist/postgres-adapter-psTVfuw7.mjs +2 -0
- package/dist/postgres-adapter-psTVfuw7.mjs.map +1 -0
- package/dist/postgres-result-133boRW-.mjs +2 -0
- package/dist/postgres-result-133boRW-.mjs.map +1 -0
- package/dist/postgres.d.mts +27 -59
- package/dist/postgres.mjs +1 -1
- package/dist/postgres.mjs.map +1 -1
- package/dist/provider-limits-Bcsz0EJv.mjs +2 -0
- package/dist/provider-limits-Bcsz0EJv.mjs.map +1 -0
- package/dist/provider-parameter-snapshot-cyTUDutH.mjs +2 -0
- package/dist/provider-parameter-snapshot-cyTUDutH.mjs.map +1 -0
- package/dist/quantized-BKBs0joq.mjs +2 -0
- package/dist/quantized-BKBs0joq.mjs.map +1 -0
- package/dist/query-BTb6iakn.mjs +2 -0
- package/dist/query-BTb6iakn.mjs.map +1 -0
- package/dist/query-backend-TisPjCPF.mjs +2 -0
- package/dist/query-backend-TisPjCPF.mjs.map +1 -0
- package/dist/query-inspection-DwYBKSDG.mjs +2 -0
- package/dist/query-inspection-DwYBKSDG.mjs.map +1 -0
- package/dist/raw-DqEb71JZ.mjs +2 -0
- package/dist/raw-DqEb71JZ.mjs.map +1 -0
- package/dist/relation-bound-CSNKLyDy.mjs +2 -0
- package/dist/{relation-bound-ku_cMdye.mjs.map → relation-bound-CSNKLyDy.mjs.map} +1 -1
- package/dist/result-parsing-BbffueEX.mjs +2 -0
- package/dist/{result-parsing-B0Y4KGDT.mjs.map → result-parsing-BbffueEX.mjs.map} +1 -1
- package/dist/routed-operations-CcKOdn51.mjs +2 -0
- package/dist/{routed-operations-wytpbYKv.mjs.map → routed-operations-CcKOdn51.mjs.map} +1 -1
- package/dist/rows-of-Bgl9GVtK.mjs +2 -0
- package/dist/rows-of-Bgl9GVtK.mjs.map +1 -0
- package/dist/rule-words-DMbQuvD2.mjs +2 -0
- package/dist/{rule-words-ZIGm7cDm.mjs.map → rule-words-DMbQuvD2.mjs.map} +1 -1
- package/dist/scalar-Dm9brvAU.mjs +4 -0
- package/dist/scalar-Dm9brvAU.mjs.map +1 -0
- package/dist/schema/introspect.d.mts +2 -2
- package/dist/schema/introspect.mjs +1 -1
- package/dist/schema/json.d.mts +6 -4
- package/dist/schema/json.mjs +1 -1
- package/dist/schema-DDkAUfOb.mjs +2 -0
- package/dist/schema-DDkAUfOb.mjs.map +1 -0
- package/dist/schema-DqR_Kcje.mjs +2 -0
- package/dist/schema-DqR_Kcje.mjs.map +1 -0
- package/dist/schema-introspection-Bbo4DN_d.mjs +4 -0
- package/dist/schema-introspection-Bbo4DN_d.mjs.map +1 -0
- package/dist/schema.d.mts +2 -2
- package/dist/schema.mjs +1 -1
- package/dist/select-assembly-CEpNu-Gw.mjs +2 -0
- package/dist/select-assembly-CEpNu-Gw.mjs.map +1 -0
- package/dist/serializer-ettLu5xG.mjs +33 -0
- package/dist/serializer-ettLu5xG.mjs.map +1 -0
- package/dist/settle-Pui-1tfJ.mjs +2 -0
- package/dist/{settle-1cy5x_52.mjs.map → settle-Pui-1tfJ.mjs.map} +1 -1
- package/dist/settled-DYYPcaBX.mjs +2 -0
- package/dist/{settled-BjyuA76m.mjs.map → settled-DYYPcaBX.mjs.map} +1 -1
- package/dist/snowflake-BfF8xwfP.mjs +2 -0
- package/dist/{snowflake-UOCC820W.mjs.map → snowflake-BfF8xwfP.mjs.map} +1 -1
- package/dist/snowflake.d.mts +3 -3
- package/dist/snowflake.mjs +2 -2
- package/dist/snowflake.mjs.map +1 -1
- package/dist/soft-delete.d.mts +9 -3
- package/dist/soft-delete.mjs +1 -1
- package/dist/soft-delete.mjs.map +1 -1
- package/dist/{spans-XDUFeTzC.mjs → spans-DwDXMvyd.mjs} +1 -1
- package/dist/{spans-XDUFeTzC.mjs.map → spans-DwDXMvyd.mjs.map} +1 -1
- package/dist/sql-Bu63iAfT.mjs +2 -0
- package/dist/sql-Bu63iAfT.mjs.map +1 -0
- package/dist/{sql-BVZ8QefY.d.mts → sql-C4_sFNDm.d.mts} +18 -5
- package/dist/sql-statement-tokens-Z5Ta4iDB.mjs +3 -0
- package/dist/{sql-statement-tokens-DbeMwHra.mjs.map → sql-statement-tokens-Z5Ta4iDB.mjs.map} +1 -1
- package/dist/sql-tegqTqGq.mjs +2 -0
- package/dist/sql-tegqTqGq.mjs.map +1 -0
- package/dist/sql.d.mts +1 -1
- package/dist/sql.mjs +1 -1
- package/dist/sqlite-adapter-Cb-SJw2f.mjs +2 -0
- package/dist/sqlite-adapter-Cb-SJw2f.mjs.map +1 -0
- package/dist/sqlite-statement-classifier-JBHiQO6Q.mjs +2 -0
- package/dist/{sqlite-statement-classifier-BAHl-WXS.mjs.map → sqlite-statement-classifier-JBHiQO6Q.mjs.map} +1 -1
- package/dist/sqlite-utils-Bfmtkt1b.mjs +2 -0
- package/dist/sqlite-utils-Bfmtkt1b.mjs.map +1 -0
- package/dist/sqlite3.d.mts +2 -46
- package/dist/sqlite3.mjs +1 -1
- package/dist/sqlite3.mjs.map +1 -1
- package/dist/standard-sql-Bl2OHGfi.mjs +6 -0
- package/dist/standard-sql-Bl2OHGfi.mjs.map +1 -0
- package/dist/suppressed-failure-CFUDJrUw.mjs +2 -0
- package/dist/{suppressed-failure-CQkQsMVS.mjs.map → suppressed-failure-CFUDJrUw.mjs.map} +1 -1
- package/dist/surrealdb.d.mts +2 -2
- package/dist/surrealdb.mjs +1 -1
- package/dist/surrealdb.mjs.map +1 -1
- package/dist/surrealql-DY74AUeD.mjs +2 -0
- package/dist/surrealql-DY74AUeD.mjs.map +1 -0
- package/dist/time-step-DJaIhpAz.mjs +2 -0
- package/dist/time-step-DJaIhpAz.mjs.map +1 -0
- package/dist/transaction-Bv5nyp-U.mjs +2 -0
- package/dist/{transaction-BNomMtme.mjs.map → transaction-Bv5nyp-U.mjs.map} +1 -1
- package/dist/transaction-operation-CaWzo7gE.mjs +2 -0
- package/dist/{transaction-operation-CVVJxQ19.mjs.map → transaction-operation-CaWzo7gE.mjs.map} +1 -1
- package/dist/types-Dy33vBdd.mjs +2 -0
- package/dist/{types-DtDnXhwa.mjs.map → types-Dy33vBdd.mjs.map} +1 -1
- package/dist/unit-DUPX5Sdd.mjs +2 -0
- package/dist/{unit-BhHbZyuJ.mjs.map → unit-DUPX5Sdd.mjs.map} +1 -1
- package/dist/unit-words-BXpLpyr2.mjs +2 -0
- package/dist/{unit-words-CT0yeqfZ.mjs.map → unit-words-BXpLpyr2.mjs.map} +1 -1
- package/dist/utils-BHkJsduV.mjs +26 -0
- package/dist/{utils-CpAojrCj.mjs.map → utils-BHkJsduV.mjs.map} +1 -1
- package/dist/v1-parse-shared-cJ-uD14P.mjs +2 -0
- package/dist/v1-parse-shared-cJ-uD14P.mjs.map +1 -0
- package/dist/validation-ATmgN5RE.mjs +2 -0
- package/dist/validation-ATmgN5RE.mjs.map +1 -0
- package/dist/validation-BHjx13zG.mjs +2 -0
- package/dist/validation-BHjx13zG.mjs.map +1 -0
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -1
- package/dist/validator-DMzH5Tz0.mjs +2 -0
- package/dist/validator-DMzH5Tz0.mjs.map +1 -0
- package/dist/value-guards-CBVIJXlI.mjs +2 -0
- package/dist/{value-guards-CBuxSC66.mjs.map → value-guards-CBVIJXlI.mjs.map} +1 -1
- package/dist/values-Ch2cTlss.mjs +2 -0
- package/dist/{values-B4aj1i1f.mjs.map → values-Ch2cTlss.mjs.map} +1 -1
- package/dist/version-0BDwfy7C.mjs +2 -0
- package/dist/{version-CXGIA82S.mjs.map → version-0BDwfy7C.mjs.map} +1 -1
- package/dist/view-CHgjF2BO.mjs +2 -0
- package/dist/view-CHgjF2BO.mjs.map +1 -0
- package/dist/write-sinks-Bei5vFHP.mjs +2 -0
- package/dist/{write-sinks-3IKCDF-S.mjs.map → write-sinks-Bei5vFHP.mjs.map} +1 -1
- package/package.json +50 -37
- package/dist/adapter-internals-DOqI8IlQ.mjs +0 -2
- package/dist/adapter-internals-DOqI8IlQ.mjs.map +0 -1
- package/dist/adapter-namespace-DaRiTIIf.mjs +0 -2
- package/dist/adapter-result-parser-3WP82Cm-.mjs +0 -2
- package/dist/adapter-result-parser-3WP82Cm-.mjs.map +0 -1
- package/dist/args-764KdWMr.mjs +0 -2
- package/dist/array-literal-DHinAnVs.mjs +0 -2
- package/dist/base-z-cH5ZBI.mjs +0 -2
- package/dist/base-z-cH5ZBI.mjs.map +0 -1
- package/dist/batch-refs-C-gx7A4-.mjs +0 -2
- package/dist/bind-parameter-capacity-BMD-bxMO.mjs +0 -2
- package/dist/call-Cz8XUmrl.mjs +0 -2
- package/dist/canonical-json-Bl-fKFF_.mjs +0 -2
- package/dist/canonical-json-Bl-fKFF_.mjs.map +0 -1
- package/dist/chunk-BuuaeEvq.mjs +0 -1
- package/dist/client-DRpX3-vw.mjs +0 -2
- package/dist/client-DRpX3-vw.mjs.map +0 -1
- package/dist/client-y7TV0PRZ.mjs +0 -9
- package/dist/client-y7TV0PRZ.mjs.map +0 -1
- package/dist/confine-DqFBTUw6.mjs +0 -2
- package/dist/coordination-6qZHx_kl.mjs +0 -2
- package/dist/coordination-6qZHx_kl.mjs.map +0 -1
- package/dist/current-DBTlPsQg.mjs +0 -2
- package/dist/current-DBTlPsQg.mjs.map +0 -1
- package/dist/datetime-physical-codec-Dj-APo9f.mjs +0 -2
- package/dist/datetime-physical-codec-Dj-APo9f.mjs.map +0 -1
- package/dist/defaults-DwOHWI_M.mjs +0 -2
- package/dist/driver-BGVcgnIX.mjs +0 -2
- package/dist/driver-BGVcgnIX.mjs.map +0 -1
- package/dist/driver-BIXhOH2_.mjs +0 -2
- package/dist/driver-BIXhOH2_.mjs.map +0 -1
- package/dist/driver-diagnostics-DW9NdckJ.mjs +0 -2
- package/dist/error-mapping-B1-IWkCQ.mjs +0 -2
- package/dist/error-mapping-B1-IWkCQ.mjs.map +0 -1
- package/dist/every-tOgQmaIE.mjs +0 -2
- package/dist/execution-context-BXpcbyPe.mjs +0 -2
- package/dist/execution-context-BXpcbyPe.mjs.map +0 -1
- package/dist/extension-CGepsF-p.mjs +0 -2
- package/dist/fs-estate-D1Nsg9G1.mjs +0 -2
- package/dist/geo-area-codec-mHrM3b9A.mjs +0 -2
- package/dist/geo-area-codec-mHrM3b9A.mjs.map +0 -1
- package/dist/hydration-A3zffFWP.mjs +0 -2
- package/dist/hydration-A3zffFWP.mjs.map +0 -1
- package/dist/identifier-conversion-DHYPTgzr.mjs +0 -2
- package/dist/identifier-conversion-DHYPTgzr.mjs.map +0 -1
- package/dist/identifiers-s00pGES8.mjs +0 -2
- package/dist/identifiers-s00pGES8.mjs.map +0 -1
- package/dist/identity-CtW15WlB.mjs +0 -2
- package/dist/identity-CtW15WlB.mjs.map +0 -1
- package/dist/introspect-Bm6xnXcG.mjs +0 -2
- package/dist/introspect-Bm6xnXcG.mjs.map +0 -1
- package/dist/json-DgMc8-GU.mjs +0 -2
- package/dist/json-DgMc8-GU.mjs.map +0 -1
- package/dist/json-number-AI-SdUUn.mjs +0 -2
- package/dist/json-parameter-oQ8nGaKr.mjs +0 -2
- package/dist/judge-words-CzUyXtJ6.mjs +0 -2
- package/dist/judge-words-CzUyXtJ6.mjs.map +0 -1
- package/dist/key-hxFFCKed.mjs +0 -2
- package/dist/key-hxFFCKed.mjs.map +0 -1
- package/dist/keys-BQxM4c_a.mjs +0 -2
- package/dist/libsql-DuGR904j.mjs +0 -3
- package/dist/libsql-DuGR904j.mjs.map +0 -1
- package/dist/light-BkJe3-yW.mjs +0 -2
- package/dist/memory-G4cSuc6A.mjs +0 -2
- package/dist/methods-part-ZY0f2AV_.mjs +0 -2
- package/dist/methods-part-ZY0f2AV_.mjs.map +0 -1
- package/dist/migrations-BMiRjR-N.mjs +0 -2
- package/dist/mysql-BNXWfTOo.mjs +0 -100
- package/dist/mysql-BNXWfTOo.mjs.map +0 -1
- package/dist/mysql-adapter-C69j1sKh.mjs +0 -2
- package/dist/mysql-adapter-C69j1sKh.mjs.map +0 -1
- package/dist/native-types-DgjMUikz.mjs +0 -2
- package/dist/native-types-DgjMUikz.mjs.map +0 -1
- package/dist/normalized-result-B8pifWS0.mjs +0 -2
- package/dist/normalized-result-B8pifWS0.mjs.map +0 -1
- package/dist/object-store-DS0F0yZX.mjs +0 -2
- package/dist/object-store-DS0F0yZX.mjs.map +0 -1
- package/dist/on-ylYaKuRu.mjs +0 -2
- package/dist/pending-operation-C_eOFOBE.mjs +0 -2
- package/dist/pending-operation-C_eOFOBE.mjs.map +0 -1
- package/dist/physical-CeE2nYmI.mjs +0 -2
- package/dist/physical-CeE2nYmI.mjs.map +0 -1
- package/dist/pinned-session-DCoAZDOz.mjs +0 -2
- package/dist/pinned-session-DCoAZDOz.mjs.map +0 -1
- package/dist/postgres-CDdh5dSP.mjs +0 -437
- package/dist/postgres-CDdh5dSP.mjs.map +0 -1
- package/dist/postgres-adapter-Dlr3ZWd7.mjs +0 -2
- package/dist/postgres-adapter-Dlr3ZWd7.mjs.map +0 -1
- package/dist/postgres-adapter-axapXX8d.mjs +0 -2
- package/dist/postgres-result-DF6DmW3r.mjs +0 -2
- package/dist/postgres-result-DF6DmW3r.mjs.map +0 -1
- package/dist/provider-limits-Ccsb8PTb.mjs +0 -2
- package/dist/provider-limits-Ccsb8PTb.mjs.map +0 -1
- package/dist/provider-parameter-snapshot-BikrgKqI.mjs +0 -2
- package/dist/provider-parameter-snapshot-BikrgKqI.mjs.map +0 -1
- package/dist/query-BZVHfA0s.mjs +0 -2
- package/dist/query-BZVHfA0s.mjs.map +0 -1
- package/dist/query-inspection-BoG-yAln.mjs +0 -2
- package/dist/query-inspection-BoG-yAln.mjs.map +0 -1
- package/dist/raw-Dyq6Y6UX.mjs +0 -2
- package/dist/raw-Dyq6Y6UX.mjs.map +0 -1
- package/dist/relation-bound-ku_cMdye.mjs +0 -2
- package/dist/result-parsing-B0Y4KGDT.mjs +0 -2
- package/dist/routed-operations-wytpbYKv.mjs +0 -2
- package/dist/rule-words-ZIGm7cDm.mjs +0 -2
- package/dist/scalar-BHCh7aUz.mjs +0 -4
- package/dist/scalar-BHCh7aUz.mjs.map +0 -1
- package/dist/schema-BYA-_bpk.mjs +0 -2
- package/dist/schema-BYA-_bpk.mjs.map +0 -1
- package/dist/schema-CFIaebgi.mjs +0 -2
- package/dist/schema-CFIaebgi.mjs.map +0 -1
- package/dist/schema-introspection-D0f8cti4.mjs +0 -6
- package/dist/schema-introspection-D0f8cti4.mjs.map +0 -1
- package/dist/select-assembly-DVI7d3tf.mjs +0 -2
- package/dist/select-assembly-DVI7d3tf.mjs.map +0 -1
- package/dist/serializer-rBq3v1xr.mjs +0 -51
- package/dist/serializer-rBq3v1xr.mjs.map +0 -1
- package/dist/settle-1cy5x_52.mjs +0 -2
- package/dist/settled-BjyuA76m.mjs +0 -2
- package/dist/snowflake-UOCC820W.mjs +0 -2
- package/dist/sql-3o4DOKm9.mjs +0 -2
- package/dist/sql-3o4DOKm9.mjs.map +0 -1
- package/dist/sql-Dl6nykFV.mjs +0 -2
- package/dist/sql-Dl6nykFV.mjs.map +0 -1
- package/dist/sql-statement-tokens-DbeMwHra.mjs +0 -3
- package/dist/sqlite-adapter-Ad0d-m2t.mjs +0 -2
- package/dist/sqlite-adapter-Ad0d-m2t.mjs.map +0 -1
- package/dist/sqlite-statement-classifier-BAHl-WXS.mjs +0 -2
- package/dist/sqlite-utils-BRvbmlQ1.mjs +0 -2
- package/dist/sqlite-utils-BRvbmlQ1.mjs.map +0 -1
- package/dist/standard-sql-qLcQyCtK.mjs +0 -6
- package/dist/standard-sql-qLcQyCtK.mjs.map +0 -1
- package/dist/suppressed-failure-CQkQsMVS.mjs +0 -2
- package/dist/surrealql-C1dp1sWw.mjs +0 -2
- package/dist/surrealql-C1dp1sWw.mjs.map +0 -1
- package/dist/to-many-BybuKQM1.mjs +0 -2
- package/dist/to-many-BybuKQM1.mjs.map +0 -1
- package/dist/transaction-BNomMtme.mjs +0 -2
- package/dist/transaction-operation-CVVJxQ19.mjs +0 -2
- package/dist/types-DtDnXhwa.mjs +0 -2
- package/dist/unit-BhHbZyuJ.mjs +0 -2
- package/dist/unit-words-CT0yeqfZ.mjs +0 -2
- package/dist/utils-CpAojrCj.mjs +0 -26
- package/dist/validation--qS7OPmg.mjs +0 -2
- package/dist/validation--qS7OPmg.mjs.map +0 -1
- package/dist/validation-CYaJ8ndO.mjs +0 -2
- package/dist/validation-CYaJ8ndO.mjs.map +0 -1
- package/dist/validator-CZLW7aR3.mjs +0 -2
- package/dist/validator-CZLW7aR3.mjs.map +0 -1
- package/dist/value-guards-CBuxSC66.mjs +0 -2
- package/dist/values-B4aj1i1f.mjs +0 -2
- package/dist/version-CXGIA82S.mjs +0 -2
- package/dist/write-sinks-3IKCDF-S.mjs +0 -2
- /package/dist/{contract-CrIB-3ZJ.d.mts → contract-CxJn0_cV.d.mts} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"model-Dtd37Sky.mjs","names":["map","parsed","values","value","model","result","model","describe","v","v","refused","v","model","#internal","record","fail","v","values","#internal","map","#state","#internal","#withForeignKeyAction","#localFields","v","fail","#state","#internal","model","#names","#nameRegistry","#scalarFieldNames","#relationNames"],"sources":["../src/schema/record.ts","../src/validation/primitives/array.ts","../src/validation/primitives/blob.ts","../src/validation/primitives/boolean.ts","../src/validation/primitives/date.ts","../src/validation/primitives/decimal.ts","../src/validation/primitives/enum.ts","../src/validation/primitives/lazy.ts","../src/validation/primitives/from-object.ts","../src/validation/primitives/iso.ts","../src/schema/field-ref.ts","../src/validation/primitives/json.ts","../src/schema/json-null.ts","../src/validation/primitives/json-null.ts","../src/validation/primitives/literal.ts","../src/validation/primitives/nullable.ts","../src/validation/primitives/omit.ts","../src/validation/primitives/filter-depth.ts","../src/validation/primitives/parameter.ts","../src/validation/primitives/operand.ts","../src/validation/primitives/pipe.ts","../src/validation/primitives/point.ts","../src/validation/primitives/record.ts","../src/validation/primitives/refused.ts","../src/validation/primitives/transform.ts","../src/validation/primitives/shorthand.ts","../src/validation/primitives/union.ts","../src/validation/primitives/single-or-array.ts","../src/validation/primitives/string.ts","../src/validation/primitives/vector.ts","../src/validation/primitives/v.ts","../src/schema/view/facts.ts","../src/schema/scalars/common.ts","../src/schema/relation/terminal.ts","../src/schema/relation/polymorphic.ts","../src/schema/relation/to-one.ts","../src/schema/model/helper.ts","../src/schema/model/model.ts"],"sourcesContent":["// Records keyed by DATA.\n//\n// A schema is built from maps whose keys come from somewhere else: a model\n// shape's field key, a document's model/field/variant key, an enum reference, a\n// default's own object keys. `record[key] = value` is not a safe way to build\n// such a map, because `__proto__` is an accessor on `Object.prototype`:\n// assigning through it sets a prototype and creates NO own key. The entry\n// disappears, and what is left is a well-formed object, so nothing downstream\n// can notice the loss.\n//\n// Reading has the mirror problem: `record[key]` resolves inherited members, so\n// a data key of `__proto__`, `constructor` or `toString` answers something the\n// map never held.\n//\n// One owner for both, used everywhere a key comes from data — the JSON\n// document's maps and `s.model(...)`'s classified member maps alike. It carries\n// no refusal: whether a key is a legal identifier is `isValidSchemaIdentifier`'s\n// question, asked at hydration and by the document reader, and the answer is the\n// same whichever way the key was written. The document READER needs neither\n// helper, because it asks that question before anything is written.\n\n/** A map with no inherited members, so a data key can only find what was put. */\nexport function emptyRecord<T>(): Record<string, T> {\n return Object.create(null);\n}\n\n/** Write one own key, whatever it is called. */\nexport function put<T>(target: Record<string, T>, key: string, value: T): void {\n Object.defineProperty(target, key, {\n value,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n}\n\n/** Read one own key, or nothing. */\nexport function own<T>(\n source: Record<string, T> | undefined,\n key: string\n): T | undefined {\n if (source === undefined || !Object.hasOwn(source, key)) return;\n return source[key];\n}\n\n/** Read the internal state of a model, scalar, or relation. */\nexport const stateOf = <T extends { readonly \"~\": { readonly state: any } }>(\n x: T\n): T[\"~\"][\"state\"] => x[\"~\"].state;\n\n/** Append `value` to the array stored under `key` in `map`. */\nexport function pushMap<K, V>(map: Map<K, V[]>, key: K, value: V): void {\n const list = map.get(key);\n if (list) list.push(value);\n else map.set(key, [value]);\n}\n\n/** Get the value for `key` in `map`, inserting `make()` when absent. */\nexport function mapGet<K, V>(\n map: { get(key: K): V | undefined; set(key: K, value: V): unknown },\n key: K,\n make: () => V\n): V {\n let value = map.get(key);\n if (value === undefined) {\n value = make();\n map.set(key, value);\n }\n return value;\n}\n","import type { InferInput, InferOutput, VibSchema } from \"../types\";\nimport { createSchema, validateArray } from \"./helpers\";\n\n// =============================================================================\n// Array Schema\n// =============================================================================\n\nexport interface ArraySchema<\n TItem extends VibSchema<any, any>,\n TInput = InferInput<TItem>[],\n TOutput = InferOutput<TItem>[],\n> extends VibSchema<TInput, TOutput> {\n readonly type: \"array\";\n readonly item: TItem;\n}\n\n/**\n * Create an array schema that validates each item.\n *\n * @example\n * const tags = v.array(v.string());\n * const scores = v.array(v.number());\n */\nexport function array<TItem extends VibSchema<any, any>>(\n item: TItem\n): ArraySchema<TItem> {\n // Cache the validate function directly\n const validate = item[\"~standard\"].validate;\n\n const schema = createSchema<InferInput<TItem>[], InferOutput<TItem>[]>(\n \"array\",\n (value) => validateArray(value, validate)\n ) as ArraySchema<TItem>;\n\n (schema as any).item = item;\n\n return schema;\n}\n","import type {\n ComputeInput,\n ComputeOutput,\n ScalarOptions,\n VibSchema,\n} from \"../types\";\nimport { isUint8Array } from \"../value-guards\";\nimport { buildSchema, frozenFail, ok } from \"./helpers\";\n\n// =============================================================================\n// Blob Schema (Uint8Array, including Node Buffer subclasses)\n// =============================================================================\n\nexport interface BaseBlobSchema<\n Opts extends ScalarOptions<Uint8Array, any> | undefined = undefined,\n> extends VibSchema<\n ComputeInput<Uint8Array, Opts>,\n ComputeOutput<Uint8Array, Opts>\n > {}\n\nexport interface BlobSchema<TInput = Uint8Array, TOutput = Uint8Array>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"blob\";\n}\n\n// Pre-computed error for fast path\nconst BLOB_ERROR = /* @__PURE__ */ frozenFail(\"Expected Uint8Array\");\n\n// %TypedArray%.prototype owns the metadata accessors. Start lookup there so a\n// genuine foreign view cannot redirect normalization through hostile own\n// properties.\nconst typedArrayPrototype: object = Object.getPrototypeOf(Uint8Array.prototype);\n\nfunction localBufferPrototype(): object | undefined {\n try {\n const bufferConstructor: unknown = Reflect.get(globalThis, \"Buffer\");\n if (typeof bufferConstructor !== \"function\") return;\n const prototype: unknown = Reflect.get(bufferConstructor, \"prototype\");\n if (\n prototype !== null &&\n typeof prototype === \"object\" &&\n Object.getPrototypeOf(prototype) === Uint8Array.prototype\n ) {\n return prototype;\n }\n } catch {\n return;\n }\n}\n\nconst trustedBufferPrototype = localBufferPrototype();\n\nfunction hasOwnViewMetadata(value: Uint8Array): boolean {\n return (\n Object.getOwnPropertyDescriptor(value, \"buffer\") !== undefined ||\n Object.getOwnPropertyDescriptor(value, \"byteOffset\") !== undefined ||\n Object.getOwnPropertyDescriptor(value, \"byteLength\") !== undefined\n );\n}\n\nfunction hasTrustedLocalPrototype(value: Uint8Array): boolean {\n const prototype = Object.getPrototypeOf(value);\n return (\n (prototype === Uint8Array.prototype ||\n prototype === trustedBufferPrototype) &&\n !hasOwnViewMetadata(value)\n );\n}\n\n/**\n * Validate binary data without requiring a Node Buffer global. Node Buffers\n * inherit from Uint8Array and therefore pass this same runtime check.\n */\nexport function validateBlob(value: unknown) {\n try {\n if (!isUint8Array(value)) return BLOB_ERROR;\n\n // Read the internal view through %TypedArray%.prototype. This proves the\n // slots without `instanceof` or caller-visible metadata and bypasses\n // hostile own properties on a genuine local or foreign Uint8Array.\n const buffer: ArrayBufferLike = Reflect.get(\n typedArrayPrototype,\n \"buffer\",\n value\n );\n const byteOffset: number = Reflect.get(\n typedArrayPrototype,\n \"byteOffset\",\n value\n );\n const byteLength: number = Reflect.get(\n typedArrayPrototype,\n \"byteLength\",\n value\n );\n // Only the two exact local prototype paths may retain identity. An\n // intermediate/custom prototype can be a stateful Proxy that agrees with\n // one metadata read and lies to the driver later, so it is never treated as\n // proof. Construct after classification so a detached backing buffer is a\n // refusal rather than a successful detached value.\n const keepsIdentity = hasTrustedLocalPrototype(value);\n const normalized = new Uint8Array(buffer, byteOffset, byteLength);\n // Keep the established plain-local/Node-Buffer identity contract only on\n // the exact trusted path. Every other admitted view normalizes locally.\n if (keepsIdentity) {\n return ok(value);\n }\n return ok(normalized);\n } catch {\n return BLOB_ERROR;\n }\n}\n\n/**\n * Create a blob schema for binary data.\n *\n * @example\n * const avatar = v.blob();\n * const optionalBlob = v.blob({ optional: true });\n * const nullableBlob = v.blob({ nullable: true });\n */\nexport function blob<\n const Opts extends ScalarOptions<Uint8Array, any> | undefined = undefined,\n>(\n options?: Opts\n): BlobSchema<ComputeInput<Uint8Array, Opts>, ComputeOutput<Uint8Array, Opts>> {\n return buildSchema(\"blob\", validateBlob, options) as BlobSchema<\n ComputeInput<Uint8Array, Opts>,\n ComputeOutput<Uint8Array, Opts>\n >;\n}\n","import type {\n ComputeInput,\n ComputeOutput,\n ScalarOptions,\n VibSchema,\n} from \"../types\";\nimport { isBoolean } from \"../value-guards\";\nimport { buildSchema, frozenFail, ok } from \"./helpers\";\n\n// =============================================================================\n// Boolean Schema\n// =============================================================================\n\nexport interface BaseBooleanSchema<\n Opts extends ScalarOptions<boolean, any> | undefined = undefined,\n> extends VibSchema<\n ComputeInput<boolean, Opts>,\n ComputeOutput<boolean, Opts>\n > {}\n\nexport interface BooleanSchema<TInput = boolean, TOutput = boolean>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"boolean\";\n}\n\n// Pre-computed error for fast path\nconst BOOLEAN_ERROR = /* @__PURE__ */ frozenFail(\"Expected boolean\");\n\n/**\n * Validate that a value is a boolean.\n */\nfunction validateBoolean(value: unknown) {\n return isBoolean(value) ? ok(value) : BOOLEAN_ERROR;\n}\n\n/**\n * Create a boolean schema.\n *\n * @example\n * const active = v.boolean();\n * const optionalFlag = v.boolean({ optional: true });\n */\nexport function boolean(): BooleanSchema<boolean, boolean>;\nexport function boolean<const Opts extends ScalarOptions<boolean, any>>(\n options: Opts\n): BooleanSchema<ComputeInput<boolean, Opts>, ComputeOutput<boolean, Opts>>;\nexport function boolean<\n const Opts extends ScalarOptions<boolean, any> | undefined,\n>(\n options?: Opts\n): BooleanSchema<ComputeInput<boolean, Opts>, ComputeOutput<boolean, Opts>> {\n return buildSchema(\"boolean\", validateBoolean, options) as BooleanSchema<\n ComputeInput<boolean, Opts>,\n ComputeOutput<boolean, Opts>\n >;\n}\n\n// Export the validate function for reuse\nexport { validateBoolean };\n","import type {\n ComputeInput,\n ComputeOutput,\n ScalarOptions,\n VibSchema,\n} from \"../types\";\nimport { isDate } from \"../value-guards\";\nimport { buildSchema, frozenFail, ok } from \"./helpers\";\n\n// =============================================================================\n// Date Schema (JavaScript Date objects)\n// =============================================================================\n\nexport interface DateSchema<TInput = Date, TOutput = Date>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"date\";\n}\n\n// Pre-computed errors for fast path\nconst NOT_DATE_ERROR = /* @__PURE__ */ frozenFail(\"Expected Date\");\nconst INVALID_DATE_ERROR = /* @__PURE__ */ frozenFail(\"Expected valid Date\");\n\n/**\n * Validate that a value is a JavaScript Date object.\n */\nfunction validateDate(value: unknown) {\n if (!isDate(value)) return NOT_DATE_ERROR;\n const time = Date.prototype.getTime.call(value);\n if (Number.isNaN(time)) return INVALID_DATE_ERROR;\n if (value instanceof Date) return ok(value);\n // A Date from another realm names this exact instant but fails every local\n // `instanceof` downstream; a local Date at the same instant does not.\n return ok(new Date(time));\n}\n\n/**\n * Create a date schema for JavaScript Date objects.\n *\n * @example\n * const createdAt = v.date();\n * const optionalDate = v.date({ optional: true });\n */\nexport function date<\n const Opts extends ScalarOptions<Date, any> | undefined = undefined,\n>(\n options?: Opts\n): DateSchema<ComputeInput<Date, Opts>, ComputeOutput<Date, Opts>> {\n return buildSchema(\"date\", validateDate, options) as DateSchema<\n ComputeInput<Date, Opts>,\n ComputeOutput<Date, Opts>\n >;\n}\n\n// Export the validate function for reuse\nexport { validateDate };\n","import type {\n ComputeInput,\n ComputeOutput,\n ScalarOptions,\n ValidationFailure,\n ValidationResult,\n VibSchema,\n} from \"../types\";\nimport { type DecimalDescriptor, toDecimal } from \"./decimal-codec\";\nimport {\n admitDecimal,\n canonicalDecimalText,\n DECIMAL_INPUT_REFUSAL,\n type Decimal,\n domainRefusal,\n} from \"./decimal-value\";\nimport { buildSchema, fail, frozenFail, ok, runValidate } from \"./helpers\";\n\n// =============================================================================\n// Decimal Schema\n// =============================================================================\n\n/**\n * What a decimal accepts on the way IN: the public value type, or its lossless\n * spelling. A JavaScript number is a double and is refused.\n */\nexport type DecimalInput = Decimal | string;\n\n/**\n * What a VALIDATED decimal is inside the engine: the canonical private string.\n *\n * This is not a public result mode. It is the one logical representation SQL\n * binding, cursors, row keys, cache keys, race pins, and link folds all key on,\n * because two distinct `Decimal` instances naming the same number must be the\n * same identity. The public `Decimal` is constructed once per selected value at\n * the typed result boundary, never here.\n */\nexport type DecimalOutput = string;\n\n/**\n * Decimal schema options: the ordinary scalar options plus the field's declared\n * fixed-decimal domain. The domain is optional at this level because the\n * primitive is also the unconstrained value grammar the codec is built on; the\n * PUBLIC surface, `s.decimal({ precision, scale })`, always declares one.\n */\nexport interface DecimalOptions<TSchemaOut = Decimal>\n extends ScalarOptions<Decimal, DecimalOutput, TSchemaOut> {\n decimal?: DecimalDescriptor | undefined;\n}\n\n/**\n * A custom `.schema()` REFINES the Decimal the base already built; it does not\n * redefine what the field accepts or what the pipeline emits. So neither\n * computed side may take its types from the schema the way every other scalar's\n * does: input stays `Decimal | string`, output stays canonical text.\n */\ntype DecimalValueOptions<Opts> =\n Opts extends ScalarOptions<any, any, any>\n ? Omit<Opts, \"schema\"> & { schema?: undefined }\n : undefined;\n\ntype ReadonlyDecimalList<T> = T extends DecimalInput[]\n ? readonly DecimalInput[]\n : T;\n\nexport type DecimalComputeInput<Opts> = ReadonlyDecimalList<\n ComputeInput<DecimalInput, DecimalValueOptions<Opts>>\n>;\n\nexport type DecimalComputeOutput<Opts> = ComputeOutput<\n DecimalOutput,\n DecimalValueOptions<Opts>\n>;\n\nexport interface DecimalSchema<TInput = DecimalInput, TOutput = DecimalOutput>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"decimal\";\n readonly acceptsUndefined: boolean;\n readonly options:\n | { readonly decimal?: DecimalDescriptor | undefined }\n | undefined;\n}\n\n/** The FIELD boundary's refusal, in the value module's own words. */\nconst DECIMAL_ERROR: ValidationFailure = /* @__PURE__ */ frozenFail(\n DECIMAL_INPUT_REFUSAL\n);\n\nconst DECIMAL_VALUE_ERROR = \"Expected Decimal from custom schema\";\n\n/**\n * Validate a decimal and NORMALIZE it to its canonical string in one step, so\n * everything downstream — binding, SQL comparison, identity, storage — sees one\n * spelling.\n */\nfunction validateDecimal(value: unknown): ValidationResult<string> {\n const canonical = admitDecimal(value);\n return canonical === undefined ? DECIMAL_ERROR : ok(canonical);\n}\n\n/**\n * The decimal's own validator chain, built HERE rather than composed by\n * `buildValidator`'s option handling, because the ORDER is the contract:\n *\n * base (exact grammar, canonical text)\n * -> the custom schema, which observes a real `Decimal` (plan 2.3)\n * -> the DESCRIPTOR, last, on whatever that schema returned\n *\n * `buildValidator` runs a custom schema after the base and has no hook after\n * it, and validation Rule 4 forbids patching one on afterwards: every decimal\n * filter and update schema is a union, and a union captures each member's\n * `~standard.validate` at construction. So the whole value chain exists before\n * the schema object does, and `buildValidator` is handed only the\n * nullable/optional/array/default wrapping it uniquely owns.\n */\nfunction buildDecimalValueValidator(\n options: DecimalOptions<any> | undefined\n): (value: unknown) => ValidationResult<string> {\n const custom = options?.schema;\n const descriptor = options?.decimal;\n let validate = validateDecimal;\n\n if (custom !== undefined) {\n const refine = custom[\"~standard\"].validate;\n const base = validate;\n validate = (value) => {\n const parsed = base(value);\n if (parsed.issues) return parsed;\n const refined = runValidate(refine, toDecimal(parsed.value));\n if (refined.issues) return refined;\n // The return position admits only a Decimal: a string, a number or a\n // decimal-shaped object the constructor never built is a different\n // value family, so the brand reader alone answers here.\n const canonical = canonicalDecimalText(refined.value);\n return canonical === undefined\n ? fail(DECIMAL_VALUE_ERROR)\n : ok(canonical);\n };\n }\n\n if (descriptor !== undefined) {\n const base = validate;\n validate = (value) => {\n const parsed = base(value);\n if (parsed.issues) return parsed;\n const refusal = domainRefusal(\n parsed.value,\n descriptor.precision,\n descriptor.scale\n );\n return refusal === undefined ? parsed : fail(refusal);\n };\n }\n\n return validate;\n}\n\n/**\n * Create a decimal schema: exact decimal in, canonical decimal string out.\n *\n * @example\n * const price = v.decimal({ decimal: { precision: 10, scale: 2 } });\n * const optionalPrice = v.decimal({ optional: true });\n */\nexport function decimal(): DecimalSchema<DecimalInput, DecimalOutput>;\nexport function decimal<const Opts extends DecimalOptions<any>>(\n options: Opts\n): DecimalSchema<DecimalComputeInput<Opts>, DecimalComputeOutput<Opts>>;\nexport function decimal(options?: DecimalOptions<any>): VibSchema<any, any> {\n // The custom schema is already composed into the value validator above, so it\n // is withheld from the wrapping options — `buildValidator` running it again\n // would re-refine a canonical STRING with a schema that expects a Decimal.\n // Everything the wrappers do own — nullable, optional, array, default —\n // passes through untouched.\n const wrapping =\n options === undefined ? undefined : { ...options, schema: undefined };\n return buildSchema(\"decimal\", buildDecimalValueValidator(options), wrapping);\n}\n\nexport { validateDecimal };\n","import type {\n ComputeInput,\n ComputeOutput,\n ScalarOptions,\n VibSchema,\n} from \"../types\";\nimport { isString } from \"../value-guards\";\nimport { buildSchema, ok } from \"./helpers\";\n\n// =============================================================================\n// Enum Schema\n// =============================================================================\nexport type EnumValues<S extends VibSchema> =\n S extends EnumSchema<infer TValues, any, any> ? TValues : never;\nexport type BaseEnumSchema<\n TValues extends readonly string[],\n Opts extends ScalarOptions<TValues[number], any> | undefined = undefined,\n> = EnumSchema<\n TValues,\n ComputeInput<TValues[number], Opts>,\n ComputeOutput<TValues[number], Opts>\n>;\n\nexport interface EnumSchema<\n TValues extends readonly string[],\n TInput = TValues[number],\n TOutput = TValues[number],\n> extends VibSchema<TInput, TOutput> {\n readonly type: \"enum\";\n readonly values: TValues;\n}\n\n/**\n * Create an enum schema that validates a value is one of the allowed strings.\n *\n * The values may be a readonly tuple (`[\"a\", \"b\"] as const`). The mutable arm\n * of the constraint keeps an inline literal inferred as a mutable tuple, so\n * the types of existing schemas do not change.\n *\n * @example\n * const status = v.enum_([\"active\", \"inactive\", \"pending\"]);\n */\n// @__NO_SIDE_EFFECTS__\nexport function enum_<\n const TValues extends string[] | readonly string[],\n const Opts extends\n | ScalarOptions<TValues[number], any>\n | undefined = undefined,\n>(\n values: TValues,\n options?: Opts\n): EnumSchema<\n TValues,\n ComputeInput<TValues[number], Opts>,\n ComputeOutput<TValues[number], Opts>\n> {\n // Create a Set for O(1) lookup\n const valueSet = new Set<TValues[number]>(values);\n\n // Create base validator\n const baseValidate = (value: unknown) => {\n if (isString(value) && valueSet.has(value)) {\n return ok(value as TValues[number]);\n }\n return {\n issues: [\n {\n message: `Expected one of: ${values.join(\" | \")}`,\n },\n ],\n };\n };\n\n const schema = buildSchema(\"enum\", baseValidate, options, {\n values,\n }) as EnumSchema<\n TValues,\n ComputeInput<TValues[number], Opts>,\n ComputeOutput<TValues[number], Opts>\n >;\n\n return schema;\n}\n","import type { VibSchema } from \"../types\";\nimport { isFunction } from \"../value-guards\";\n\n/**\n * Creates a lazy schema that defers evaluation until first access.\n * The schema is cached after first resolution.\n *\n * Uses a Proxy to transparently forward all property access, method calls,\n * and operations to the wrapped schema. This ensures the lazy schema\n * behaves identically to the wrapped type.\n *\n * The returned schema is typed as T, so it's transparent to consumers -\n * InferInput and InferOutput work as if it were the wrapped schema.\n *\n * @param factory - A function that returns the schema to wrap\n * @returns A schema typed as T that lazily resolves on first access\n */\nexport function lazy<T extends VibSchema>(factory: () => T): T {\n let build: (() => T) | undefined = factory;\n let value: T;\n\n const resolve = (): T => {\n if (build) {\n value = build();\n build = undefined;\n }\n return value;\n };\n\n // Use a Proxy to transparently forward all operations to the resolved schema\n const proxy = new Proxy({} as T, {\n get(_target, prop, receiver) {\n const resolved = resolve();\n const value = Reflect.get(resolved, prop, receiver);\n // Bind methods to the resolved schema to preserve `this` context\n return isFunction(value) ? value.bind(resolved) : value;\n },\n\n has(_target, prop) {\n return Reflect.has(resolve(), prop);\n },\n\n ownKeys(_target) {\n return Reflect.ownKeys(resolve());\n },\n\n getOwnPropertyDescriptor(_target, prop) {\n return Reflect.getOwnPropertyDescriptor(resolve(), prop);\n },\n\n getPrototypeOf(_target) {\n return Reflect.getPrototypeOf(resolve());\n },\n });\n\n return proxy;\n}\n\n/**\n * Lightweight deferred schema reference.\n *\n * Unlike `lazy()` (a Proxy that resolves on ANY property access — including\n * the object validator's duck-typing reads), `lazyRef` exposes a static\n * `type` and a `~standard.validate` that only builds the wrapped schema when\n * the validator is first CALLED. Used for args→core schema cross-references\n * so an operation only constructs the core schemas its arguments actually\n * use (e.g. `findUnique({ where })` never builds select/include).\n *\n * NOT a general-purpose wrapper: it reports no `acceptsUndefined`/default\n * metadata, so it must only wrap schemas with no default value (true for all\n * core schema references).\n */\nexport function lazyRef<T extends VibSchema>(factory: () => T): T {\n let build: (() => T) | undefined = factory;\n let value: T;\n let fn: ((value: unknown) => any) | undefined;\n const resolve = (): T => {\n if (build) {\n value = build();\n build = undefined;\n }\n return value;\n };\n\n return {\n type: \"lazyRef\",\n /**\n * JSON-schema conversion unwraps through this (resolves on demand) — see\n * the `lazyRef` case in {@link file://../json-schema/converters.ts}. A\n * reference that points BACK at a schema still being converted (a scalar\n * filter's `not`) is closed there with a `$ref`, so unwrapping terminates.\n */\n get wrapped() {\n return resolve();\n },\n // Introspection surface (resolves on demand). Deliberately NOT exposed:\n // `options`/`acceptsUndefined`/`default` — the object validator\n // duck-types those during resolve(), and resolving getters there would\n // rebuild the wrapped schema eagerly, defeating the laziness.\n get entries() {\n return (resolve() as { entries?: unknown }).entries;\n },\n \"~standard\": {\n version: 1,\n vendor: \"viborm\",\n validate: (input: unknown) =>\n (fn ??= resolve()[\"~standard\"].validate)(input),\n get jsonSchema() {\n return resolve()[\"~standard\"].jsonSchema;\n },\n },\n } as unknown as T;\n}\n","import { ValidationError } from \"@errors\";\nimport type { Cast, ThunkCast, VibSchema } from \"../types\";\nimport { isFunction, isRecord } from \"../value-guards\";\nimport { lazyRef } from \"./lazy\";\nimport { type ObjectOptions, type ObjectSchema, object } from \"./object\";\n\n// =============================================================================\n// Path Utilities for Nested Object Access\n// =============================================================================\n\n/**\n * Gets the value at a dot path in an object type.\n * Supports nested paths like \"create.name\" or \"create.friends\".\n */\ntype PathValue<T, P extends string> = P extends `${infer Key}.${infer Rest}`\n ? Key extends keyof T\n ? T[Key] extends Record<string, any>\n ? PathValue<T[Key], Rest>\n : never\n : never\n : P extends keyof T\n ? T[P]\n : never;\n\n/**\n * Recursively extracts all dot paths that lead to VibSchema or ThunkCast instances.\n * Returns a union of all valid paths (e.g., \"create\" | \"create.name\").\n * Limited to 5 levels of nesting to avoid infinite recursion.\n */\ntype PathsToSchemas<\n T extends string,\n Prefix extends string = \"\",\n Depth extends readonly unknown[] = [],\n> = Depth[\"length\"] extends 5\n ? never\n : // Check if T is a VibSchema\n T extends VibSchema<any, any>\n ? Prefix\n : // Check if T is a ThunkCast (function returning Cast)\n T extends ThunkCast<any, any>\n ? Prefix\n : T extends () => Cast<any, any>\n ? Prefix\n : // Otherwise recurse into object properties\n T extends Record<string, any>\n ? {\n [K in keyof T]: K extends string\n ? PathsToSchemas<\n T[K],\n Prefix extends \"\" ? K : `${Prefix}.${K}`,\n [...Depth, unknown]\n >\n : never;\n }[keyof T]\n : never;\n\n/**\n * Normalize a schema entry to VibSchema.\n * Handles both direct VibSchema and ThunkCast (unwrapping the thunk's return type).\n */\ntype NormalizeSchemaEntry<T> =\n T extends VibSchema<infer I, infer O>\n ? VibSchema<I, O>\n : T extends ThunkCast<infer I, infer O>\n ? VibSchema<I, O>\n : T extends () => Cast<infer I, infer O>\n ? VibSchema<I, O>\n : never;\n\n/**\n * Gets the schema type at a specific path for a specific key.\n * Handles both VibSchema and ThunkCast entries.\n */\ntype SchemaAtPath<\n TObject extends Record<string, any>,\n TPath extends string,\n K extends keyof TObject,\n> = NormalizeSchemaEntry<PathValue<TObject[K], TPath>>;\n\n/**\n * Extracts all valid paths that lead to schemas from all keys in the object.\n */\nexport type AllPathsToSchemas<TObject extends Record<string, any>> = {\n [K in keyof TObject]: K extends string ? PathsToSchemas<TObject[K]> : never;\n}[keyof TObject];\n\n// =============================================================================\n// FromObject Schema Types\n// =============================================================================\n\n/**\n * Options for fromObject schemas (same as ObjectOptions).\n */\nexport type FromObjectOptions<T = unknown> = ObjectOptions<T>;\n\n/**\n * Compute the entries type from an object and path.\n */\ntype ComputeEntries<\n TObject extends Record<string, any>,\n TPath extends string,\n> = {\n [K in keyof TObject]: SchemaAtPath<TObject, TPath, K>;\n};\n\n// =============================================================================\n// FromObject Schema Implementation\n// =============================================================================\n\n/**\n * Runtime helper to get a nested value by dot path.\n */\nfunction getNestedValue(obj: any, path: string): any {\n const parts = path.split(\".\");\n let current = obj;\n for (const part of parts) {\n if (current === null || current === undefined) {\n return undefined;\n }\n current = current[part];\n }\n return current;\n}\n\n/**\n * Whether `path` names a property of `value`, including one that holds\n * `undefined` — a member that DECLARES it has no schema there (an insert-only\n * scalar's `update`) is not a path typo, and contributes no entry.\n */\nfunction declaresPath(value: unknown, path: string): boolean {\n const cut = path.lastIndexOf(\".\");\n const parent = cut === -1 ? value : getNestedValue(value, path.slice(0, cut));\n return isRecord(parent) && path.slice(cut + 1) in parent;\n}\n\n/**\n * Project entries without constructing an object validator that a composer\n * would immediately discard. The public builder uses this same path boundary.\n */\nexport function entriesFromObject<\n TObject extends Record<string, any>,\n TPath extends string,\n>(sourceObject: TObject, path: TPath): ComputeEntries<TObject, TPath> {\n const result: Record<string, VibSchema<any, any>> = {};\n for (const key of Object.keys(sourceObject)) {\n const value = getNestedValue(sourceObject[key], path);\n if (value !== undefined) {\n result[key] = value;\n }\n }\n if (Object.keys(sourceObject).length > 0 && Object.keys(result).length === 0)\n refuseUnmatchedPath(sourceObject, path);\n // The runtime path projection is the boundary that establishes this mapping.\n return result as ComputeEntries<TObject, TPath>;\n}\n\n/**\n * Deferred key-by-key projection over a lazy record of schema bundles whose\n * member at `key` is guaranteed present and default-free (e.g. scalar filters\n * and relation families). Reading `Object.keys(sourceObject)` triggers no\n * bundle getter; each member is materialized only when that key is validated\n * or converted to JSON Schema.\n */\nexport function lazyEntriesFromObject<\n TObject extends Record<string, any>,\n TPath extends string,\n>(sourceObject: TObject, path: TPath): ComputeEntries<TObject, TPath> {\n const result: Record<string, VibSchema<any, any>> = {};\n for (const key of Object.keys(sourceObject)) {\n result[key] = lazyRef(() => {\n const value = sourceObject[key][path];\n return isFunction(value) ? value() : value;\n });\n }\n return result as ComputeEntries<TObject, TPath>;\n}\n\n/**\n * Creates an object schema by extracting schemas from a record using a dot path.\n * This is a convenient way to build an object schema from a record with proper type inference.\n *\n * @param sourceObject - Source object containing nested schemas\n * @param path - Dot path to extract schemas (e.g., \"create\", \"filter.where\")\n * @param options - Schema options (same as object schema)\n *\n * @example\n * // Given a record of models with nested schemas:\n * const models = {\n * user: { create: v.string(), update: v.string() },\n * post: { create: v.number(), update: v.number() },\n * };\n *\n * // Extract all \"create\" schemas into a single object schema:\n * const createSchema = fromObject(models, \"create\");\n * // Validates: { user: string, post: number }\n *\n * // With options:\n * const optionalSchema = fromObject(models, \"create\", { optional: true });\n * // Validates: { user: string, post: number } | undefined\n *\n * @example\n * // Nested paths work too:\n * const nestedModels = {\n * user: { schemas: { create: v.string() } },\n * post: { schemas: { create: v.number() } },\n * };\n * const nestedSchema = fromObject(nestedModels, \"schemas.create\");\n * // Validates: { user: string, post: number }\n */\nexport function fromObject<\n TObject extends Record<string, any>,\n TPath extends string,\n // TPath extends AllPathsToSchemas<TObject>,\n const TOpts extends FromObjectOptions | undefined = undefined,\n>(\n sourceObject: TObject,\n path: TPath,\n options?: TOpts\n): ObjectSchema<ComputeEntries<TObject, TPath>, TOpts> {\n return object(entriesFromObject(sourceObject, path), options);\n}\n\nexport type { ComputeEntries as ComputeEntriesFromObject };\n\n/** An empty projection, refused unless some source declares the path empty. */\nfunction refuseUnmatchedPath(\n sourceObject: Record<string, unknown>,\n path: string\n): void {\n if (Object.values(sourceObject).some((value) => declaresPath(value, path)))\n return;\n throw new ValidationError(\n { kind: \"schema-builder\", builder: \"fromObject\", path },\n [\n {\n path,\n message: `Path \"${path}\" unmatched in source`,\n },\n ]\n );\n}\n","import type {\n ComputeInput,\n ComputeOutput,\n ScalarOptions,\n VibSchema,\n} from \"../types\";\nimport { isDate, isString } from \"../value-guards\";\nimport {\n isDateTimeClock,\n isDateTimeInstant,\n isGregorianCalendarDate,\n} from \"./datetime-values\";\nimport { buildSchema, frozenFail, ok } from \"./helpers\";\n\n// =============================================================================\n// ISO Format Validators\n// =============================================================================\n\n// ISO timestamp regex: 2023-12-15T10:30:00.000Z\nconst ISO_TIMESTAMP_REGEX =\n /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})(?:\\.\\d{1,3})?(?:Z|[+-](\\d{2}):(\\d{2}))$/;\n\n// ISO date regex: 2023-12-15\nconst ISO_DATE_REGEX = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\n\n// ISO time regex: 10:30:00 or 10:30:00.000\nconst ISO_TIME_REGEX = /^\\d{2}:\\d{2}:\\d{2}(\\.\\d{1,3})?$/;\n\nconst getDateTime = (value: Date) => Date.prototype.getTime.call(value);\nconst toDateIso = (value: Date) => Date.prototype.toISOString.call(value);\n\n// Pre-computed errors\nconst NOT_STRING_OR_DATE_ERROR = /* @__PURE__ */ frozenFail(\n \"Expected string or Date\"\n);\n\n// =============================================================================\n// ISO Timestamp Schema\n// =============================================================================\n\nexport interface BaseIsoTimestampSchema<\n Opts extends ScalarOptions<string, any> | undefined = undefined,\n> extends VibSchema<\n ComputeInput<string | Date, Opts>,\n ComputeOutput<string, Opts>\n > {}\n\nexport interface IsoTimestampSchema<TInput = string | Date, TOutput = string>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"iso_timestamp\";\n}\n\n// Pre-computed errors\nconst INVALID_TIMESTAMP_FORMAT = /* @__PURE__ */ frozenFail(\n \"Invalid ISO timestamp\"\n);\nconst INVALID_TIMESTAMP_DATE = /* @__PURE__ */ frozenFail(\n \"Invalid date in ISO timestamp\"\n);\n\n/**\n * Validate ISO timestamp format.\n * Accepts Date objects and converts them to ISO strings.\n */\nfunction validateIsoTimestamp(value: unknown) {\n // Handle Date objects - convert to ISO string\n if (isDate(value)) {\n return isDateTimeInstant(getDateTime(value))\n ? ok(toDateIso(value))\n : INVALID_TIMESTAMP_DATE;\n }\n\n if (!isString(value)) return NOT_STRING_OR_DATE_ERROR;\n const match = ISO_TIMESTAMP_REGEX.exec(value);\n if (!match) return INVALID_TIMESTAMP_FORMAT;\n const hasValidCalendarAndClock =\n isGregorianCalendarDate(\n Number(match[1]),\n Number(match[2]),\n Number(match[3])\n ) && isDateTimeClock(Number(match[4]), Number(match[5]), Number(match[6]));\n if (\n !hasValidCalendarAndClock ||\n Number(match[7] ?? 0) > 23 ||\n Number(match[8] ?? 0) > 59\n ) {\n return INVALID_TIMESTAMP_DATE;\n }\n if (\n value.length === 24 &&\n value.charCodeAt(23) === 90 &&\n value.charCodeAt(19) === 46\n ) {\n return ok(value);\n }\n const epoch = Date.parse(value);\n if (!isDateTimeInstant(epoch)) {\n return INVALID_TIMESTAMP_DATE;\n }\n return ok(new Date(epoch).toISOString());\n}\n\n/**\n * Create an ISO timestamp schema.\n * Accepts strings in format: 2023-12-15T10:30:00.000Z or Date objects.\n * Date objects are automatically converted to ISO strings.\n *\n * @example\n * const timestamp = v.isoTimestamp();\n * parse(timestamp, new Date()) // Returns ISO string\n */\nexport function isoTimestamp<\n const Opts extends ScalarOptions<string, any> | undefined = undefined,\n>(\n options?: Opts\n): IsoTimestampSchema<\n ComputeInput<string | Date, Opts>,\n ComputeOutput<string, Opts>\n> {\n return buildSchema(\n \"iso_timestamp\",\n validateIsoTimestamp,\n options\n ) as IsoTimestampSchema<\n ComputeInput<string | Date, Opts>,\n ComputeOutput<string, Opts>\n >;\n}\n\n// =============================================================================\n// ISO Date Schema\n// =============================================================================\n\nexport interface BaseIsoDateSchema<\n Opts extends ScalarOptions<string, any> | undefined = undefined,\n> extends VibSchema<\n ComputeInput<string | Date, Opts>,\n ComputeOutput<string, Opts>\n > {}\n\nexport interface IsoDateSchema<TInput = string | Date, TOutput = string>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"iso_date\";\n}\n\n// Pre-computed errors\nconst INVALID_DATE_FORMAT = /* @__PURE__ */ frozenFail(\n \"Expected ISO date (YYYY-MM-DD)\"\n);\nconst INVALID_DATE = /* @__PURE__ */ frozenFail(\"Invalid date\");\n\n/**\n * Validate ISO date format.\n * Accepts Date objects and converts them to ISO date strings (YYYY-MM-DD).\n */\nfunction validateIsoDate(value: unknown) {\n // Handle Date objects - convert to ISO date string\n if (isDate(value)) {\n return isDateTimeInstant(getDateTime(value))\n ? ok(toDateIso(value).slice(0, 10))\n : INVALID_DATE;\n }\n\n if (!isString(value)) return NOT_STRING_OR_DATE_ERROR;\n const match = ISO_DATE_REGEX.exec(value);\n if (!match) return INVALID_DATE_FORMAT;\n if (\n !isGregorianCalendarDate(\n Number(match[1]),\n Number(match[2]),\n Number(match[3])\n )\n ) {\n return INVALID_DATE;\n }\n return ok(value);\n}\n\n/**\n * Create an ISO date schema.\n * Accepts strings in format: 2023-12-15 or Date objects.\n * Date objects are automatically converted to ISO date strings (YYYY-MM-DD).\n *\n * @example\n * const birthDate = v.isoDate();\n * parse(birthDate, new Date()) // Returns \"2023-12-15\"\n */\nexport function isoDate<\n const Opts extends ScalarOptions<string, any> | undefined = undefined,\n>(\n options?: Opts\n): IsoDateSchema<\n ComputeInput<string | Date, Opts>,\n ComputeOutput<string, Opts>\n> {\n return buildSchema(\"iso_date\", validateIsoDate, options) as IsoDateSchema<\n ComputeInput<string | Date, Opts>,\n ComputeOutput<string, Opts>\n >;\n}\n\n// =============================================================================\n// ISO Time Schema\n// =============================================================================\n\nexport interface BaseIsoTimeSchema<\n Opts extends ScalarOptions<string, any> | undefined = undefined,\n> extends VibSchema<\n ComputeInput<string | Date, Opts>,\n ComputeOutput<string, Opts>\n > {}\n\nexport interface IsoTimeSchema<TInput = string | Date, TOutput = string>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"iso_time\";\n}\n\n// Pre-computed errors\nconst INVALID_TIME_FORMAT = /* @__PURE__ */ frozenFail(\n \"Expected ISO time (HH:mm:ss)\"\n);\nconst INVALID_TIME = /* @__PURE__ */ frozenFail(\"Invalid time\");\n\nfunction validateIsoTime(value: unknown) {\n if (isDate(value)) {\n return Number.isNaN(getDateTime(value))\n ? INVALID_TIME\n : ok(toDateIso(value).split(\"T\")[1]!.slice(0, -1));\n }\n\n if (!isString(value)) return NOT_STRING_OR_DATE_ERROR;\n if (!ISO_TIME_REGEX.test(value)) return INVALID_TIME_FORMAT;\n\n const parts = value.split(\":\");\n if (\n !isDateTimeClock(\n Number(parts[0]),\n Number(parts[1]),\n Math.trunc(Number(parts[2]))\n )\n ) {\n return INVALID_TIME;\n }\n return ok(value.padEnd(12, value.includes(\".\") ? \"0\" : \".000\"));\n}\n\n/**\n * Create an ISO time schema.\n * Accepts strings in format: 10:30:00 or Date objects.\n * Date objects are automatically converted to time strings (HH:mm:ss.sss).\n *\n * @example\n * const startTime = v.isoTime();\n * parse(startTime, new Date()) // Returns \"10:30:00.000\"\n */\nexport function isoTime<\n const Opts extends ScalarOptions<string, any> | undefined = undefined,\n>(\n options?: Opts\n): IsoTimeSchema<\n ComputeInput<string | Date, Opts>,\n ComputeOutput<string, Opts>\n> {\n return buildSchema(\"iso_time\", validateIsoTime, options) as IsoTimeSchema<\n ComputeInput<string | Date, Opts>,\n ComputeOutput<string, Opts>\n >;\n}\n\n// Export validators for reuse\nexport { validateIsoTimestamp, validateIsoDate, validateIsoTime };\n","/**\n * Field references (Prisma `FieldRef` parity)\n *\n * A field reference is an opaque, symbol-branded token that stands for a COLUMN\n * instead of a bound parameter in a filter operand position:\n *\n * ```ts\n * client.post.findMany({ where: { views: { gt: (ctx) => ctx.fields.likes } } });\n * // -> ... WHERE \"t0\".\"views\" > \"t0\".\"likes\"\n * ```\n *\n * The token is the MECHANISM; the callback is the surface that hands one out —\n * `ctx.fields` is this file's per-model table, built for the model whose filter\n * the operand sits in (see `validation/primitives/operand.ts`). A token held\n * directly is just as valid: it is what the callback returns.\n *\n * The token carries only what both the validation layer and the SQL builders\n * need — the owning model's schema key, the field's schema key, and the field's\n * scalar type — so it can be created without touching the model graph and\n * compared without any registry lookup.\n *\n * Two rules govern it, and each is enforced where it is actually decidable:\n *\n * - TYPE. A reference's scalar type must match the filter operand's scalar\n * type. Decided by the validation layer ({@link file://../validation/primitives/operand.ts}),\n * which knows the operand's type and nothing about models — scalar filter\n * schemas are interned across models by design (see `validation/scalars/intern.ts`).\n *\n * - SAME MODEL. A reference may only be used in a filter on its own model\n * (Prisma's rule: a field reference compares two columns of the SAME row).\n * Decided by the where-builder ({@link file://../query-engine/builders/where-builder.ts}),\n * because \"the model being filtered\" is a property of the QUERY SCOPE, not of\n * the schema: a nested relation `where` re-scopes to the relation's target\n * model while reusing that model's own (interned, model-blind) filter schemas.\n * The builder must resolve the referenced column against the current scope to\n * emit it at all, so the check is intrinsic there, not a duplicated guard. It\n * runs at SQL-build time — before any I/O.\n */\n\nimport type { Model } from \"./model/model\";\nimport { stateOf } from \"./record\";\nimport type { ScalarType } from \"./scalars/common\";\n\n/**\n * Brand carried by every field reference. `Symbol.for` (not a fresh symbol) so\n * a reference stays recognizable across duplicated module instances.\n */\nexport const FIELD_REF_BRAND: unique symbol = Symbol.for(\"viborm.field-ref\");\n\n/**\n * An opaque reference to a scalar column of `TModel`.\n *\n * `TType` is the field's scalar type; it is what makes an `Int` reference\n * unassignable to a `String` filter operand at the type level.\n */\n/** What a reference knows about its column, held UNDER the brand symbol. */\nexport interface FieldRefPayload<\n TModel extends string = string,\n TType extends ScalarType = ScalarType,\n> {\n /** Schema key of the model owning the field (e.g. `\"post\"`). */\n readonly model: TModel;\n /** Schema key of the field (e.g. `\"likes\"`), NOT the mapped column name. */\n readonly field: string;\n /** Scalar type of the field (e.g. `\"int\"`). */\n readonly type: TType;\n /** Whether the field is a list scalar. List references are not supported. */\n readonly list: boolean;\n}\n\nexport interface FieldRef<\n TModel extends string = string,\n TType extends ScalarType = ScalarType,\n> {\n // The ONLY key, and it is a symbol on purpose. A reference rides operand\n // unions everywhere a filter value goes; if it exposed string-keyed members\n // (`model`, `field`, ...) the editor would offer them as completions inside\n // every filter object literal that admits a reference. The payload lives\n // under the brand so the token contributes NOTHING to those completions.\n readonly [FIELD_REF_BRAND]: FieldRefPayload<TModel, TType>;\n}\n\n/** Any field reference, regardless of model or scalar type. */\nexport type AnyFieldRef = FieldRef<string, ScalarType>;\n\n/**\n * Runtime brand check. Deliberately a plain property probe: it runs once per\n * filter operand, so it must be a single `typeof` plus one symbol lookup.\n */\nexport function isFieldRef(value: unknown): value is AnyFieldRef {\n if (typeof value !== \"object\" || value === null) return false;\n const payload = (value as { [FIELD_REF_BRAND]?: unknown })[FIELD_REF_BRAND];\n return typeof payload === \"object\" && payload !== null;\n}\n\n/** The reference's column facts. The one sanctioned way to read them. */\nexport function fieldRefPayload(ref: AnyFieldRef): FieldRefPayload {\n return ref[FIELD_REF_BRAND];\n}\n\n/** Human-readable spelling of a reference, for error messages. */\nexport function formatFieldRef(ref: AnyFieldRef): string {\n const payload = fieldRefPayload(ref);\n return `${payload.model}.${payload.field}`;\n}\n\nfunction createFieldRef(\n model: string,\n field: string,\n type: ScalarType,\n list: boolean\n): AnyFieldRef {\n return Object.freeze({\n [FIELD_REF_BRAND]: Object.freeze({ model, field, type, list }),\n });\n}\n\n// =============================================================================\n// TYPE-LEVEL PROJECTION: model -> its reference table\n// =============================================================================\n\ntype ScalarsOf<M> = M extends { \"~\": { state: { scalars: infer S } } }\n ? S\n : never;\n\ntype ScalarTypeOf<S> = S extends {\n \"~\": { state: { type: infer T extends ScalarType } };\n}\n ? T\n : ScalarType;\n\ntype ReferenceableScalarKeys<M> = {\n [K in keyof ScalarsOf<M>]: ScalarTypeOf<ScalarsOf<M>[K]> extends \"point\"\n ? never\n : K;\n}[keyof ScalarsOf<M>];\n\n/**\n * One model's reference table — the type of `ctx.fields` inside an operand\n * callback: one reference per scalar field, and nothing else on it, so a\n * mistyped field name is a compile error before it is a runtime one.\n */\nexport type ModelFieldRefs<TModelName extends string, M> = {\n readonly [K in ReferenceableScalarKeys<M> & string]: FieldRef<\n TModelName,\n ScalarTypeOf<ScalarsOf<M>[K]>\n >;\n};\n\n// =============================================================================\n// RUNTIME PROJECTION\n// =============================================================================\n\nconst UNKNOWN_FIELD = (modelName: string, key: string, known: string[]) =>\n new Error(\n `Unknown scalar '${key}' on '${modelName}' (known: ${known.join(\", \")})`\n );\n\nexport function createModelFieldRefs<\n TName extends string,\n M extends Model<any>,\n>(modelName: TName, model: M): ModelFieldRefs<TName, M> {\n const cache = new Map<string, AnyFieldRef>();\n const scalars = stateOf(model).scalars;\n const referenceableNames = Object.keys(scalars).filter(\n (key) => stateOf(scalars[key]!).type !== \"point\"\n );\n const referenceableSet = new Set(referenceableNames);\n const table = new Proxy(Object.create(null) as Record<string, AnyFieldRef>, {\n get(_target, key) {\n if (typeof key !== \"string\") return undefined;\n const cached = cache.get(key);\n if (cached) return cached;\n const scalar = referenceableSet.has(key) ? scalars[key] : undefined;\n if (!scalar) {\n throw UNKNOWN_FIELD(modelName, key, referenceableNames);\n }\n const state = stateOf(scalar);\n const ref = createFieldRef(modelName, key, state.type, state.array);\n cache.set(key, ref);\n return ref;\n },\n has: (_target, key) => typeof key === \"string\" && referenceableSet.has(key),\n ownKeys: () => referenceableNames,\n getOwnPropertyDescriptor: (_target, key) =>\n typeof key === \"string\" && referenceableSet.has(key)\n ? {\n enumerable: true,\n configurable: true,\n }\n : undefined,\n });\n // The one projection this file owes its callers: the proxy answers exactly\n // the model's scalar keys (`has`/`ownKeys` above enforce it, and any other key\n // throws), which is what `ModelFieldRefs` describes and no proxy signature can.\n return table as ModelFieldRefs<TName, M>;\n}\n","import { isFieldRef } from \"@schema/field-ref\";\nimport type {\n ComputeInput,\n ComputeOutput,\n ScalarOptions,\n ValidationResult,\n VibSchema,\n} from \"../types\";\nimport { isBoolean, isNumber, isRecord, isString } from \"../value-guards\";\nimport { buildSchema, frozenFail, ok } from \"./helpers\";\n\n// =============================================================================\n// JSON Schema\n// =============================================================================\n\n/**\n * JSON-compatible value type.\n * Represents any value that can be safely serialized to JSON.\n */\nexport type JsonValue =\n | string\n | number\n | boolean\n | null\n | JsonValue[]\n | { [key: string]: JsonValue };\n\n/** JSON serialization omits undefined object members and nulls array holes. */\nexport type JsonInput =\n | string\n | number\n | boolean\n | null\n | readonly (JsonInput | undefined)[]\n | { [key: string]: JsonInput | undefined };\n\n/**\n * A JSON value in WRITE position: everything `JsonValue` allows EXCEPT a bare\n * top-level `null`.\n *\n * Once `DbNull` and `JsonNull` exist, a top-level `null` no longer says which\n * of the two nulls it means, so it is not a legal write value — the same line\n * Prisma draws with its own `InputJsonValue`. Nested nulls are untouched:\n * `{ a: null }` is an ordinary document.\n */\nexport type InputJsonValue = Exclude<JsonInput, null>;\n\nexport interface BaseJsonSchema<\n Opts extends ScalarOptions<JsonInput, any> | undefined = undefined,\n> extends VibSchema<\n ComputeInput<JsonInput, Opts>,\n ComputeOutput<JsonValue, Opts>\n > {}\n\nexport interface JsonSchema<TInput = JsonInput, TOutput = JsonValue>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"json\";\n}\n\n// Pre-computed errors for fast path\nconst NOT_JSON_ERROR = /* @__PURE__ */ frozenFail(\n \"Expected JSON-compatible value\"\n);\n\n/**\n * Check if a value is JSON-compatible (can be serialized without loss).\n * Rejects: undefined, functions, symbols, bigint, circular references.\n */\nconst INVALID_JSON = Symbol(\"invalid JSON\");\n\nfunction normalizeJson(\n value: unknown,\n seen = new WeakMap<object, JsonValue | typeof INVALID_JSON>()\n): JsonValue | typeof INVALID_JSON {\n if (value === null || isString(value) || isBoolean(value)) return value;\n if (isNumber(value)) return Number.isFinite(value) ? value : INVALID_JSON;\n if (!(isRecord(value) || Array.isArray(value))) return INVALID_JSON;\n if (isFieldRef(value)) return INVALID_JSON;\n const previous = seen.get(value);\n if (previous !== undefined) return previous;\n seen.set(value, INVALID_JSON); // A back-edge is a cycle; completed aliases are reusable.\n if (Array.isArray(value)) {\n const result: JsonValue[] = [];\n for (const original of value) {\n const member =\n original === undefined ? null : normalizeJson(original, seen);\n if (member === INVALID_JSON) return INVALID_JSON;\n result.push(member);\n }\n seen.set(value, result);\n return result;\n }\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== null && prototype !== Object.prototype) return INVALID_JSON;\n const result: Record<string, JsonValue> = {};\n for (const key of Object.keys(value)) {\n const original = value[key];\n if (original === undefined) {\n continue;\n }\n const member = normalizeJson(original, seen);\n if (member === INVALID_JSON) return INVALID_JSON;\n Object.defineProperty(result, key, {\n value: member,\n enumerable: true,\n configurable: true,\n writable: true,\n });\n }\n seen.set(value, result);\n return result;\n}\n\n/**\n * Validate that a value is JSON-compatible.\n */\nfunction validateJson(value: unknown): ValidationResult<JsonValue> {\n const normalized = normalizeJson(value);\n return normalized === INVALID_JSON ? NOT_JSON_ERROR : ok(normalized);\n}\n\n/**\n * Create a JSON schema that validates any JSON-compatible value.\n * Accepts: strings, numbers (finite), booleans, null, arrays, plain objects.\n * Rejects: undefined, functions, symbols, bigint, circular references, class instances.\n *\n * @example\n * const data = v.json();\n * const optionalData = v.json({ optional: true });\n * const nullableData = v.json({ nullable: true });\n */\n// @__NO_SIDE_EFFECTS__\nexport function json<\n const Opts extends ScalarOptions<JsonInput, any> | undefined = undefined,\n>(\n options?: Opts\n): JsonSchema<ComputeInput<JsonInput, Opts>, ComputeOutput<JsonValue, Opts>> {\n return buildSchema<JsonInput, Opts | undefined>(\n \"json\",\n validateJson,\n options\n ) as JsonSchema<\n ComputeInput<JsonInput, Opts>,\n ComputeOutput<JsonValue, Opts>\n >;\n}\n\n// Export for reuse\nexport { validateJson };\n","/**\n * JSON null sentinels (Prisma `DbNull` / `JsonNull` / `AnyNull` parity)\n *\n * A nullable JSON column has TWO different nulls, and SQL can tell them apart\n * while JavaScript cannot:\n *\n * - the SQL NULL — the column holds no document at all (`col IS NULL`);\n * - the JSON null — the column holds a document, and that document is the\n * JSON value `null` (`'null'::jsonb`, `CAST('null' AS JSON)`, the text\n * `null` on SQLite).\n *\n * Both read back as JavaScript `null`, so a bare `null` cannot name either one\n * without guessing. Prisma solves this with three exported sentinel values, and\n * so does this file:\n *\n * ```ts\n * import { AnyNull, DbNull, JsonNull } from \"viborm\";\n *\n * await client.entry.update({ where, data: { meta: DbNull } }); // -> SQL NULL\n * await client.entry.update({ where, data: { meta: JsonNull } }); // -> 'null'\n * await client.entry.findMany({ where: { meta: { equals: AnyNull } } });\n * ```\n *\n * `AnyNull` is FILTER-ONLY, exactly as in Prisma: \"either null\" is a question,\n * not a value, so there is nothing for a write to store. The validation layer\n * refuses it in write position by name (see\n * {@link file://../validation/primitives/json-null.ts}).\n *\n * THE TOKENS ARE CLASS INSTANCES ON PURPOSE. `v.json()` accepts a plain object\n * with any keys, so a plain-object token would type-check as an ordinary JSON\n * document and could be PERSISTED as user data — the same hazard field\n * references have (see {@link file://./field-ref.ts}). A class instance has a\n * prototype that is not `Object.prototype`, so JSON validation rejects it\n * structurally: a sentinel nested anywhere inside a document\n * (`{ a: DbNull }`) fails validation instead of landing in the column as `{}`.\n * Only the top-level operand positions that explicitly opt in accept one.\n *\n * The `kind` property is an OWN ENUMERABLE STRING key, not only the symbol\n * brand, so a token reads as itself in a dump and a structural serializer at\n * least tells the three apart rather than flattening all three to `{}`.\n *\n * BEING TOLD APART IS NOT THE SAME AS BEING RECOGNIZED, and this file used to\n * claim otherwise. A JSON column accepts an ARBITRARY object, so\n * `{ kind: \"DbNull\" }` is ordinary user data — and a serializer walking\n * `Object.keys` gives it the same identity as the sentinel. The cache key\n * builder did exactly that, and a cached client served the rows of\n * `equals: DbNull` for `equals: { kind: \"DbNull\" }`, in both directions, for\n * the whole TTL. A consumer that must not confuse the two asks\n * {@link isJsonNullSentinel} and keys the answer somewhere a document cannot\n * reach, as {@link file://../cache/key.ts} now does.\n */\n\n/**\n * Brand carried by every JSON null sentinel. `Symbol.for` (not a fresh symbol)\n * so a token stays recognizable across duplicated module instances, exactly as\n * for field references.\n */\nexport const JSON_NULL_BRAND: unique symbol = Symbol.for(\"viborm.json-null\");\n\n/** The three sentinels, by name. */\nexport type JsonNullKind = \"DbNull\" | \"JsonNull\" | \"AnyNull\";\n\n/**\n * A JSON null sentinel. `TKind` is what makes `AnyNull` unassignable to a write\n * slot while `DbNull` and `JsonNull` are assignable to it.\n */\nexport class JsonNullSentinel<TKind extends JsonNullKind = JsonNullKind> {\n readonly [JSON_NULL_BRAND]: TKind;\n /** Own enumerable key so structural serializers separate the three. */\n readonly kind: TKind;\n\n constructor(kind: TKind) {\n this[JSON_NULL_BRAND] = kind;\n this.kind = kind;\n Object.freeze(this);\n }\n\n /** Readable in error messages: `DbNull`, not `[object Object]`. */\n toString(): string {\n return this.kind;\n }\n\n /** Distinct under `JSON.stringify` (instrumentation, dedup keys). */\n toJSON(): string {\n return `viborm.json-null:${this.kind}`;\n }\n}\n\n/** Any sentinel, regardless of kind. */\nexport type AnyJsonNullSentinel = JsonNullSentinel<JsonNullKind>;\n\n/** The database NULL: the column holds no JSON document. */\nexport const DbNull: JsonNullSentinel<\"DbNull\"> =\n /*#__PURE__*/ new JsonNullSentinel(\"DbNull\");\n\n/** The JSON null: the column holds the JSON document `null`. */\nexport const JsonNull: JsonNullSentinel<\"JsonNull\"> =\n /*#__PURE__*/ new JsonNullSentinel(\"JsonNull\");\n\n/** Either null. Filter positions only — see the module header. */\nexport const AnyNull: JsonNullSentinel<\"AnyNull\"> =\n /*#__PURE__*/ new JsonNullSentinel(\"AnyNull\");\n\nconst KINDS: ReadonlySet<string> = new Set<JsonNullKind>([\n \"DbNull\",\n \"JsonNull\",\n \"AnyNull\",\n]);\n\n/**\n * Runtime brand check. A property probe rather than `instanceof`, so a token\n * created by a duplicated copy of this module is still recognized (the same\n * reason {@link file://./field-ref.ts} probes its symbol).\n */\nexport function isJsonNullSentinel(\n value: unknown\n): value is AnyJsonNullSentinel {\n if (typeof value !== \"object\" || value === null) return false;\n const brand = (value as { [JSON_NULL_BRAND]?: unknown })[JSON_NULL_BRAND];\n return typeof brand === \"string\" && KINDS.has(brand);\n}\n\n/** The sentinel's kind, or `undefined` when the value is not a sentinel. */\nexport function jsonNullKindOf(value: unknown): JsonNullKind | undefined {\n return isJsonNullSentinel(value) ? value.kind : undefined;\n}\n","// JSON null sentinel operand schemas\n// Admits `DbNull` / `JsonNull` / `AnyNull` into the exact JSON slots that can\n// mean something by them, and refuses them everywhere else BY NAME.\n\nimport {\n type AnyJsonNullSentinel,\n isJsonNullSentinel,\n JsonNull,\n type JsonNullKind,\n type JsonNullSentinel,\n} from \"@schema/json-null\";\nimport type { InferInput, InferOutput, VibSchema } from \"../types\";\nimport { createSchema, fail, ok, validateSchema, withWrapped } from \"./helpers\";\n\n/**\n * Why this is a brand-discriminated wrapper and not `v.union([...])`: a union\n * rewrites every existing operand failure into \"Value did not match any union\n * member: …\". Here the brand is the discriminator, so a non-sentinel value is\n * handed straight to the wrapped schema and keeps its exact message, and a\n * sentinel gets a sentinel-specific one. Same reasoning as\n * {@link file://./field-ref.ts}.\n */\nexport interface JsonNullOrSchema<\n TAllowed extends JsonNullKind,\n TSchema extends VibSchema<any, any>,\n> extends VibSchema<\n InferInput<TSchema> | JsonNullSentinel<TAllowed>,\n InferOutput<TSchema> | JsonNullSentinel<TAllowed>\n > {\n readonly type: \"json_null_or\";\n /** The sentinel kinds this slot accepts. */\n readonly allowed: readonly JsonNullKind[];\n /** The operand schema this wraps. */\n readonly wrapped: TSchema;\n /** Mirrors the wrapped schema, for the object validator's absent-key path. */\n readonly acceptsUndefined: boolean;\n}\n\n/**\n * A JSON WRITE slot: the sentinels it accepts, the whole JSON document\n * language, and — deliberately — NOT a bare `null`.\n *\n * `null` is excluded from the INPUT type as well as refused at runtime, which\n * is Prisma's rule: its `InputJsonValue` documents that `null` is disallowed at\n * the top level of a JSON write because its meaning would be ambiguous, and\n * directs callers to `Prisma.JsonNull` / `Prisma.DbNull`\n * (`@prisma/client`, `runtime/client.d.ts`, the `InputJsonValue` doc comment;\n * https://www.prisma.io/docs/orm/prisma-client/special-fields-and-types/working-with-json-fields#using-null-values).\n * `null` is only excluded at the TOP level — `{ a: null }` is an ordinary\n * document and stays legal, exactly as in Prisma.\n */\nexport interface JsonWriteSchema<\n TAllowed extends JsonNullKind,\n TSchema extends VibSchema<any, any>,\n> extends VibSchema<\n Exclude<InferInput<TSchema>, null> | JsonNullSentinel<TAllowed>,\n InferOutput<TSchema> | JsonNullSentinel<TAllowed>\n > {\n readonly type: \"json_write\";\n readonly allowed: readonly JsonNullKind[];\n readonly wrapped: TSchema;\n readonly acceptsUndefined: boolean;\n}\n\n/** `DbNull, JsonNull or AnyNull` — for the refusal messages. */\nfunction listKinds(kinds: readonly JsonNullKind[]): string {\n if (kinds.length === 1) return kinds[0] as string;\n return `${kinds.slice(0, -1).join(\", \")} or ${kinds.at(-1)}`;\n}\n\nfunction refuseSentinel(\n sentinel: AnyJsonNullSentinel,\n allowed: readonly JsonNullKind[],\n where: string\n) {\n return fail(\n allowed.length === 0\n ? `JSON null sentinels are not supported in ${where}.`\n : `${sentinel.kind} is not supported in ${where}; pass ${listKinds(allowed)}.`\n );\n}\n\nfunction checkSentinel(\n value: AnyJsonNullSentinel,\n allowed: readonly JsonNullKind[],\n where: string\n) {\n return allowed.includes(value.kind)\n ? ok(value)\n : refuseSentinel(value, allowed, where);\n}\n\nexport function jsonNullOr<\n TAllowed extends JsonNullKind,\n TSchema extends VibSchema<any, any>,\n>(\n allowed: readonly TAllowed[],\n wrapped: TSchema,\n where: string\n): JsonNullOrSchema<TAllowed, TSchema> {\n const schema = createSchema<\n InferInput<TSchema> | JsonNullSentinel<TAllowed>,\n InferOutput<TSchema> | JsonNullSentinel<TAllowed>\n >(\"json_null_or\", (value) => {\n if (isJsonNullSentinel(value)) {\n return checkSentinel(value, allowed, where) as never;\n }\n return validateSchema(wrapped, value) as never;\n }) as JsonNullOrSchema<TAllowed, TSchema>;\n\n return withWrapped(schema, wrapped, { allowed });\n}\n\nexport function jsonWrite<\n TAllowed extends JsonNullKind,\n TSchema extends VibSchema<any, any>,\n>(\n allowed: readonly TAllowed[],\n wrapped: TSchema,\n where: string,\n nullRefusal: string\n): JsonWriteSchema<TAllowed, TSchema> {\n const schema = createSchema<\n Exclude<InferInput<TSchema>, null> | JsonNullSentinel<TAllowed>,\n InferOutput<TSchema> | JsonNullSentinel<TAllowed>\n >(\"json_write\", (value) => {\n if (isJsonNullSentinel(value)) {\n return checkSentinel(value, allowed, where) as never;\n }\n if (value === null) return fail(nullRefusal) as never;\n const result = validateSchema(wrapped, value);\n return (\n !result.issues && result.value === null && value !== undefined\n ? checkSentinel(JsonNull, allowed, where)\n : result\n ) as never;\n }) as JsonWriteSchema<TAllowed, TSchema>;\n\n return withWrapped(schema, wrapped, { allowed });\n}\n","import type {\n ComputeInput,\n ComputeOutput,\n ScalarOptions,\n VibSchema,\n} from \"../types\";\nimport { buildSchema, ok } from \"./helpers\";\n\n// =============================================================================\n// Literal Schema\n// =============================================================================\n\nexport type LiteralValue =\n | string\n | number\n | boolean\n | null\n | undefined\n | bigint;\n\nexport interface LiteralSchema<T extends LiteralValue, TInput = T, TOutput = T>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"literal\";\n readonly value: T;\n}\n\n/**\n * Create a literal schema that matches an exact value.\n *\n * @example\n * const admin = v.literal(\"admin\");\n * const zero = v.literal(0);\n * const isTrue = v.literal(true);\n */\nexport function literal<\n const T extends LiteralValue,\n const Opts extends ScalarOptions<T, any> | undefined = undefined,\n>(\n expected: T,\n options?: Opts\n): LiteralSchema<T, ComputeInput<T, Opts>, ComputeOutput<T, Opts>> {\n // Pre-compute error for fast path\n const expectedStr = expected === null ? \"null\" : String(expected);\n const errorResult = Object.freeze({\n issues: Object.freeze([\n Object.freeze({\n message: `Expected literal: ${expectedStr}`,\n }),\n ]),\n });\n\n // Create base validator\n const baseValidate = (value: unknown) =>\n value === expected ? ok(value as T) : errorResult;\n\n return buildSchema(\"literal\", baseValidate, options, {\n value: expected,\n }) as LiteralSchema<T, ComputeInput<T, Opts>, ComputeOutput<T, Opts>>;\n}\n","import type {\n InferInput,\n InferOutput,\n ValidationResult,\n VibSchema,\n} from \"../types\";\nimport { createSchema, ok } from \"./helpers\";\n\n// =============================================================================\n// Nullable Schema\n// =============================================================================\n\nexport interface NullableSchema<\n TWrapped extends VibSchema<any, any>,\n TInput = InferInput<TWrapped> | null,\n TOutput = InferOutput<TWrapped> | null,\n> extends VibSchema<TInput, TOutput> {\n readonly type: \"nullable\";\n readonly wrapped: TWrapped;\n}\n\n/**\n * Create a nullable schema that allows null values.\n *\n * @example\n * const nullableName = v.nullable(v.string());\n */\nexport function nullable<TWrapped extends VibSchema<any, any>>(\n wrapped: TWrapped\n): NullableSchema<TWrapped> {\n // Cache validate function directly\n const validate = wrapped[\"~standard\"].validate;\n\n const schema = createSchema(\n \"nullable\",\n (value): ValidationResult<InferOutput<TWrapped> | null> => {\n // Handle null - fast path\n if (value === null) {\n return ok(null);\n }\n\n // Delegate to wrapped schema (cast to our result type)\n return validate(value) as ValidationResult<InferOutput<TWrapped>>;\n }\n ) as NullableSchema<TWrapped>;\n\n // Add reference\n (schema as any).wrapped = wrapped;\n\n return schema;\n}\n\n/**\n * Conditionally wrap a schema in nullable based on a boolean flag.\n * Useful for building schemas dynamically where nullability is determined at compile time.\n *\n * @example\n * const schema = v.maybeNullable(v.string(), true); // NullableSchema<StringSchema>\n * const schema2 = v.maybeNullable(v.string(), false); // StringSchema\n */\nexport function maybeNullable<\n TWrapped extends VibSchema<any, any>,\n TIsNullable extends boolean,\n>(\n wrapped: TWrapped,\n isNullable: TIsNullable\n): TIsNullable extends true ? NullableSchema<TWrapped> : TWrapped {\n if (isNullable) {\n return nullable(wrapped) as TIsNullable extends true\n ? NullableSchema<TWrapped>\n : TWrapped;\n }\n return wrapped as TIsNullable extends true\n ? NullableSchema<TWrapped>\n : TWrapped;\n}\n","import { type ObjectSchema, object } from \"./object\";\nimport type { V } from \"./v\";\n\n/**\n * Create a new object schema with specific keys omitted.\n *\n * @param schema - The source object schema\n * @param keys - Array of keys to omit from the schema\n * @returns A new object schema without the specified keys\n *\n * @example\n * const user = v.object({\n * id: v.string(),\n * name: v.string(),\n * password: v.string(),\n * });\n *\n * const publicUser = v.omit(user, ['password']);\n * // { id?: string; name?: string }\n */\nexport function omit<\n TSchema extends ObjectSchema<any, any>,\n const TKeys extends readonly (keyof TSchema[\"entries\"])[] | undefined,\n>(schema: TSchema, keys: TKeys): V.Omit<TSchema, TKeys> {\n return object(schema.entries, {\n ...(schema.options || {}),\n omit: keys,\n }) as V.Omit<TSchema, TKeys>;\n}\n","import type { VibSchema } from \"../types\";\nimport { fail, patchValidate } from \"./helpers\";\n\n// Filter parsing is synchronous. Bound semantic filter containers before\n// descending, including scalar `not`, without restricting JSON data depth.\nlet activeDepth = 0;\nconst MAX_FILTER_DEPTH = 16;\nlet bounded = true;\n\n/**\n * Run `parse` without the bound: a domain predicate is the application's own\n * data, whose termination its lowering proves (the bound is for payloads).\n */\nexport function withoutFilterDepthBound<T>(parse: () => T): T {\n const previous = bounded;\n bounded = false;\n try {\n return parse();\n } finally {\n bounded = previous;\n }\n}\n\nexport function limitFilterDepth<S extends VibSchema>(schema: S): S {\n return patchValidate(schema, (validate) => (value) => {\n if (bounded && activeDepth >= MAX_FILTER_DEPTH)\n return fail(`Filter nesting exceeds ${MAX_FILTER_DEPTH} levels`);\n activeDepth++;\n try {\n return validate(value);\n } finally {\n activeDepth--;\n }\n });\n}\n","// A domain predicate (an extension's `rule`) names values the call supplies\n// and conditions on them. While one is admitted, every value position of the\n// `where` schemas asks the admission what its value stands for, and every\n// `where` asks what a filter word in its place stands for: the schemas, which\n// own which place is a value and which a filter, are the one judge of where a\n// word can sit. The nodes the admission answers are registered here and kept\n// as they are, by identity, so an admitted predicate admits again as itself.\n// Nothing else can produce one: the registries are module-private, so a\n// caller's payload never carries a node.\n\nimport type { VibSchema } from \"../types\";\nimport { withoutFilterDepthBound } from \"./filter-depth\";\nimport {\n createSchema,\n fail,\n ok,\n patchValidate,\n validateSchema,\n withWrapped,\n} from \"./helpers\";\n\n/**\n * What a filter word stands for: `nodes`, kept as they are, and the filter\n * written with them that is parsed in the word's place (the first node\n * itself where there is none); or why the word is refused, at a path inside\n * it.\n */\nexport type FilterWord =\n | { readonly nodes: readonly object[]; readonly where?: unknown }\n | { readonly message: string; readonly path: readonly PropertyKey[] };\n\n/** What a domain predicate's admission makes of the markers it meets. */\nexport interface DomainMarkers {\n /** The node a value stands for (a call value), `undefined` for a literal. */\n value(value: unknown): object | undefined;\n /** What a filter word stands for, `undefined` for a value that is none. */\n filter(value: object): FilterWord | undefined;\n}\n\nconst values = new WeakSet<object>();\nconst conditions = new WeakSet<object>();\n\n/** The admission in progress, while a domain predicate is parsed. */\nlet admitting: DomainMarkers | undefined;\n\n/**\n * One admission's parsed filters, per `where` schema and input object. A\n * predicate shares sub-filters freely (a relation's target predicate is\n * inlined wherever it is read), so each shared object is parsed once per\n * schema and its admitted value shared alike. Only successes are kept: a\n * refusal is always reported from the place that reached it.\n */\nexport type AdmittedFilters = WeakMap<object, WeakMap<object, unknown>>;\nlet parsed: AdmittedFilters | undefined;\n\n/**\n * The node `value` is, or, while a domain predicate is admitted, the node it\n * stands for; `undefined` for any other value.\n */\nexport function valueNodeOf(value: unknown): object | undefined {\n if (typeof value === \"object\" && value !== null && values.has(value))\n return value;\n const node = admitting?.value(value);\n if (node !== undefined) values.add(node);\n return node;\n}\n\n/** A value position that also keeps a value node. */\nexport function valueNodeOr<S extends VibSchema<any, any>>(wrapped: S): S {\n const schema = createSchema<unknown, unknown>(\"value_node_or\", (value) => {\n const node = valueNodeOf(value);\n return node === undefined ? validateSchema(wrapped, value) : ok(node);\n });\n return withWrapped(schema, wrapped) as unknown as S;\n}\n\n/**\n * A `where` that also keeps a condition node, and, while a domain predicate is\n * admitted, reads a filter word in its place as what the word stands for.\n * Wrapped in place: a `where` reaches itself through `AND`/`OR`/`NOT`, so\n * every nested position keeps one.\n */\nexport function conditionNodeOr<S extends VibSchema<any, any>>(where: S): S {\n const standard = where[\"~standard\"];\n return patchValidate(where, (validate) => {\n const admit = (value: object) => {\n const word = admitting?.filter(value);\n if (word === undefined) return validate(value);\n if (\"message\" in word) return fail(word.message, [...word.path]);\n for (const node of word.nodes) conditions.add(node);\n return word.where === undefined\n ? ok(word.nodes[0])\n : validate(word.where);\n };\n return (value) => {\n if (typeof value !== \"object\" || value === null) return validate(value);\n if (conditions.has(value)) return ok(value);\n const seen = admitting && parsed;\n if (!seen) return admit(value);\n let byValue = seen.get(standard);\n if (byValue === undefined) seen.set(standard, (byValue = new WeakMap()));\n const known = byValue.get(value);\n if (known !== undefined) return known;\n const result = admit(value) as { issues?: unknown };\n if (result.issues === undefined) byValue.set(value, result);\n return result;\n };\n });\n}\n\n/**\n * Parse with a domain predicate's rules: its markers are `markers`' nodes, it\n * is the application's own finite data, so the caller payload's nesting\n * bound does not apply, and a recursion writes its depth.\n */\nexport function admittingDomainPredicate<T>(\n markers: DomainMarkers,\n admit: () => T,\n filters: AdmittedFilters = new WeakMap()\n): T {\n const previous = admitting;\n const previousFilters = parsed;\n admitting = markers;\n parsed = filters;\n try {\n return withoutFilterDepthBound(admit);\n } finally {\n admitting = previous;\n parsed = previousFilters;\n }\n}\n\n/**\n * A filter's `recurse`, which a domain predicate must give a depth: the\n * default one would stop inheritance at a number nobody wrote.\n */\nexport function writtenDepth<S extends VibSchema<any, any>>(recurrence: S): S {\n const schema = createSchema<unknown, unknown>(\"written_depth\", (value) =>\n admitting &&\n (value === true ||\n (typeof value === \"object\" &&\n value !== null &&\n (value as { depth?: unknown }).depth === undefined))\n ? fail(\"Row recurse requires depth (false or number)\")\n : validateSchema(recurrence, value)\n );\n return withWrapped(schema, recurrence) as unknown as S;\n}\n","// Comparison Operand Schemas\n//\n// A comparison operand is the right-hand side of a scalar filter: the thing a\n// column is compared AGAINST. Four kinds live here, and this file is the only\n// place that decides which of them a given position accepts:\n//\n// 1. a plain value `{ views: { gt: 10 } }`\n// 2. a field reference `{ views: { gt: <FieldRef> } }` -> another column\n// 3. an SQL fragment `{ views: { gt: sql`…` } }` -> escape hatch\n// 4. a callback `{ views: { gt: (ctx) => … } }` -> sugar for 2 and 3\n//\n// The callback is RESOLVED HERE, during validation: it is invoked once and its\n// return value substituted, so the query engine's operand invariant stays\n// exactly \"plain value | FieldRef | Sql\" and no function ever reaches it. That\n// is what keeps validation the single home for payload normalization — the\n// engine does not learn a fourth operand kind, and neither does the cache key.\n\nimport {\n type AnyFieldRef,\n createModelFieldRefs,\n type FieldRef,\n fieldRefPayload,\n isFieldRef,\n type ModelFieldRefs,\n} from \"@schema/field-ref\";\nimport type { AnyModel } from \"@schema/model\";\nimport type { ScalarType } from \"@schema/scalars/common\";\nimport { isSql, type Sql, sql } from \"@sql\";\nimport { discardAsyncValidationResult } from \"../parse-failure\";\nimport type { InferInput, InferOutput, VibSchema } from \"../types\";\nimport { isFunction, isRecord } from \"../value-guards\";\nimport { limitFilterDepth } from \"./filter-depth\";\nimport {\n createSchema,\n fail,\n ok,\n patchValidate,\n runValidate,\n validateSchema,\n withWrapped,\n} from \"./helpers\";\nimport { valueNodeOf } from \"./parameter\";\n\n// =============================================================================\n// THE CALLBACK CONTEXT\n// =============================================================================\n\n/**\n * What a comparison-operand callback is handed.\n *\n * `fields` is the CURRENT model's reference table — the model whose filter the\n * operand sits in, which for a nested relation filter is the relation's TARGET,\n * not the root. Correlated references to an enclosing scope are deliberately\n * absent: a field reference compares two columns of the SAME row, and widening\n * that is a separate decision.\n *\n * `sql` is the ordinary tagged template; interpolations inside a fragment ride\n * along as bound parameters (see {@link file://../../sql/sql.ts}).\n *\n * PURITY IS THE CONTRACT for the callback handed this context. Validation may\n * run a payload's callbacks more than once — `upsert` re-parses its taken arm\n * (the C2 residue), so a callback under `upsert.update` can be invoked twice\n * for one call. A callback that counts its calls, mutates outer state, or\n * returns a different fragment each time gets exactly what it asks for; a pure\n * one is indistinguishable from a literal token, which is the whole point of\n * the sugar.\n */\nexport interface OperandCtx<TModel> {\n readonly fields: ModelFieldRefs<string, TModel>;\n readonly sql: typeof sql;\n}\n\n/** An operand context for an unknown model — the type-level default. */\nexport type AnyOperandCtx = OperandCtx<any>;\n\n// =============================================================================\n// THE PER-MODEL SCOPE\n// =============================================================================\n\n/**\n * The model whose filter is currently being validated.\n *\n * WHY AN AMBIENT SCOPE RATHER THAN A BAKED-IN CONTEXT: scalar filter schemas are\n * INTERNED across models on purpose (see `validation/scalars/intern.ts`) — two\n * `s.string()` fields on different models share one filter tree — so an operand\n * schema cannot carry a model. What IS per-model is the `where` schema that\n * contains it, and every re-scoping boundary is one of those (a nested relation\n * filter embeds the TARGET model's `where`). So the boundary pushes the model\n * and the operand reads it. Validation is synchronous and depth-first, which is\n * what makes a single slot with save/restore exact rather than merely likely.\n */\nlet activeModel: AnyModel | undefined;\n\n/** Contexts are built on first use and memoized per model. */\nconst contexts = new WeakMap<AnyModel, AnyOperandCtx>();\n\n/**\n * Run `validate` with `model` as the operand scope, restoring the previous one\n * afterwards. Re-entrant: a nested relation filter pushes its own target and\n * pops back to the parent.\n */\nexport function runInOperandScope<T>(model: AnyModel, validate: () => T): T {\n const previous = activeModel;\n activeModel = model;\n try {\n return validate();\n } finally {\n activeModel = previous;\n }\n}\n\n/**\n * Re-close a schema onto a model: everything validated through it resolves its\n * operand callbacks against `model`.\n *\n * The wrap is applied IN PLACE, and both reasons matter. The schema is a\n * freshly built, model-owned object whose `entries` / `extend` surface its own\n * factory and the factories above it still read, so returning a different object\n * would either lose that surface or force a copy of every entry. And a `where`\n * is SELF-REFERENTIAL — its `AND`/`OR`/`NOT` thunks close over the very const\n * being returned — so a copy would leave the recursion pointing at the\n * unwrapped original.\n */\nexport function scopeOperands<S extends VibSchema<any, any>>(\n schema: S,\n model: AnyModel\n): S {\n return limitFilterDepth(\n patchValidate(\n schema,\n (inner) => (value) => runInOperandScope(model, () => inner(value))\n )\n );\n}\n\n/** The context for the model in scope, or `undefined` outside any filter. */\nfunction currentContext(): AnyOperandCtx | undefined {\n const model = activeModel;\n if (!model) return undefined;\n const cached = contexts.get(model);\n if (cached) return cached;\n const context: AnyOperandCtx = {\n fields: createModelFieldRefs(model[\"~\"].names.ts ?? \"unknown\", model),\n sql,\n };\n contexts.set(model, context);\n return context;\n}\n\n// =============================================================================\n// THE OPERAND SCHEMA\n// =============================================================================\n\n/**\n * A comparison operand: the wrapped scalar schema, a field reference of\n * `TType`, an SQL fragment, or a callback returning one of the latter two.\n *\n * This is deliberately not `v.union([...])`: a union would rewrite every\n * existing operand's failure message into \"Value did not match any union\n * member: …\". Here each non-value kind is recognized by its own discriminator,\n * so an ordinary bad value is handed straight to the wrapped schema and keeps\n * its exact message.\n *\n * The reference's MODEL is not checked here — scalar filter schemas are interned\n * across models and carry no model identity (see `validation/scalars/intern.ts`);\n * the same-model rule is a query-scope property and is enforced by the\n * where-builder before any I/O. See {@link file://../../schema/field-ref.ts}.\n */\nexport interface ComparisonOperandSchema<\n TType extends ScalarType,\n TSchema extends VibSchema<any, any>,\n TCtx extends AnyOperandCtx = AnyOperandCtx,\n> extends VibSchema<\n | InferInput<TSchema>\n | FieldRef<string, TType>\n | Sql\n | ((ctx: TCtx) => FieldRef<string, TType> | Sql),\n InferOutput<TSchema> | FieldRef<string, TType> | Sql\n > {\n readonly type: \"comparison_operand\";\n /** The scalar type a reference must carry to be accepted. */\n readonly fieldType: TType;\n /** The literal-operand schema this wraps. */\n readonly wrapped: TSchema;\n /** Mirrors the wrapped schema, for the object validator's absent-key path. */\n readonly acceptsUndefined: boolean;\n}\n\nconst CALLBACK_OUT_OF_SCOPE = \"Filter callback needs model scope.\";\n\nconst RETURN_REFUSAL = \"Callback must return field ref or Sql.\";\n\nfunction describe(value: unknown): string {\n if (value === null) return \"null\";\n if (Array.isArray(value)) return \"an array\";\n return `type '${typeof value}'`;\n}\n\nfunction resolveCallback(\n callback: (ctx: AnyOperandCtx) => unknown,\n fieldType: ScalarType\n) {\n const context = currentContext();\n if (!context) {\n return fail(CALLBACK_OUT_OF_SCOPE);\n }\n\n let returned: unknown;\n try {\n returned = callback(context);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return fail(`Filter callback threw: ${message}`);\n }\n\n if (isFieldRef(returned)) {\n return checkRef(returned, fieldType);\n }\n if (isSql(returned)) {\n return ok(returned);\n }\n if (isRecord(returned) && isFunction(returned.then)) {\n discardAsyncValidationResult(returned);\n return fail(`${RETURN_REFUSAL}; got a promise (async unsupported).`);\n }\n return fail(`${RETURN_REFUSAL}; got ${describe(returned)}.`);\n}\n\n/**\n * Build a comparison operand around a scalar schema.\n *\n * ATTACH IT ONLY WHERE THE ENGINE CAN COMPILE THE RESULT. Acceptance that\n * outruns the builder is accept-and-ignore with extra steps: today that means\n * `equals` / `not` / `lt` / `lte` / `gt` / `gte` on non-list scalar filters, and\n * nothing else. `in` / `notIn` and the list operators take VALUES, `having` is\n * an aggregate over a group rather than a column of one row, and the string\n * predicates keep the narrower {@link fieldRefOr} (a reference, no fragment).\n */\nfunction operandSchema(\n type: \"comparison_operand\" | \"field_ref_or\",\n fieldType: ScalarType,\n wrapped: VibSchema<any, any>,\n full: boolean\n) {\n return withWrapped(\n createSchema<any, any>(type, (value) => {\n const node = valueNodeOf(value);\n if (node !== undefined) return ok(node);\n if (full && isFunction(value)) {\n return resolveCallback(\n value as (ctx: AnyOperandCtx) => unknown,\n fieldType\n );\n }\n if (isFieldRef(value)) return checkRef(value, fieldType);\n if (full && isSql(value)) return ok(value);\n return validateSchema(wrapped, value);\n }),\n wrapped,\n { fieldType }\n );\n}\n\nexport function comparisonOperand<\n TType extends ScalarType,\n TSchema extends VibSchema<any, any>,\n TCtx extends AnyOperandCtx = AnyOperandCtx,\n>(\n fieldType: TType,\n wrapped: TSchema\n): ComparisonOperandSchema<TType, TSchema, TCtx> {\n return operandSchema(\n \"comparison_operand\",\n fieldType,\n wrapped,\n true\n ) as ComparisonOperandSchema<TType, TSchema, TCtx>;\n}\n\n// =============================================================================\n// FIELD-REFERENCE-ONLY OPERAND\n// =============================================================================\n\n/**\n * A comparison operand that accepts EITHER a field reference of `TType` or the\n * wrapped scalar schema — no fragment, no callback.\n *\n * This is what the string predicates (`contains` / `startsWith` / `endsWith`)\n * take: the builder compiles a referenced column there, so the reference stays,\n * while the fragment and its callback sugar are drawn at the comparison\n * operators only.\n */\nexport interface FieldRefOrSchema<\n TType extends ScalarType,\n TSchema extends VibSchema<any, any>,\n> extends VibSchema<\n InferInput<TSchema> | FieldRef<string, TType>,\n InferOutput<TSchema> | FieldRef<string, TType>\n > {\n readonly type: \"field_ref_or\";\n /** The scalar type a reference must carry to be accepted. */\n readonly fieldType: TType;\n /** The literal-operand schema this wraps. */\n readonly wrapped: TSchema;\n /** Mirrors the wrapped schema, for the object validator's absent-key path. */\n readonly acceptsUndefined: boolean;\n}\n\nexport function fieldRefOr<\n TType extends ScalarType,\n TSchema extends VibSchema<any, any>,\n>(fieldType: TType, wrapped: TSchema): FieldRefOrSchema<TType, TSchema> {\n return operandSchema(\n \"field_ref_or\",\n fieldType,\n wrapped,\n false\n ) as FieldRefOrSchema<TType, TSchema>;\n}\n\n// =============================================================================\n// RE-CLOSING WRAPPER\n// =============================================================================\n\n/**\n * Re-closes a schema that transitively opened a non-value operand.\n *\n * Scalar filter schemas are shared: `having` reuses the very same interned\n * filter a `where` uses. Prisma does not allow field references in\n * `having`/`groupBy` (a HAVING operand is an aggregate over a group, not a\n * column of one row), and neither do we — so the reuse site wraps itself and\n * fails closed instead of inheriting the operand by accident.\n */\nexport interface NoFieldRefSchema<TSchema extends VibSchema<any, any>>\n extends VibSchema<InferInput<TSchema>, InferOutput<TSchema>> {\n readonly type: \"no_field_ref\";\n readonly wrapped: TSchema;\n readonly acceptsUndefined: boolean;\n}\n\nfunction closeOperands<TSchema extends VibSchema<any, any>>(\n wrapped: TSchema,\n where: string,\n fragments: boolean\n): NoFieldRefSchema<TSchema> {\n const validate = wrapped[\"~standard\"].validate;\n const rejectOpaque = (value: unknown) => {\n const found = findOpaqueOperand(value, fragments);\n return found ? fail(`${found} is not supported in ${where}.`) : undefined;\n };\n const schema = createSchema<InferInput<TSchema>, InferOutput<TSchema>>(\n \"no_field_ref\",\n (value) => {\n const pre = rejectOpaque(value);\n if (pre) return pre;\n const result = runValidate(validate, value);\n if (result.issues) return result as never;\n return (rejectOpaque(result.value) ?? result) as never;\n }\n ) as NoFieldRefSchema<TSchema>;\n\n return withWrapped(schema, wrapped);\n}\n\n/**\n * Close a schema to field references only.\n *\n * For the sites whose wrapped schema legitimately holds ARBITRARY DATA — the\n * JSON operand and JSON write data. Only the branded token is looked for there,\n * because it is the only non-value an ordinary document cannot also be: a real\n * `Sql` is a class instance and `v.json` already rejects it as\n * non-JSON-compatible, while a plain `{ strings: […], values: […] }` document\n * that merely LOOKS like a fragment is honest user data and must stay accepted.\n */\nexport function noFieldRef<TSchema extends VibSchema<any, any>>(\n wrapped: TSchema,\n where: string\n): NoFieldRefSchema<TSchema> {\n return closeOperands(wrapped, where, false);\n}\n\n/**\n * Close a schema to field references AND SQL fragments.\n *\n * For the sites whose wrapped schema is a SCALAR FILTER — `having`, where a\n * fragment is refused for the same reason a reference is: whatever it names, it\n * is not the aggregate the group is keyed by. A plain object cannot be a legal\n * scalar operand in the first place, so there is no honest value here for the\n * structural fragment check to misread.\n */\nexport function noOperandExpression<TSchema extends VibSchema<any, any>>(\n wrapped: TSchema,\n where: string\n): NoFieldRefSchema<TSchema> {\n return closeOperands(wrapped, where, true);\n}\n\n/**\n * Exhaustive, cycle-safe search for a field-reference token or an SQL fragment\n * inside an already-validated value; returns how to name the one it found.\n *\n * There is deliberately NO depth cap. An earlier version stopped at four levels\n * on the premise that \"filter values nest at most a couple of levels\" — false\n * on this branch, where scalar `not` nests arbitrarily\n * (`{ not: { not: { … { gt: ref } } } }`, see `buildNegatableFilterSchema`). A\n * five-deep chain therefore walked straight past the guard and emitted the\n * referenced column into HAVING: Postgres rejected the ungrouped column,\n * SQLite/LibSQL accepted it and returned a silently wrong row. A guard that\n * stops looking is accept-and-ignore, which is precisely what this wrapper\n * exists to prevent.\n *\n * Termination comes from structure, not from a budget: every object and array\n * is visited at most once (`seen`), so the walk is linear in the number of\n * distinct nodes the caller already materialized — the same order the\n * `validateSchema` call directly above just spent walking the very same value.\n * The worklist is explicit rather than recursive so a pathologically deep\n * payload cannot overflow the stack here. Binary payloads are skipped whole:\n * bytes cannot be a reference, and `Object.keys` on a typed array would\n * enumerate every index.\n */\nfunction findOpaqueOperand(\n root: unknown,\n fragments: boolean\n): string | undefined {\n // The set of visited objects is made at the second object: most values\n // checked here are one flat object (an `orderBy` term), and a `WeakSet` per\n // check was 5 % of an ordered nested read's validation (2026-11-16).\n let first: object | undefined;\n let seen: WeakSet<object> | undefined;\n const pending: unknown[] = [root];\n\n while (pending.length > 0) {\n const value = pending.pop();\n if (fragments && typeof value === \"function\") return \"A filter callback\";\n if (typeof value !== \"object\" || value === null) continue;\n if (isFieldRef(value)) {\n const payload = fieldRefPayload(value);\n return `Field reference '${payload.model}.${payload.field}'`;\n }\n if (fragments && isSql(value)) return \"An SQL fragment\";\n if (seen) {\n if (seen.has(value)) continue;\n seen.add(value);\n } else if (first === undefined) first = value;\n else if (value === first) continue;\n else seen = new WeakSet([first, value]);\n\n if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) continue;\n\n if (Array.isArray(value)) {\n for (const item of value) pending.push(item);\n continue;\n }\n\n for (const key of Object.keys(value)) {\n pending.push((value as Record<string, unknown>)[key]);\n }\n }\n\n return undefined;\n}\n\nfunction checkRef(ref: AnyFieldRef, fieldType: ScalarType) {\n const payload = fieldRefPayload(ref);\n if (payload.list) {\n return fail(\n `Field reference '${payload.model}.${payload.field}' cannot be a list.`\n );\n }\n if (payload.type !== fieldType) {\n return fail(\n `Field reference '${payload.model}.${payload.field}' has type '${payload.type}', expected '${fieldType}'.`\n );\n }\n return ok(ref) as never;\n}\n","import type { InferInput, InferOutput, VibSchema } from \"../types\";\nimport { createSchema, ok, transformFail, validateSchema } from \"./helpers\";\n\n// =============================================================================\n// Pipe Schema\n// =============================================================================\n\n/**\n * Transform action interface.\n */\nexport interface TransformAction<TIn, TOut> {\n readonly type: \"transform\";\n readonly transform: (value: TIn) => TOut;\n}\n\n/**\n * Create a transform action for use with pipe.\n *\n * @example\n * const upperCase = v.pipe(v.string(), v.transform(s => s.toUpperCase()));\n */\nexport function transform<TIn, TOut>(\n fn: (value: TIn) => TOut\n): TransformAction<TIn, TOut> {\n return {\n type: \"transform\",\n transform: fn,\n };\n}\n\n/**\n * Pipe action types.\n */\nexport type PipeAction<TIn, TOut> = TransformAction<TIn, TOut>;\n\n/**\n * Pipe schema interface.\n */\nexport interface PipeSchema<\n TSchema extends VibSchema<any, any>,\n TActions extends readonly PipeAction<any, any>[],\n TInput = InferInput<TSchema>,\n TOutput = TActions extends readonly [...any[], PipeAction<any, infer TLast>]\n ? TLast\n : InferOutput<TSchema>,\n> extends VibSchema<TInput, TOutput> {\n readonly type: \"pipe\";\n readonly schema: TSchema;\n readonly actions: TActions;\n}\n\n/**\n * Infer the final output type from a chain of actions.\n */\ntype InferPipeOutput<\n TSchema extends VibSchema<any, any>,\n TActions extends readonly PipeAction<any, any>[],\n> = TActions extends readonly []\n ? InferOutput<TSchema>\n : TActions extends readonly [PipeAction<any, infer TOut>]\n ? TOut\n : TActions extends readonly [PipeAction<any, infer TMid>, ...infer TRest]\n ? TRest extends readonly PipeAction<any, any>[]\n ? InferPipeOutput<VibSchema<TMid, TMid>, TRest>\n : TMid\n : InferOutput<TSchema>;\n\n/**\n * Create a pipe schema that chains a base schema with transform actions.\n *\n * @example\n * const trimmedString = v.pipe(v.string(), v.transform(s => s.trim()));\n * const isoDate = v.pipe(v.date(), v.transform(d => d.toISOString()));\n */\nexport function pipe<\n TSchema extends VibSchema<any, any>,\n const TActions extends readonly PipeAction<any, any>[],\n>(\n schema: TSchema,\n ...actions: TActions\n): PipeSchema<\n TSchema,\n TActions,\n InferInput<TSchema>,\n InferPipeOutput<TSchema, TActions>\n> {\n const pipeSchema = createSchema<\n InferInput<TSchema>,\n InferPipeOutput<TSchema, TActions>\n >(\"pipe\", (value) => {\n const result = validateSchema(schema, value);\n if (result.issues) {\n return result as any;\n }\n\n let current: unknown = (result as { value: unknown }).value;\n for (const action of actions) {\n if (action.type === \"transform\") {\n try {\n current = action.transform(current);\n } catch (e) {\n return transformFail(e);\n }\n }\n }\n\n return ok(current as InferPipeOutput<TSchema, TActions>);\n }) as PipeSchema<\n TSchema,\n TActions,\n InferInput<TSchema>,\n InferPipeOutput<TSchema, TActions>\n >;\n\n (pipeSchema as any).schema = schema;\n (pipeSchema as any).actions = actions;\n\n return pipeSchema;\n}\n","import type {\n ComputeInput,\n ComputeOutput,\n ScalarOptions,\n VibSchema,\n} from \"../types\";\nimport { type GeoPoint, validateGeoPoint } from \"./geo-point-codec\";\nimport { buildSchema } from \"./helpers\";\n\n// =============================================================================\n// GeoPoint Schema ({ longitude: number, latitude: number })\n// =============================================================================\n\nexport interface BasePointSchema<\n Opts extends ScalarOptions<GeoPoint, any> | undefined = undefined,\n> extends VibSchema<\n ComputeInput<GeoPoint, Opts>,\n ComputeOutput<GeoPoint, Opts>\n > {}\n\nexport interface PointSchema<TInput = GeoPoint, TOutput = GeoPoint>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"point\";\n}\n\n/**\n * Create a point schema for EPSG:4326 longitude/latitude coordinates.\n *\n * @example\n * const location = v.point();\n * const optionalPoint = v.point({ optional: true });\n * const pointArray = v.point({ array: true });\n */\nexport function point<\n const Opts extends ScalarOptions<GeoPoint, any> | undefined = undefined,\n>(\n options?: Opts\n): PointSchema<ComputeInput<GeoPoint, Opts>, ComputeOutput<GeoPoint, Opts>> {\n return buildSchema(\"point\", validateGeoPoint, options) as PointSchema<\n ComputeInput<GeoPoint, Opts>,\n ComputeOutput<GeoPoint, Opts>\n >;\n}\n","import type {\n Cast,\n InferInput,\n InferOutput,\n ThunkCast,\n VibSchema,\n} from \"../types\";\nimport { isRecord } from \"../value-guards\";\nimport { createSchema, fail, ok, validateSchema } from \"./helpers\";\nimport { type ObjectOptions, type ObjectSchema, object } from \"./object\";\n\n// =============================================================================\n// Record Schema (dynamic keys)\n// =============================================================================\n\nexport interface RecordSchema<\n TKey extends VibSchema<string, string>,\n TValue extends VibSchema<any, any>,\n TInput = Record<InferInput<TKey>, InferInput<TValue>>,\n TOutput = Record<InferOutput<TKey>, InferOutput<TValue>>,\n> extends VibSchema<TInput, TOutput> {\n readonly type: \"record\";\n readonly key: TKey;\n readonly value: TValue;\n}\n\n/**\n * Create a record schema that validates keys and values.\n *\n * @example\n * const stringRecord = v.record(v.string(), v.number());\n * // Validates: { foo: 1, bar: 2 }\n */\nexport function record<\n TKey extends VibSchema<string, string>,\n TValue extends VibSchema<any, any>,\n>(key: TKey, value: TValue): RecordSchema<TKey, TValue> {\n const schema = createSchema<\n Record<InferInput<TKey>, InferInput<TValue>>,\n Record<InferOutput<TKey>, InferOutput<TValue>>\n >(\"record\", (input) => {\n if (!isRecord(input)) {\n return fail(\n `Expected object, received ${\n Array.isArray(input) ? \"array\" : typeof input\n }`\n );\n }\n\n const output: Record<string, unknown> = {};\n\n for (const [k, v] of Object.entries(input)) {\n const keyResult = validateSchema(key, k);\n if (keyResult.issues) {\n return fail(`Invalid key \"${k}\": ${keyResult.issues[0]!.message}`, [k]);\n }\n\n const valueResult = validateSchema(value, v);\n if (valueResult.issues) {\n const issue = valueResult.issues[0]!;\n // Use concat instead of spread for better performance\n const newPath = issue.path\n ? ([k] as PropertyKey[]).concat(issue.path)\n : [k];\n return fail(issue.message, newPath);\n }\n\n output[(keyResult as { value: string }).value] = (\n valueResult as { value: unknown }\n ).value;\n }\n\n return ok(output as Record<InferOutput<TKey>, InferOutput<TValue>>);\n }) as RecordSchema<TKey, TValue>;\n\n (schema as any).key = key;\n (schema as any).value = value;\n\n return schema;\n}\n\n// =============================================================================\n// FromKeys Schema (static keys with same value schema)\n// =============================================================================\n\n/**\n * Schema entry type - VibSchema or ThunkCast for circular references.\n */\ntype SchemaEntry =\n | VibSchema<any, any>\n | ThunkCast<any, any>\n | (() => Cast<any, any>);\n\n/**\n * Normalize a schema entry to VibSchema for type extraction.\n */\ntype NormalizeEntry<T> =\n T extends VibSchema<infer I, infer O>\n ? VibSchema<I, O>\n : T extends ThunkCast<infer I, infer O>\n ? VibSchema<I, O>\n : T extends () => Cast<infer I, infer O>\n ? VibSchema<I, O>\n : never;\n\n/**\n * Compute entries from a tuple of keys and a schema.\n */\nexport type ComputeEntriesFromKeys<\n TKeys extends readonly string[],\n TSchema extends SchemaEntry,\n> = {\n [K in TKeys[number]]: NormalizeEntry<TSchema>;\n};\n\n/**\n * Options for fromKeys (same as ObjectOptions).\n */\nexport type FromKeysOptions<T = unknown> = ObjectOptions<T>;\n\n/** Project entries for composition without constructing a temporary schema. */\nexport function entriesFromKeys<\n const TKeys extends readonly string[],\n TSchema extends SchemaEntry,\n>(keys: TKeys, schema: TSchema): ComputeEntriesFromKeys<TKeys, TSchema> {\n const entries: Record<string, SchemaEntry> = {};\n for (const key of keys) {\n entries[key] = schema;\n }\n // Preserve the builder's existing thunk-normalized inference boundary.\n return entries as unknown as ComputeEntriesFromKeys<TKeys, TSchema>;\n}\n\n/**\n * Creates an object schema from an array of keys, all mapping to the same schema.\n * This is a convenient wrapper around `object()` for creating uniform schemas.\n *\n * @param keys - Array of key names (use `as const` for type inference)\n * @param schema - Schema to use for all keys (can be a thunk for circular refs)\n * @param options - Schema options (same as object schema)\n *\n * @example\n * // All keys have the same string schema\n * const schema = v.fromKeys([\"name\", \"email\", \"bio\"] as const, v.string());\n * // → ObjectSchema<{ name: string, email: string, bio: string }>\n *\n * @example\n * // With options\n * const optionalSchema = v.fromKeys(\n * [\"user\", \"post\"] as const,\n * v.number(),\n * { partial: false }\n * );\n * // → ObjectSchema<{ user: number, post: number }> (all required)\n *\n * @example\n * // With thunks for circular references\n * const nodeSchema: VibSchema<any, any> = v.object({ value: v.string() });\n * const schema = v.fromKeys(\n * [\"left\", \"right\"] as const,\n * () => nodeSchema,\n * { optional: true }\n * );\n */\nexport function fromKeys<\n const TKeys extends readonly string[],\n TSchema extends SchemaEntry,\n const TOpts extends FromKeysOptions | undefined = undefined,\n>(\n keys: TKeys,\n schema: TSchema,\n options?: TOpts\n): ObjectSchema<ComputeEntriesFromKeys<TKeys, TSchema>, TOpts> {\n return object(entriesFromKeys(keys, schema), options);\n}\n","import type { VibSchema } from \"../types\";\nimport { createSchema, fail } from \"./helpers\";\n\n/**\n * A key that EXISTS on an object schema but accepts NOTHING.\n *\n * Leaving a key out already rejects it — with `Unknown key: gt`, which reads\n * like a typo. Some keys are absent for a reason worth telling the caller:\n * ordered comparison on an enum cannot answer the same on every provider\n * (see {@link file://../scalars/enum.ts}), `_distance` is only meaningful under\n * a vector order (see {@link file://../model/core/orderby.ts}). Spelling those\n * out as a refusal turns a shrug into an explanation, and keeps the key in the\n * schema where the reason can be read.\n *\n * Input and output are both `never`, so TypeScript refuses the key too —\n * the runtime refusal is the backstop for untyped callers.\n *\n * @param reason - the message the caller sees, stating WHY, not just \"no\"\n */\nexport function refused(reason: string): VibSchema<never, never> {\n return createSchema<never, never>(\"refused\", () => fail(reason));\n}\n","import type {\n InferInput,\n InferOutput,\n ValidationResult,\n VibSchema,\n} from \"../types\";\nimport {\n createSchema,\n ok,\n transformFail,\n validateSchema,\n withWrapped,\n} from \"./helpers\";\n\n// =============================================================================\n// Transform Schema Wrapper\n// =============================================================================\n\n/**\n * Schema that wraps another schema and transforms its output.\n */\nexport interface TransformSchema<TInput, TOutput>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"transform\";\n}\n\n/**\n * Wrap a schema with a transform function.\n * Validates with the wrapped schema, then applies the transform to the output.\n *\n * @param schema - The base schema to validate with\n * @param fn - Transform function: (validatedValue) => newValue\n *\n * @example\n * // String to uppercase\n * const upper = v.coerce(v.string(), s => s.toUpperCase());\n *\n * @example\n * // Parse string to number\n * const parseNum = v.coerce(v.string(), s => parseInt(s, 10));\n * type Out = InferOutput<typeof parseNum>; // number\n *\n * @example\n * // Date to ISO string\n * const isoDate = v.coerce(v.date(), d => d.toISOString());\n * type Out = InferOutput<typeof isoDate>; // string\n *\n * @example\n * // Extract property from object\n * const getName = v.coerce(\n * v.object({ name: v.string(), age: v.number() }),\n * obj => obj.name\n * );\n * type Out = InferOutput<typeof getName>; // string\n */\nexport function coerce<S extends VibSchema<any, any>, TOut>(\n schema: S,\n fn: (value: S[\" vibInferred\"][\"1\"]) => TOut\n): TransformSchema<InferInput<S>, TOut> & { wrapped: S } {\n const transformSchema = createSchema<InferInput<S>, TOut>(\n \"transform\",\n (value): ValidationResult<TOut> => {\n const result = validateSchema(schema, value);\n // The wrapped schema's issues keep their paths: a refusal inside a\n // coerced object names the member that refused.\n if (result.issues) return { issues: result.issues };\n try {\n return ok(fn((result as { value: InferOutput<S> }).value));\n } catch (e) {\n return transformFail(e);\n }\n }\n ) as TransformSchema<InferInput<S>, TOut> & { wrapped: S };\n\n return withWrapped(transformSchema, schema);\n}\n\n/**\n * Alias for coerce - transform wrapper.\n */\nexport const map = coerce;\n","// Shorthand Coercion Schemas\n// Utilities for coercing simple values to structured objects\n\nimport type { VibSchema } from \"../types\";\nimport { coerce } from \"./transform\";\n\n/**\n * Coerces a value to a filter object with `equals` key.\n * Used for shorthand filter syntax: `\"value\"` -> `{ equals: \"value\" }`\n */\nexport const shorthandFilter = <S extends VibSchema>(schema: S) =>\n coerce(schema, (val: S[\" vibInferred\"][\"1\"]) => ({ equals: val }));\n\n/**\n * Coerces a value to an update object with `set` key.\n * Used for shorthand update syntax: `\"value\"` -> `{ set: \"value\" }`\n */\nexport const shorthandUpdate = <S extends VibSchema>(schema: S) =>\n coerce(schema, (val: S[\" vibInferred\"][\"1\"]) => ({ set: val }));\n\n/**\n * Coerces a single value to an array.\n * Used for shorthand array syntax: `\"value\"` -> `[\"value\"]`\n */\nexport const shorthandArray = <S extends VibSchema>(schema: S) =>\n coerce(\n schema,\n (val: S[\" vibInferred\"][\"1\"]) => [val] as [S[\" vibInferred\"][\"1\"]]\n );\n","// biome-ignore-all lint/suspicious/noBitwiseOperators: JS-domain bitmask dispatch.\nimport { discardAsyncValidationResult } from \"../parse-failure\";\nimport type {\n InferInput,\n InferOutput,\n ValidationIssue,\n ValidationResult,\n VibSchema,\n} from \"../types\";\nimport { isRecord } from \"../value-guards\";\nimport { createSchema, fail } from \"./helpers\";\n\n// =============================================================================\n// Union Schema\n// =============================================================================\n\nconst ASYNC_REFUSAL: readonly ValidationIssue[] = Object.freeze([\n Object.freeze({ message: \"Async schemas are not supported\" }),\n]);\n\nexport interface UnionSchema<\n TOptions extends readonly VibSchema<any, any>[],\n TInput = TOptions[number][\" vibInferred\"][\"0\"],\n TOutput = InferOutput<TOptions[number]>,\n> extends VibSchema<TInput, TOutput> {\n readonly type: \"union\";\n readonly options: TOptions;\n}\n\n/**\n * The tag of a TAGGED union: one key at which every member is an object whose\n * entry is a required literal, each a different one. A value carrying one of\n * those literals was written for that member alone.\n */\ninterface Tags {\n readonly key: string;\n readonly members: ReadonlyMap<unknown, VibSchema[\"~standard\"][\"validate\"]>;\n}\n\nfunction tagsOf(options: readonly VibSchema<any, any>[]): Tags | undefined {\n let key: string | undefined;\n const members = new Map<unknown, VibSchema[\"~standard\"][\"validate\"]>();\n for (const option of options) {\n const {\n type,\n entries,\n options: shape,\n } = option as {\n type?: string;\n entries?: Record<string, unknown>;\n options?: { array?: boolean; omit?: readonly string[] };\n };\n if (type !== \"object\" || !entries || shape?.array === true) return;\n key ??= Object.keys(entries).find((name) => isLiteral(entries[name]));\n const tag = key === undefined ? undefined : entries[key];\n if (!(isLiteral(tag) && tag.acceptsUndefined !== true)) return;\n if (members.has(tag.value) || shape?.omit?.includes(key!)) return;\n members.set(tag.value, option[\"~standard\"].validate);\n }\n return key === undefined || members.size < 2 ? undefined : { key, members };\n}\n\nfunction isLiteral(\n entry: unknown\n): entry is { type: \"literal\"; value: unknown; acceptsUndefined?: boolean } {\n return isRecord(entry) && entry.type === \"literal\";\n}\n\n// 1=string 2=number 4=boolean 8=array 16=object 32=other (null/undefined/bigint/fn/sym)\nconst D_ANY = 63;\nconst KIND: Record<string, number> = Object.assign(Object.create(null), {\n string: 1,\n enum: 1,\n number: 2,\n boolean: 4,\n array: 8,\n object: 16,\n});\n\nconst valueDomain = (v: unknown): number =>\n typeof v === \"object\"\n ? v === null\n ? 32\n : Array.isArray(v)\n ? 8\n : 16\n : (KIND[typeof v] ?? 32);\n\n/**\n * Sound JS-type bitmask of inputs `option` can accept. Unrecognized or\n * wrapper-opaque schemas return `D_ANY` so they always run.\n */\nfunction optionDomain(option: {\n type?: string;\n value?: unknown;\n wrapped?: object;\n options?: Record<string, unknown>;\n}): number {\n const { type } = option;\n if (type === \"transform\") return optionDomain(option.wrapped!);\n const base =\n type === \"literal\" ? valueDomain(option.value) : (type && KIND[type]) || 0;\n if (!base) return D_ANY;\n const o = option.options;\n return o\n ? (o.array ? 8 : base) |\n (o.nullable || o.optional || o.default !== undefined ? 32 : 0)\n : base;\n}\n\ntype MemberResult = ReturnType<VibSchema[\"~standard\"][\"validate\"]>;\n\n/** A member's result, an async member's promise being a refusal. */\nfunction settled<T>(result: MemberResult): ValidationResult<T> {\n if (!(\"then\" in result)) return result as ValidationResult<T>;\n discardAsyncValidationResult(result);\n return { issues: ASYNC_REFUSAL };\n}\n\n/** A member's first issue, spelled with its path for a refusal that lists several. */\nfunction describe({ message, path }: ValidationIssue): string {\n return path?.length ? `${path.join(\".\")}: ${message}` : message;\n}\n\n/**\n * Create a union schema that validates against multiple options.\n * Returns the result of the first matching schema.\n *\n * A refusal names the member the value was written for. In a tagged union\n * (every member an object with its own literal at one key) that is the member\n * its tag names, and only that member runs. Otherwise it is the member whose\n * first issue reads DEEPEST into the value (`{ gt: \"3\" }` is refused at `gt`\n * by the operator object, not at the root by the shorthand). Members that\n * refused equally deep leave no such member, and the refusal lists what each\n * one said, once (one issue, path kept, when they all said the same).\n *\n * @example\n * const stringOrNumber = v.union([v.string(), v.number()]);\n */\nexport function union<const TOptions extends readonly VibSchema<any, any>[]>(\n options: TOptions\n): UnionSchema<TOptions> {\n const validators = options.map((option) => option[\"~standard\"].validate);\n // Read on first use: a union nothing validates through never inspects its\n // members. Members whose entries are still unresolved thunks then read as\n // untagged for good, and the depth rule alone names the member.\n let tags: Tags | undefined | null = null;\n // JS-domain bitmask per member, read on first use like `tags`;\n // `undefined` when every member accepts any domain.\n let masks: readonly number[] | undefined | null = null;\n const schema = createSchema<\n InferInput<TOptions[number]>,\n InferOutput<TOptions[number]>\n >(\"union\", (value) => {\n if (tags === null) tags = tagsOf(options);\n const tagged = tags && isRecord(value) && tags.members.get(value[tags.key]);\n if (tagged) return settled<InferOutput<TOptions[number]>>(tagged(value));\n // Skip members whose accepted JS input domain cannot match `value` on the\n // fast path (e.g. scalar shorthand vs operator object, object vs array,\n // boolean vs relation node). If every compatible member refuses, the\n // refusal loop below still weighs every member in place so error reporting\n // stays identical.\n if (masks === null) {\n const computed = options.map(optionDomain);\n masks = computed.some((mask) => mask !== D_ANY) ? computed : undefined;\n }\n const kind = masks ? valueDomain(value) : 0;\n let refused: (readonly ValidationIssue[] | undefined)[] | undefined;\n if (masks) {\n for (let at = 0; at < validators.length; at++) {\n if ((masks[at]! & kind) === 0) continue;\n const result = settled<InferOutput<TOptions[number]>>(\n validators[at]!(value)\n );\n if (!result.issues) return result;\n (refused ??= [])[at] = result.issues;\n }\n }\n // Success returns the matching member's result as-is. Nothing about a\n // refusal is allocated until a second member refuses as deep as the first,\n // so the common \"first member misses, second matches\" pattern stays free.\n let deepest: readonly ValidationIssue[] | undefined;\n let depth = -1;\n let tied: string[] | undefined;\n\n for (let at = 0; at < validators.length; at++) {\n const result =\n masks && (masks[at]! & kind) !== 0\n ? { issues: refused![at]! }\n : settled<InferOutput<TOptions[number]>>(validators[at]!(value));\n if (!result.issues) return result;\n const { issues } = result;\n const reach = issues[0]!.path?.length ?? 0;\n if (reach > depth) {\n deepest = issues;\n depth = reach;\n tied = undefined;\n } else if (reach === depth) {\n const said = describe(issues[0]!);\n tied ??= [describe(deepest![0]!)];\n if (!tied.includes(said)) tied.push(said);\n }\n }\n\n if (tied && tied.length > 1) return fail(tied.join(\", or \"));\n return deepest ? { issues: deepest } : fail(\"Empty union\");\n }) as UnionSchema<TOptions>;\n\n (schema as any).options = options;\n\n return schema;\n}\n","// Single or Array Schema\n// Accepts either a single value or an array of values, normalizes to array\n\nimport type { VibSchema } from \"../types\";\nimport { array } from \"./array\";\nimport { coerce } from \"./transform\";\nimport { union } from \"./union\";\n\n/**\n * Creates a schema that accepts either a single value or an array of values.\n * Single values are coerced to a single-element array for consistent output.\n *\n * @example\n * const schema = v.singleOrArray(v.string());\n * // Accepts: \"foo\" -> [\"foo\"]\n * // Accepts: [\"foo\", \"bar\"] -> [\"foo\", \"bar\"]\n */\nexport const singleOrArray = <S extends VibSchema>(schema: S) =>\n union([coerce(schema, (v: S[\" vibInferred\"][\"1\"]) => [v]), array(schema)]);\n\nexport const termOrList = <S extends VibSchema>(schema: S) =>\n union([schema, array(schema)]);\n","import type {\n ComputeInput,\n ComputeOutput,\n ScalarOptions,\n VibSchema,\n} from \"../types\";\nimport { isString } from \"../value-guards\";\nimport { buildSchema, frozenFail, ok } from \"./helpers\";\n\n// =============================================================================\n// String Schema\n// =============================================================================\nexport interface StringSchema<TInput = string, TOutput = string>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"string\";\n}\n\n// Pre-computed error for fast path (avoid allocation on error)\nconst STRING_ERROR = /* @__PURE__ */ frozenFail(\"Expected string\");\n\n/**\n * Validate that a value is a string.\n */\nfunction validateString(value: unknown) {\n return isString(value) ? ok(value) : STRING_ERROR;\n}\n\n/**\n * Create a string schema.\n *\n * @example\n * const name = v.string();\n * const optionalName = v.string({ optional: true });\n * const tags = v.string({ array: true });\n */\nexport function string(): StringSchema<string, string>;\nexport function string<const Opts extends ScalarOptions<string, any>>(\n options: Opts\n): StringSchema<ComputeInput<string, Opts>, ComputeOutput<string, Opts>>;\nexport function string<\n const Opts extends ScalarOptions<string, any> | undefined,\n>(\n options?: Opts\n): StringSchema<ComputeInput<string, Opts>, ComputeOutput<string, Opts>> {\n return buildSchema(\"string\", validateString, options) as StringSchema<\n ComputeInput<string, Opts>,\n ComputeOutput<string, Opts>\n >;\n}\n\n// Export the validate function for reuse\nexport { validateString };\n","import type {\n ComputeInput,\n ComputeOutput,\n ScalarOptions,\n VibSchema,\n} from \"../types\";\nimport { isNumber } from \"../value-guards\";\nimport { buildSchema, fail, frozenFail, ok } from \"./helpers\";\n\n// =============================================================================\n// Vector Schema (array of numbers for embeddings/ML)\n// =============================================================================\n\nexport interface BaseVectorSchema<\n Opts extends ScalarOptions<number[], any> | undefined = undefined,\n> extends VibSchema<\n ComputeInput<number[], Opts>,\n ComputeOutput<number[], Opts>\n > {}\n\nexport interface VectorSchema<TInput = number[], TOutput = number[]>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"vector\";\n}\n\n// Pre-computed error for fast path\nconst NOT_ARRAY_ERROR = /* @__PURE__ */ frozenFail(\"Expected array of numbers\");\n\n/**\n * Validate that a value is a vector (array of numbers).\n * Optionally check for specific dimensions.\n */\nfunction createVectorValidator(dimensions?: number) {\n // Pre-compute dimension error if applicable\n const dimensionError =\n dimensions !== undefined\n ? frozenFail(`Expected vector of ${dimensions} dimensions`)\n : null;\n\n return (value: unknown) => {\n if (!Array.isArray(value)) return NOT_ARRAY_ERROR;\n\n const len = value.length;\n for (let i = 0; i < len; i++) {\n if (!(isNumber(value[i]) && Number.isFinite(value[i]))) {\n return fail(`Expected finite number at index ${i}`);\n }\n }\n\n if (dimensionError && len !== dimensions) return dimensionError;\n\n return ok(value as number[]);\n };\n}\n\n/**\n * Create a vector schema for arrays of numbers (embeddings, coordinates, etc.)\n *\n * @param dimensions - Optional fixed number of dimensions\n * @param options - Schema options\n *\n * @example\n * const embedding = v.vector(); // Any length\n * const embedding3d = v.vector(3); // Exactly 3 dimensions\n * const optionalVector = v.vector(undefined, { optional: true });\n */\nexport function vector<\n const Opts extends ScalarOptions<number[], any> | undefined = undefined,\n>(\n dimensions?: number,\n options?: Opts\n): VectorSchema<ComputeInput<number[], Opts>, ComputeOutput<number[], Opts>> & {\n dimensions?: number;\n} {\n const baseValidate = createVectorValidator(dimensions);\n return buildSchema(\"vector\", baseValidate, options, {\n dimensions,\n }) as VectorSchema<\n ComputeInput<number[], Opts>,\n ComputeOutput<number[], Opts>\n > & { dimensions?: number };\n}\n\n// Export validator for reuse\nexport { createVectorValidator as validateVector };\n","// =============================================================================\n// VibORM Validation - Runtime and Type-Level Namespace\n// =============================================================================\n\nimport type { JsonNullKind } from \"@schema/json-null\";\nimport type { ScalarType } from \"@schema/scalars/common\";\nimport type {\n ComputeInput,\n ComputeOutput,\n InferInput,\n InferOutput,\n ScalarOptions,\n VibSchema,\n} from \"../types\";\nimport type { ArraySchema } from \"./array\";\nimport { array } from \"./array\";\nimport type { BigIntSchema } from \"./bigint\";\nimport { bigint } from \"./bigint\";\nimport type { BlobSchema } from \"./blob\";\nimport { blob } from \"./blob\";\nimport type { BooleanSchema } from \"./boolean\";\nimport { boolean } from \"./boolean\";\nimport type { DateSchema } from \"./date\";\nimport { date } from \"./date\";\nimport type {\n DecimalComputeInput,\n DecimalComputeOutput,\n DecimalOptions,\n DecimalSchema,\n} from \"./decimal\";\nimport { decimal } from \"./decimal\";\nimport type { EnumSchema } from \"./enum\";\nimport { enum_ } from \"./enum\";\nimport type { ComputeEntriesFromObject } from \"./from-object\";\nimport { fromObject } from \"./from-object\";\nimport type { GeoPoint } from \"./geo-point-codec\";\nimport type { IsoDateSchema, IsoTimeSchema, IsoTimestampSchema } from \"./iso\";\nimport { isoDate, isoTime, isoTimestamp } from \"./iso\";\nimport type { JsonInput, JsonSchema, JsonValue } from \"./json\";\nimport { json } from \"./json\";\nimport type { JsonNullOrSchema, JsonWriteSchema } from \"./json-null\";\nimport { jsonNullOr, jsonWrite } from \"./json-null\";\nimport { lazy, lazyRef } from \"./lazy\";\nimport type { LiteralSchema, LiteralValue } from \"./literal\";\nimport { literal } from \"./literal\";\nimport type { NullableSchema } from \"./nullable\";\nimport { maybeNullable, nullable } from \"./nullable\";\nimport type { IntegerSchema, NumberSchema } from \"./number\";\nimport { integer, number } from \"./number\";\nimport type {\n ObjectOptions,\n ObjectSchema,\n OmittedObjectSchema,\n} from \"./object\";\nimport { object } from \"./object\";\nimport { omit } from \"./omit\";\nimport type {\n ComparisonOperandSchema,\n FieldRefOrSchema,\n NoFieldRefSchema,\n OperandCtx,\n} from \"./operand\";\nimport {\n comparisonOperand,\n fieldRefOr,\n noFieldRef,\n noOperandExpression,\n} from \"./operand\";\nimport type { OptionalSchema, WrappableSchema } from \"./optional\";\nimport { optional } from \"./optional\";\nimport type { PipeAction, PipeSchema } from \"./pipe\";\nimport { pipe, transform as transformAction } from \"./pipe\";\nimport type { PointSchema } from \"./point\";\nimport { point } from \"./point\";\nimport type { ComputeEntriesFromKeys, RecordSchema } from \"./record\";\nimport { fromKeys, record } from \"./record\";\nimport { refused } from \"./refused\";\nimport { shorthandArray, shorthandFilter, shorthandUpdate } from \"./shorthand\";\nimport { singleOrArray } from \"./single-or-array\";\nimport type { StringSchema } from \"./string\";\nimport { string } from \"./string\";\nimport type { TransformSchema } from \"./transform\";\nimport { coerce, map } from \"./transform\";\nimport type { UnionSchema } from \"./union\";\nimport { union } from \"./union\";\nimport type { VectorSchema } from \"./vector\";\nimport { vector } from \"./vector\";\n\ntype OmitOptions<\n TOptions extends ObjectOptions | undefined,\n TKeys extends readonly PropertyKey[] | undefined,\n> = (TOptions extends ObjectOptions ? Omit<TOptions, \"omit\"> : object) & {\n omit: TKeys;\n};\n\n// =============================================================================\n// Runtime Namespace (v.string(), v.number(), etc.)\n// =============================================================================\n\n/**\n * VibORM validation namespace.\n *\n * @example\n * import { v } from \"viborm/validation\";\n *\n * const user = v.object({\n * name: v.string(),\n * age: v.number({ optional: true }),\n * email: v.string(),\n * createdAt: v.date(),\n * });\n *\n * // Circular references use thunks\n * const node = v.object({\n * value: v.string(),\n * parent: () => node, // Thunk for self-reference\n * });\n */\nexport const v = {\n // Scalars\n string,\n number,\n integer,\n boolean,\n bigint,\n decimal,\n literal,\n enum: enum_,\n json,\n // Date & Time\n date,\n isoTimestamp,\n isoDate,\n isoTime,\n // Blob, Vector, Point\n blob,\n vector,\n point,\n // Wrappers\n array,\n nullable,\n maybeNullable,\n optional,\n // Objects\n object,\n omit,\n fromObject,\n // Composition\n union,\n pipe,\n transformAction,\n record,\n fromKeys,\n // Transform wrappers\n coerce,\n map,\n // Lazy evaluation\n lazy,\n lazyRef,\n // Single or array\n singleOrArray,\n // Shorthand coercions\n shorthandFilter,\n shorthandUpdate,\n shorthandArray,\n // Comparison operands: field references (Prisma FieldRef parity), SQL\n // fragments, and the callback that sugars both\n comparisonOperand,\n fieldRefOr,\n noFieldRef,\n noOperandExpression,\n // JSON null sentinels (Prisma DbNull/JsonNull/AnyNull parity)\n jsonNullOr,\n jsonWrite,\n // Keys that exist only to explain why they are refused\n refused,\n} as const;\n\nexport default v;\n\n// =============================================================================\n// Type-Level Namespace (V.String, V.Number, etc.)\n// =============================================================================\n\n/**\n * V Namespace - Type-level schema constructors for explicit type annotations.\n *\n * These mirror the runtime v.* functions but produce types directly without\n * needing to serialize the full schema structure in .d.ts files.\n *\n * @example\n * ```typescript\n * // In a .d.ts file:\n * import type { V } from \"@validation\";\n *\n * export type UserSchema = V.Object<{\n * id: V.String;\n * name: V.String<{ optional: true }>;\n * age: V.Number;\n * }>;\n * ```\n */\nexport namespace V {\n // =========================================================================\n // Scalar Types\n // =========================================================================\n\n /**\n * Type-level string schema.\n * @example V.String - Required string\n * @example V.String<{ optional: true }> - Optional string\n * @example V.String<{ nullable: true }> - Nullable string\n * @example V.String<{ array: true }> - Array of strings\n */\n export type String<\n Opts extends ScalarOptions<string, any> | undefined = undefined,\n > = StringSchema<ComputeInput<string, Opts>, ComputeOutput<string, Opts>>;\n\n /**\n * Type-level number schema.\n * @example V.Number - Required number\n * @example V.Number<{ optional: true }> - Optional number\n */\n export type Number<\n Opts extends ScalarOptions<number, any> | undefined = undefined,\n > = NumberSchema<ComputeInput<number, Opts>, ComputeOutput<number, Opts>>;\n\n /**\n * Type-level integer schema.\n */\n export type Integer<\n Opts extends ScalarOptions<number, any> | undefined = undefined,\n > = IntegerSchema<ComputeInput<number, Opts>, ComputeOutput<number, Opts>>;\n\n /**\n * Type-level decimal schema. Input and output differ on purpose: a decimal\n * accepts `Decimal | string` and validates to the canonical private\n * string every identity owner keys on. The public `Decimal` result is built\n * once per selected value at the typed result boundary, not here.\n * @example V.Decimal - Required decimal\n * @example V.Decimal<{ nullable: true }> - Nullable decimal\n * @example V.Decimal<{ decimal: { precision: 10; scale: 2 } }> - A declared domain\n */\n export type Decimal<\n Opts extends DecimalOptions<any> | undefined = undefined,\n > = DecimalSchema<DecimalComputeInput<Opts>, DecimalComputeOutput<Opts>>;\n\n /**\n * Type-level boolean schema.\n */\n export type Boolean<\n Opts extends ScalarOptions<boolean, any> | undefined = undefined,\n > = BooleanSchema<ComputeInput<boolean, Opts>, ComputeOutput<boolean, Opts>>;\n\n /**\n * Type-level bigint schema.\n */\n export type BigInt<\n Opts extends ScalarOptions<bigint, any> | undefined = undefined,\n > = BigIntSchema<ComputeInput<bigint, Opts>, ComputeOutput<bigint, Opts>>;\n\n // =========================================================================\n // Date & Time Types\n // =========================================================================\n\n /**\n * Type-level Date schema (JavaScript Date object).\n */\n export type Date<\n Opts extends ScalarOptions<globalThis.Date, any> | undefined = undefined,\n > = DateSchema<\n ComputeInput<globalThis.Date, Opts>,\n ComputeOutput<globalThis.Date, Opts>\n >;\n\n /**\n * Type-level ISO timestamp schema (accepts string | Date, outputs string).\n */\n export type IsoTimestamp<\n Opts extends ScalarOptions<string, any> | undefined = undefined,\n > = IsoTimestampSchema<\n ComputeInput<string | globalThis.Date, Opts>,\n ComputeOutput<string, Opts>\n >;\n\n /**\n * Type-level ISO date schema (accepts string | Date, outputs string YYYY-MM-DD).\n */\n export type IsoDate<\n Opts extends ScalarOptions<string, any> | undefined = undefined,\n > = IsoDateSchema<\n ComputeInput<string | globalThis.Date, Opts>,\n ComputeOutput<string, Opts>\n >;\n\n /**\n * Type-level ISO time schema (accepts string | Date, outputs string HH:MM:SS).\n */\n export type IsoTime<\n Opts extends ScalarOptions<string, any> | undefined = undefined,\n > = IsoTimeSchema<\n ComputeInput<string | globalThis.Date, Opts>,\n ComputeOutput<string, Opts>\n >;\n\n // =========================================================================\n // Special Types\n // =========================================================================\n\n /**\n * Type-level JSON schema.\n */\n export type Json<\n Opts extends ScalarOptions<JsonInput, any> | undefined = undefined,\n > = JsonSchema<ComputeInput<JsonInput, Opts>, ComputeOutput<JsonValue, Opts>>;\n\n /**\n * Type-level blob schema (Uint8Array or Buffer-like).\n */\n export type Blob<\n Opts extends ScalarOptions<Uint8Array, any> | undefined = undefined,\n > = BlobSchema<\n ComputeInput<Uint8Array, Opts>,\n ComputeOutput<Uint8Array, Opts>\n >;\n\n /**\n * Type-level vector schema (number array for embeddings).\n */\n export type Vector<\n Opts extends ScalarOptions<number[], any> | undefined = undefined,\n > = VectorSchema<ComputeInput<number[], Opts>, ComputeOutput<number[], Opts>>;\n\n /**\n * Type-level point schema (geographic coordinates).\n */\n export type Point<\n Opts extends ScalarOptions<GeoPoint, any> | undefined = undefined,\n > = PointSchema<ComputeInput<GeoPoint, Opts>, ComputeOutput<GeoPoint, Opts>>;\n\n // =========================================================================\n // Composition Types\n // =========================================================================\n\n /**\n * Type-level object schema.\n * @example V.Object<{ name: V.String; age: V.Number }>\n * @example V.Object<{ name: V.String }, { partial: false }> - All required\n */\n export type Object<\n TEntries,\n TOpts extends ObjectOptions | undefined = undefined,\n > = ObjectSchema<TEntries, TOpts>;\n\n /**\n * Type-level omit schema - creates a new object schema with keys removed.\n * @example V.Omit<UserSchema, [\"password\"]> - User without password field\n */\n export type Omit<\n TSchema extends ObjectSchema<any, any>,\n TKeys extends readonly (keyof TSchema[\"entries\"])[] | undefined,\n > = OmittedObjectSchema<\n TSchema[\"entries\"],\n OmitOptions<TSchema[\"options\"], TKeys>,\n TKeys\n >;\n\n /**\n * Type-level from object schema.\n * @example V.FromObject<{ name: V.String }, \"name\"> - Object with name field\n */\n export type FromObject<\n TObject extends Record<string, any>,\n TPath extends string,\n TOpts extends ObjectOptions | undefined = undefined,\n > = ObjectSchema<ComputeEntriesFromObject<TObject, TPath>, TOpts>;\n\n export type FromKeys<\n TKeys extends string[],\n TSchema extends VibSchema<any, any>,\n TOpts extends ObjectOptions | undefined = undefined,\n > = ObjectSchema<ComputeEntriesFromKeys<TKeys, TSchema>, TOpts>;\n\n /**\n * Type-level array schema.\n * @example V.Array<V.String> - Array of strings\n */\n export type Array<TItem extends VibSchema<any, any>> = ArraySchema<TItem>;\n\n /**\n * Type-level union schema.\n * @example V.Union<[V.String, V.Number]>\n */\n export type Union<TOptions extends readonly VibSchema<any, any>[]> =\n UnionSchema<TOptions>;\n\n /**\n * Type-level enum schema.\n * @example V.Enum<[\"active\", \"inactive\", \"pending\"]>\n */\n export type Enum<\n TValues extends readonly string[],\n Opts extends ScalarOptions<TValues[number], any> | undefined = undefined,\n > = EnumSchema<\n TValues,\n ComputeInput<TValues[number], Opts>,\n ComputeOutput<TValues[number], Opts>\n >;\n\n /**\n * Type-level literal schema.\n * @example V.Literal<\"active\">\n */\n export type Literal<TValue extends LiteralValue> = LiteralSchema<TValue>;\n\n /**\n * Type-level record schema (dictionary with uniform value type).\n * @example V.Record<V.String, V.Number>\n */\n export type VRecord<\n TKey extends VibSchema<any, string>,\n TValue extends VibSchema<any, any>,\n > = RecordSchema<TKey, TValue>;\n\n // =========================================================================\n // Wrapper Types\n // =========================================================================\n\n /**\n * Type-level optional schema.\n * @example V.Optional<V.String> - string | undefined\n */\n export type Optional<\n TWrapped extends WrappableSchema,\n TDefault = undefined,\n > = OptionalSchema<TWrapped, TDefault>;\n\n /**\n * Type-level nullable schema.\n * @example V.Nullable<V.String> - string | null\n */\n export type Nullable<TWrapped extends VibSchema<any, any>> =\n NullableSchema<TWrapped>;\n\n export type MaybeNullable<\n TWrapped extends VibSchema<any, any>,\n TIsNullable extends boolean,\n > = TIsNullable extends true ? NullableSchema<TWrapped> : TWrapped;\n\n // =========================================================================\n // Transform Types\n // =========================================================================\n\n /**\n * Type-level transform schema.\n * @example V.Transform<string, number> - transforms string input to number output\n */\n export type Transform<TInput, TOutput> = TransformSchema<TInput, TOutput>;\n\n /**\n * Type-level pipe schema for chaining validations.\n * @example V.Pipe<V.String, [TrimAction, LowercaseAction]>\n */\n export type Pipe<\n TSchema extends VibSchema<any, any>,\n TActions extends readonly PipeAction<any, any>[],\n > = PipeSchema<TSchema, TActions>;\n\n export type Coerce<\n TWrapped extends VibSchema<any, any>,\n TOutput,\n > = TransformSchema<InferInput<TWrapped>, TOutput> & { wrapped: TWrapped };\n\n export type ShorthandFilter<TWrapped extends VibSchema<any, any>> = Coerce<\n TWrapped,\n { equals: TWrapped[\" vibInferred\"][\"1\"] }\n >;\n export type ShorthandUpdate<TWrapped extends VibSchema<any, any>> = Coerce<\n TWrapped,\n { set: TWrapped[\" vibInferred\"][\"1\"] }\n >;\n export type ShorthandArray<TWrapped extends VibSchema<any, any>> = Coerce<\n TWrapped,\n [TWrapped[\" vibInferred\"][\"1\"]]\n >;\n\n /**\n * Type-level comparison operand that also accepts a field reference of the\n * given scalar type.\n * @example V.FieldRefOr<\"int\", V.Integer>\n */\n export type FieldRefOr<\n TType extends ScalarType,\n TSchema extends VibSchema<any, any>,\n > = FieldRefOrSchema<TType, TSchema>;\n\n /**\n * Type-level comparison operand: the value, a field reference of the given\n * scalar type, an SQL fragment, or a callback returning one of the latter two\n * from `TCtx` — the context of the model being filtered.\n * @example V.ComparisonOperand<\"int\", V.Integer, V.OperandCtx<typeof post>>\n */\n export type ComparisonOperand<\n TType extends ScalarType,\n TSchema extends VibSchema<any, any>,\n TCtx extends OperandCtx<any> = OperandCtx<any>,\n > = ComparisonOperandSchema<TType, TSchema, TCtx>;\n\n /**\n * Type-level operand callback context: `{ fields, sql }` keyed to the scalars\n * of the model being filtered.\n */\n export type Operand<TModel> = OperandCtx<TModel>;\n\n /**\n * Type-level re-closing wrapper: same shape as the wrapped schema, but a\n * field reference anywhere inside the parsed value is rejected.\n */\n export type NoFieldRef<TSchema extends VibSchema<any, any>> =\n NoFieldRefSchema<TSchema>;\n\n /**\n * Type-level JSON filter operand that also accepts the named JSON null\n * sentinels (`DbNull` / `JsonNull` / `AnyNull`).\n * @example V.JsonNullOr<\"DbNull\" | \"JsonNull\" | \"AnyNull\", V.Json>\n */\n export type JsonNullOr<\n TAllowed extends JsonNullKind,\n TSchema extends VibSchema<any, any>,\n > = JsonNullOrSchema<TAllowed, TSchema>;\n\n /**\n * Type-level JSON write slot: the sentinels in `TAllowed`, the whole JSON\n * document language, and no bare top-level `null` (Prisma's rule).\n */\n export type JsonWrite<\n TAllowed extends JsonNullKind,\n TSchema extends VibSchema<any, any>,\n > = JsonWriteSchema<TAllowed, TSchema>;\n\n export type SingleOrArray<TWrapped extends VibSchema<any, any>> = V.Union<\n readonly [\n V.Coerce<TWrapped, [TWrapped[\" vibInferred\"][\"1\"]]>,\n V.Array<TWrapped>,\n ]\n >;\n\n // =========================================================================\n // Utility Types\n // =========================================================================\n\n /**\n * Extract input type from a V.* type or VibSchema.\n */\n export type Input<T> = InferInput<T>;\n\n /**\n * Extract output type from a V.* type or VibSchema.\n */\n export type Output<T> = InferOutput<T>;\n\n /**\n * Any VibSchema - useful for generic constraints.\n */\n export type Schema<TInput = unknown, TOutput = TInput> = VibSchema<\n TInput,\n TOutput\n >;\n}\n","/**\n * What makes a model a database view: the facts `s.view` declares, held\n * beside the typed model state like `rawIndexes`. Every layer that must tell\n * a view from a table asks {@link viewFacts}; nothing else marks one.\n */\n\nimport type { TimeStep } from \"@validation/model/args/time-step\";\nimport type { AnyModel, ModelState } from \"../model\";\n\n/** An aggregate an aggregated view's column holds. */\nexport type ViewAggregate = \"_count\" | \"_avg\" | \"_sum\" | \"_min\" | \"_max\";\n\n/** Where one column of an aggregated view comes from. */\nexport interface ViewColumnOrigin {\n /** The source field it reads: absent for a count of rows. */\n readonly field?: string;\n /** The aggregate it holds of that field: absent for a grouped field. */\n readonly aggregate?: ViewAggregate;\n /** The time step a grouped field is taken by. */\n readonly step?: TimeStep;\n}\n\n/**\n * What makes a view aggregated: its query is what `groupBy` takes on its\n * source (`by`, `having`, `_count`, `_sum`, …), and its rows are groups.\n */\nexport interface AggregatedViewFacts {\n /** The grouped fields, in the order `by` lists them: the view's key when none is nullable. */\n readonly by: readonly string[];\n /**\n * Each column, by field name, in the order of the view's columns: a\n * grouped field under its own name, an aggregate under its own\n * (`count`, `sumAmount`, …).\n */\n readonly origins: Readonly<Record<string, ViewColumnOrigin>>;\n /**\n * The scalars and the compound key the view derived, which a source does\n * not hold: what its model's state may hold and nothing beside (W002).\n */\n readonly scalars: ModelState[\"scalars\"];\n readonly compoundId: ModelState[\"compoundId\"];\n}\n\nexport interface ViewFacts {\n /** The model or view whose rows this view reads. */\n readonly source: AnyModel;\n /** What `findMany` takes on the source, as declared; `groupBy` for an aggregated view. */\n readonly query: Readonly<Record<string, unknown>>;\n /**\n * The view's scalar columns, by field name: the source scalars the query\n * projects, in the source's order; an aggregated view's grouped fields and\n * aggregates, in its columns' order, a name twice where two columns take it\n * and a name with no scalar where it is longer than a column's (W004).\n */\n readonly columns: readonly string[];\n /**\n * The view's JSON columns, by name: each non-scalar selection of the query\n * (a relation, `_count`, `_aggregate`), in the order the query's projection\n * lists them. The one field written after `s.view`: the schema's\n * resolution settles a `_count: true` over a view source, whose inherited\n * relations it alone knows (`settleCount`).\n */\n documents: readonly string[];\n /**\n * Declared with `.materialized()`: the database stores the view's rows\n * (PostgreSQL's materialized view), so `.index()` may index its columns\n * and `$refresh()` recomputes them. Where a database has no such view it\n * is an ordinary one.\n */\n readonly materialized?: true;\n /**\n * Declared `.materialized({ refresh: \"auto\" })`: a table the database keeps\n * current from its source's writes, by triggers (SurrealDB keeps every view\n * so), on every database.\n */\n readonly refresh?: \"auto\";\n /** Present when the query groups the source's rows (`by`): see {@link AggregatedViewFacts}. */\n readonly aggregated?: AggregatedViewFacts;\n}\n\n/** The state of a view, at the type level: what `.materialized()` is called on. */\nexport interface DeclaredViewState {\n readonly view: object;\n}\n\n/** What `.materialized()` takes. */\nexport interface MaterializedOptions {\n /**\n * `\"auto\"`: the view is a table its source's triggers keep current at each\n * write, rather than rows `$refresh()` computes again.\n */\n readonly refresh?: \"auto\";\n}\n\n/** What `.materialized()` adds to a view's state, at the type level. */\nexport interface MaterializedViewState {\n readonly view: { readonly materialized: true };\n}\n\n/**\n * A view declared `.materialized()`, at the type level: the client types\n * `$refresh` on its delegate alone.\n */\nexport interface MaterializedView {\n readonly \"~\": { readonly state: MaterializedViewState };\n}\n\n/**\n * The source field whose values a view's column holds, read through\n * {@link ViewFacts.aggregated}: the column's own name in a view of rows; in\n * an aggregated view a grouped field's, or the one a `_min` or a `_max`\n * picks a value of; none for a count, a sum, an average or a period, which\n * hold values of their own.\n */\nexport function heldField(facts: ViewFacts, field: string): string | undefined {\n const origin = facts.aggregated?.origins[field];\n if (origin === undefined) return field;\n if (origin.step !== undefined) return;\n const { aggregate } = origin;\n return aggregate === undefined || aggregate === \"_min\" || aggregate === \"_max\"\n ? origin.field\n : undefined;\n}\n\n/** The view facts of `model`, or undefined when it is a table. */\nexport function viewFacts(model: AnyModel): ViewFacts | undefined {\n return (model[\"~\"].state as { view?: ViewFacts }).view;\n}\n\n/** The table `model` reads through every view it reads: itself for a table. */\nexport function viewTable(model: AnyModel): AnyModel {\n let table = model;\n for (let facts = viewFacts(table); facts; facts = viewFacts(table))\n table = facts.source;\n return table;\n}\n","// Common Scalar Utilities\n// Shared types and helpers for all scalar classes\n\nimport { ValidationError } from \"@errors\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { InferInput, VibSchema } from \"@validation\";\nimport type { DecimalDescriptor } from \"@validation/primitives/decimal-codec\";\nimport type { Scalar } from \"./base\";\nimport type { NativeTypeDeclaration } from \"./native-types\";\n\n// =============================================================================\n// SCHEMA NAMES (hydrated by client at initialization)\n// =============================================================================\n\n/**\n * Name slots for models, scalars, and relations.\n * These are hydrated by the client at initialization time when the full\n * schema context is available.\n *\n * - ts: TypeScript/schema key name (e.g., \"email\", \"User\")\n * - sql: Resolved database name (e.g., \"email_column\", \"users\")\n */\nexport interface SchemaNames {\n /** TypeScript key name in the schema */\n ts?: string;\n /** Resolved SQL name (column/table) */\n sql?: string;\n}\n\n/**\n * Hydrated schema names - guaranteed to have both ts and sql defined.\n * Returned by model[\"~\"].getFieldName() for scalar keys.\n */\nexport interface HydratedSchemaNames {\n /** TypeScript key name in the schema */\n ts: string;\n /** Resolved SQL name (column/table) */\n sql: string;\n}\n\n// =============================================================================\n// SCALAR TYPES\n// =============================================================================\n\nexport type ScalarType =\n | \"string\"\n | \"int\"\n | \"number\"\n | \"decimal\"\n | \"boolean\"\n | \"datetime\"\n | \"date\"\n | \"time\"\n | \"bigint\"\n | \"json\"\n | \"blob\"\n | \"vector\"\n | \"point\"\n | \"enum\";\n\nexport type AutoGenerateType =\n | \"uuid\"\n | \"uuidv7\"\n | \"ulid\"\n | \"ksuid\"\n | \"nanoid\"\n | \"cuid\"\n | \"increment\"\n | \"now\"\n | \"updatedAt\";\n\n/**\n * A generator declaration.\n *\n * `kind` is the only statement of which generator runs. `prefix` and `length`\n * are declaration facts the string generators otherwise bake into their default\n * closure, where nothing can read them back; state is their durable home so a\n * serializer can restate the declaration that produced the closure.\n * `increment`/`now`/`updatedAt` take neither.\n */\nexport interface AutoGenerate {\n kind: AutoGenerateType;\n prefix?: string | undefined;\n length?: number | undefined;\n /**\n * The caller did not NAME this format; `.id()` installed it.\n *\n * The distinction is what separates a key from a domain. `.ulid()` is an\n * assertion about every value the field will ever hold — which is what lets\n * VibORM admit those values, normalize their aliases and store them as\n * sixteen bytes. `.id()` is an assertion about the KEY, carrying a generator\n * so a caller need not supply one; the values it accepts are still whatever\n * a string column accepts, and it stores them as text. `.ulid().id()` says\n * both, and is a ULID key.\n *\n * It lives on the declaration record, beside `kind`, because it IS a fact\n * about how this generator came to be declared — not a second scalar state.\n */\n implicit?: boolean | undefined;\n /** Explicit generation choice; absent formats acquire a default only as IDs. */\n generate?: boolean | undefined;\n}\n\n/**\n * The closures the generator modifiers installed.\n *\n * A generator writes TWO facts: `autoGenerate`, which is the declaration, and\n * `default`, which is the closure that produces the value. A later\n * `.default(fn)` replaces only the second, so `autoGenerate !== undefined` is\n * not evidence that the closure standing in `default` is the generator's — and\n * a consumer that restates a declaration from state (the JSON serializer) would\n * otherwise silently substitute a random generator for a caller's own function.\n *\n * Identity is the only thing that distinguishes them, so identity is what is\n * recorded. One owner, beside the declaration it belongs to; nothing outside\n * the eight modifier writers may add to it.\n */\nconst GENERATOR_DEFAULTS = new WeakSet<object>();\n\n/** Mark a closure as the default a generator modifier installed. */\ndeclare const GENERATED_DEFAULT: unique symbol;\nexport interface GeneratorDefaultBrand {\n readonly [GENERATED_DEFAULT]: true;\n}\nexport function generatorDefault<F extends () => unknown>(\n closure: F\n): F & GeneratorDefaultBrand;\nexport function generatorDefault<F extends () => unknown>(closure: F) {\n GENERATOR_DEFAULTS.add(closure);\n return closure;\n}\n\n/** Shared construction-time refusal for schema builders. */\nexport function refuseBuilder(\n builder: string,\n path: string,\n message: string,\n cause?: Error\n): never {\n throw new ValidationError(\n { kind: \"schema-builder\", builder, path },\n [{ path, message }],\n cause === undefined ? undefined : { cause }\n );\n}\n\n/** A scalar generator cannot produce a complete list default. */\nexport function refuseListGenerator(builder: string): never {\n refuseBuilder(builder, \"array\", \"Scalar generation unsupported on lists\");\n}\n\n/** Shared rebase options for keyed/temporal scalars. */\nexport const rebaseOpts = <S extends ScalarState>(s: S) => ({\n nullable: s.nullable,\n array: s.array,\n schema: s.schema,\n});\n\n/** Shared state patch for `.increment()` on int and bigInt scalars. */\nexport const INCREMENT_STATE: {\n readonly hasDefault: true;\n readonly autoGenerate: { readonly kind: \"increment\" };\n readonly default: undefined;\n readonly disallowZero: true;\n readonly optional: true;\n} = {\n hasDefault: true,\n autoGenerate: { kind: \"increment\" },\n default: undefined,\n disallowZero: true,\n optional: true,\n};\n\n/** Nullable admission supplies null only when no default was already declared. */\nexport function nullableDefault<State extends ScalarState>(\n state: State\n): State[\"hasDefault\"] extends true ? State[\"default\"] : null;\nexport function nullableDefault(state: ScalarState) {\n return state.hasDefault ? state.default : null;\n}\n\n/** Whether this default value IS a generator's own installed closure. */\nexport function isGeneratorDefault(value: unknown): boolean {\n return typeof value === \"function\" && GENERATOR_DEFAULTS.has(value);\n}\n\n// =============================================================================\n// SCALAR STATE\n// =============================================================================\n\n/**\n * Complete state for a scalar instance.\n * This is the single generic that flows through the scalar class.\n */\n\nexport interface ScalarState<T extends ScalarType = ScalarType> {\n type: T;\n nullable: boolean;\n array: boolean;\n hasDefault: boolean;\n isId: boolean;\n isUnique: boolean;\n default: DefaultValue<any> | undefined;\n autoGenerate: AutoGenerate | undefined;\n /** Runtime create validation for portable auto-increment semantics. */\n disallowZero?: boolean;\n schema: StandardSchemaV1<any, any> | undefined;\n optional: boolean;\n /** Custom column name in the database (set via .map()) */\n columnName: string | undefined;\n base: VibSchema;\n withTimezone?: boolean | undefined;\n /**\n * The declared fixed-decimal domain, frozen at `s.decimal({...})`.\n *\n * It is the ONE source of truth for input validation, physical DDL, literal\n * encoding, result decoding, comparison and aggregate lowering, arithmetic\n * rounding and overflow, list-member encoding, and migration compatibility.\n * No adapter, driver, result parser, or migration component stores a second\n * precision or scale decision, and every modifier carries THIS object by\n * reference rather than rebuilding one.\n */\n decimal?: DecimalDescriptor | undefined;\n /** Fixed vector length for pgvector-backed vector scalars. */\n dimension?: number | undefined;\n /** Custom enum type name in the database (set via .name() on enum scalars) */\n enumName?: string | undefined;\n}\n\n// =============================================================================\n// STATE UPDATE HELPER\n// =============================================================================\n\n/**\n * Computes the new state type after applying an update.\n * Used by chainable methods to derive the return type.\n *\n * @example\n * nullable(): StringScalar<UpdateState<State, { nullable: true }>>\n */\nexport type UpdateState<\n State extends ScalarState,\n Update extends Partial<ScalarState>,\n> = Omit<State, keyof Update> & Update;\n\nexport const updateState = <\n F extends Scalar,\n const Update extends Partial<ScalarState>,\n>(\n scalar: F,\n update: Update\n) => {\n return { ...scalar[\"~\"].state, ...update } as UpdateState<\n F[\"~\"][\"state\"],\n Update\n >;\n};\n\n// =============================================================================\n// TYPE HELPERS\n// =============================================================================\n\n/**\n * Conditionally wraps a type with null\n */\nexport type MaybeNullable<\n T,\n Nullable extends boolean = false,\n> = Nullable extends true ? T | null : T;\n\n/**\n * Conditionally wraps a type as array\n */\nexport type MaybeArray<\n T,\n IsArray extends boolean = false,\n> = IsArray extends true ? T[] : T;\n\n/**\n * Type for default value - can be direct value or factory function\n */\nexport type DefaultValue<T> = T | (() => T);\n\n/**\n * The input accepted by the scalar's current base schema, or a factory for it.\n *\n * The base schema already owns the scalar's nullable and array wrappers. Adding\n * them again here turns a list default into a list of lists at the type level\n * (`string[][]` for `s.string().array()`), while runtime validation correctly\n * expects `string[]`. Read the one trusted shape instead of reconstructing it.\n */\nexport type DefaultValueInput<S extends ScalarState> = DefaultValue<\n InferInput<S[\"base\"]>\n>;\n\n// =============================================================================\n// DEFAULT STATE FACTORY\n// =============================================================================\n\n/** The factory's existing initial state stays named in exported model graphs. */\nexport interface InitialScalarState<T extends ScalarType, B extends VibSchema> {\n type: T;\n nullable: boolean;\n array: boolean;\n hasDefault: boolean;\n isId: boolean;\n isUnique: boolean;\n default: undefined;\n autoGenerate: undefined;\n disallowZero: boolean;\n schema: undefined;\n columnName: undefined;\n optional: boolean;\n withTimezone: boolean;\n base: B;\n}\n\n/**\n * Creates a default initial state for a scalar type\n */\nexport const createDefaultState = <T extends ScalarType, B extends VibSchema>(\n type: T,\n base: B\n): InitialScalarState<T, B> => ({\n type,\n nullable: false,\n array: false,\n hasDefault: false,\n isId: false,\n isUnique: false,\n default: undefined,\n autoGenerate: undefined,\n disallowZero: false,\n schema: undefined,\n columnName: undefined,\n optional: false,\n withTimezone: false,\n base,\n});\n\n// =============================================================================\n// INFER HELPERS (for type-level inference from state)\n// =============================================================================\n\n/**\n * Infers the base TypeScript type from a scalar state\n */\nexport type InferBaseType<\n BaseType,\n State extends ScalarState,\n> = State[\"array\"] extends true\n ? State[\"nullable\"] extends true\n ? (BaseType | null)[]\n : BaseType[]\n : State[\"nullable\"] extends true\n ? BaseType | null\n : BaseType;\n\n/**\n * Infers the create input type from a scalar state\n */\nexport type InferCreateType<\n BaseType,\n State extends ScalarState,\n> = State[\"hasDefault\"] extends true\n ? State[\"nullable\"] extends true\n ? BaseType | null | undefined\n : BaseType | undefined\n : State[\"nullable\"] extends true\n ? BaseType | null\n : BaseType;\n\n// =============================================================================\n// SCHEMA SHORTHANDS (re-exported from validation primitives)\n// =============================================================================\n\nexport {\n shorthandArray,\n shorthandFilter,\n shorthandUpdate,\n} from \"@validation/primitives/shorthand\";\n\n// =============================================================================\n// THE CHAIN EVERY SCALAR SHARES\n// =============================================================================\n\n/** The scalar a modifier answers: this one's state with what the modifier changes. */\nexport const next = (\n scalar: ScalarChain,\n update: Partial<ScalarState>,\n rebuilt = false\n) => {\n const state = { ...scalar.state, ...update };\n // The base validator follows from the state: no modifier builds it itself.\n if (rebuilt) state.base = scalar.rebase(state);\n // The scalar a modifier answers is of the class that says how its base is\n // built, whatever the receiver is an instance of: a subclass's constructor\n // is not asked to carry a state it may not take.\n let concrete = Object.getPrototypeOf(scalar);\n while (!Object.hasOwn(concrete, \"rebase\"))\n concrete = Object.getPrototypeOf(concrete);\n return new concrete.constructor(state, scalar._nativeType);\n};\n\n/**\n * The modifiers every scalar has, written once. Each scalar class types them\n * for its own state and says how its base validator is built from a state.\n */\nabstract class ScalarChain {\n readonly state: ScalarState;\n readonly _nativeType?: NativeTypeDeclaration | undefined;\n #internal?: {\n state: ScalarState;\n nativeType: NativeTypeDeclaration | undefined;\n };\n\n constructor(state: ScalarState, _nativeType?: NativeTypeDeclaration) {\n this.state = state;\n this._nativeType = _nativeType;\n }\n abstract rebase(state: ScalarState): VibSchema;\n nullable() {\n return next(\n this,\n {\n nullable: true,\n hasDefault: true,\n default: nullableDefault(this.state),\n optional: true,\n },\n true\n );\n }\n default(value: unknown) {\n return next(this, { hasDefault: true, default: value, optional: true });\n }\n map(columnName: string) {\n return next(this, { columnName });\n }\n get [\"~\"]() {\n return (this.#internal ??= {\n state: this.state,\n nativeType: this._nativeType,\n });\n }\n}\n\n/** The chain of a scalar that can be a list. */\nabstract class ListScalarChain extends ScalarChain {\n array() {\n return next(this, { array: true }, true);\n }\n}\n\n/** The chain of a scalar that can be a key and can carry a custom schema. */\nexport abstract class KeyedScalarChain extends ListScalarChain {\n id() {\n return next(this, { isId: true, isUnique: true });\n }\n unique() {\n return next(this, { isUnique: true });\n }\n schema(schema: StandardSchemaV1<any, any>) {\n return next(this, { schema }, true);\n }\n}\n\n/**\n * A chain as a scalar class extends it. The class types the members for its\n * own state; what it inherits here is one type for every scalar and state,\n * so a schema's fields cost a consumer's compiler nothing more.\n */\nexport declare abstract class TypedScalarChain {\n /** The base validator of a scalar in this state. */\n protected abstract rebase(state: any): VibSchema;\n}\ntype Chain = abstract new <State>(\n state: State,\n nativeType?: NativeTypeDeclaration\n) => TypedScalarChain;\n/**\n * The list chain with its members left untyped, for a class that types them\n * as methods of its own and hands their work back with `super`.\n */\nexport declare abstract class UntypedScalarChain extends TypedScalarChain {\n nullable(): unknown;\n array(): unknown;\n default(value: unknown): unknown;\n map(columnName: string): unknown;\n}\nexport const untypedListScalarChain =\n ListScalarChain as unknown as abstract new <State>(\n state: State,\n nativeType?: NativeTypeDeclaration\n ) => UntypedScalarChain;\n/** The keyed chain, untyped in the same way. */\nexport declare abstract class UntypedKeyedScalarChain extends UntypedScalarChain {\n id(): unknown;\n unique(): unknown;\n schema(schema: StandardSchemaV1<any, any>): unknown;\n}\nexport const untypedKeyedScalarChain =\n KeyedScalarChain as unknown as abstract new <State>(\n state: State,\n nativeType?: NativeTypeDeclaration\n ) => UntypedKeyedScalarChain;\nexport const scalarChain = ScalarChain as unknown as Chain;\nexport const listScalarChain = ListScalarChain as unknown as Chain;\nexport const keyedScalarChain = KeyedScalarChain as unknown as Chain;\n\n/**\n * A scalar of `scalar`'s class, in its state with `update` applied and its\n * base validator rebuilt: a column a schema object derives from a declared\n * one (an aggregated view's, `s.view`), built as a modifier builds one.\n */\nexport const derivedScalar = (\n scalar: Scalar,\n update: Partial<ScalarState>\n): Scalar => next(scalar as unknown as ScalarChain, update, true);\n","// Shared immutable-terminal machinery: the construction-time refusal vocabulary\n// and the source-independent target once-cell.\n//\n// Every structurally knowable fact about a declaration is decided HERE or in the\n// factory/modifier that owns it, before the value enters trusted relation state.\n// Facts that need the schema graph — is the settled return a registered model,\n// which endpoint owns the foreign key, does the pair exist — belong to the\n// full-schema relation resolver and are deliberately absent.\n\nimport { isValidSchemaIdentifier } from \"../identifier\";\nimport { refuseBuilder } from \"../scalars/common\";\nimport type {\n JunctionReferentialAction,\n JunctionSideActions,\n NonEmptyFieldTuple,\n ReferentialAction,\n} from \"./types\";\n\n/** The builder label carried by every construction-time refusal. */\nexport type RelationBuilder = \"s.toOne\" | \"s.toMany\" | \"s.model\";\n\nexport function refuseRelationInput(\n builder: RelationBuilder,\n path: string,\n message: string,\n cause?: Error\n): never {\n refuseBuilder(builder, path, message, cause);\n}\n\n// =============================================================================\n// PLAIN-RECORD READS\n// =============================================================================\n\n/**\n * A caller-supplied map is a variant declaration only when it is a plain\n * record: a hostile prototype would otherwise smuggle inherited entries past\n * own-key enumeration into schema truth.\n */\nexport function isPlainRecord(\n value: unknown\n): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\n/**\n * Own ENUMERABLE string keys — the declaration surface of a record. Symbol keys\n * and inherited entries are not declarations, and neither is an own key hidden\n * behind `enumerable: false`.\n */\nexport function declaredKeys(record: Record<string, unknown>): string[] {\n return Object.keys(record);\n}\n\n/** Exactly these keys, in any order. */\nexport function hasExactKeys(\n actual: readonly string[],\n expected: readonly string[]\n): boolean {\n return (\n actual.length === expected.length &&\n expected.every((key) => actual.includes(key))\n );\n}\n\n/**\n * Read one caller-owned property exactly once. Accessors are executable input:\n * when one throws, the declaration boundary owns the V4002 refusal and keeps a\n * normalized cause instead of leaking the caller's thrown value.\n */\nexport function readCallerProperty(\n builder: RelationBuilder,\n record: Record<string, unknown>,\n property: string,\n path: string\n): unknown {\n try {\n return Reflect.get(record, property);\n } catch (thrown) {\n refuseRelationInput(\n builder,\n path,\n `Could not read '${path}'`,\n normalizeThrown(thrown, `Reading '${path}' threw non-Error`)\n );\n }\n}\n\nexport function normalizeRelationName(\n builder: RelationBuilder,\n name: unknown\n): string {\n if (typeof name !== \"string\" || !name)\n refuseRelationInput(builder, \"name\", \"Relation name required\");\n return name;\n}\n\nexport function normalizeReferentialAction(\n path: string,\n action: unknown\n): ReferentialAction {\n if (\n action === \"cascade\" ||\n action === \"setNull\" ||\n action === \"restrict\" ||\n action === \"noAction\"\n ) {\n return action;\n }\n refuseRelationInput(\"s.toOne\", path, \"Invalid referential action\");\n}\n\nfunction normalizeJunctionAction(\n path: string,\n action: unknown\n): JunctionReferentialAction {\n if (action === \"cascade\" || action === \"restrict\" || action === \"noAction\") {\n return action;\n }\n refuseRelationInput(\"s.toMany\", path, \"Invalid junction action\");\n}\n\nexport function normalizeJunctionActions(\n path: \"onDelete\" | \"onUpdate\",\n declared: unknown\n): JunctionSideActions {\n if (typeof declared !== \"object\" || declared === null) {\n const action = normalizeJunctionAction(path, declared);\n return Object.freeze({ source: action, target: action });\n }\n if (\n !(\n isPlainRecord(declared) &&\n hasExactKeys(declaredKeys(declared), [\"source\", \"target\"])\n )\n ) {\n refuseRelationInput(\n \"s.toMany\",\n path,\n `'${path}' must be { source, target }`\n );\n }\n const side = (name: \"source\" | \"target\"): JunctionReferentialAction =>\n normalizeJunctionAction(\n `${path}.${name}`,\n readCallerProperty(\"s.toMany\", declared, name, `${path}.${name}`)\n );\n return Object.freeze({ source: side(\"source\"), target: side(\"target\") });\n}\n\nexport function normalizeJunctionToken(path: string, token: unknown): string {\n if (!isValidSchemaIdentifier(token))\n refuseRelationInput(\"s.toMany\", path, `Invalid '${path}' identifier`);\n return token;\n}\n\nexport function normalizeFieldTuple(\n builder: RelationBuilder,\n path: string,\n fields: readonly string[]\n): NonEmptyFieldTuple {\n const [head, ...rest] = fields;\n if (head === undefined)\n refuseRelationInput(builder, path, `'${path}' requires a field`);\n if (new Set(fields).size !== fields.length)\n refuseRelationInput(builder, path, `'${path}' has duplicate field`);\n return [head, ...rest];\n}\n\n// =============================================================================\n// TARGET SETTLEMENT\n// =============================================================================\n\ntype SettledTarget = readonly [1, unknown] | readonly [0, Error];\n\nexport function createTargetSettlement(\n readGetter: (variantKey: string | undefined) => unknown\n): (variantKey?: string) => unknown {\n const cells = new Map<string, SettledTarget>();\n return (variantKey?: string): unknown => {\n const cellKey = variantKey ?? \"\";\n let cell = cells.get(cellKey);\n if (cell === undefined) {\n cell = settleTargetOnce(readGetter, variantKey);\n cells.set(cellKey, cell);\n }\n if (cell[0] === 1) return cell[1];\n throw cell[1];\n };\n}\n\nfunction settleTargetOnce(\n readGetter: (variantKey: string | undefined) => unknown,\n variantKey: string | undefined\n): SettledTarget {\n const getter = readGetter(variantKey);\n if (typeof getter !== \"function\")\n return [0, new Error(\"Relation target must be a function\")];\n try {\n return [1, getter()];\n } catch (thrown) {\n return [0, normalizeThrown(thrown, \"Relation target threw\")];\n }\n}\n\n/**\n * One normalization, owned here: a thrown `Error` keeps its identity across\n * every consumer, and a non-Error throw becomes exactly one `Error` that every\n * consumer then shares.\n */\nfunction normalizeThrown(thrown: unknown, nonErrorPrefix: string): Error {\n if (thrown instanceof Error) return thrown;\n let rendered: string;\n try {\n rendered = typeof thrown === \"symbol\" ? thrown.toString() : String(thrown);\n } catch {\n rendered = \"<unrenderable non-Error value>\";\n }\n return new Error(`${nonErrorPrefix}: ${rendered}`);\n}\n","// Variant target domains: the normalization owner and the two variant terminals.\n//\n// \"Polymorphic\" is not a relation family. It is the derived observation that a\n// declaration's TARGET DOMAIN holds named variants instead of one model, which\n// is why the two variant terminals are reached through the same `s.toOne` /\n// `s.toMany` factories as the model-target ones. What is irreducibly different\n// is the legal local configuration: a row-held variant to-one may be\n// `.optional()` and owns no public foreign key, and a member-junction variant\n// to-many names one junction per variant through an exact `.through(...)` map.\n\nimport type { Model } from \"@schema/model\";\nimport type { Scalar } from \"@schema/scalars/base\";\nimport { isValidSchemaIdentifier } from \"../identifier\";\nimport {\n createTargetSettlement,\n declaredKeys,\n hasExactKeys,\n isPlainRecord,\n normalizeRelationName,\n type RelationBuilder,\n readCallerProperty,\n refuseRelationInput,\n} from \"./terminal\";\nimport type {\n AnyRelation,\n Getter,\n RelationInternal,\n Replace,\n VariantEntry,\n VariantJunctionOverride,\n VariantManyEntry,\n VariantToManyState,\n VariantToOneState,\n} from \"./types\";\n\n/**\n * The stored-discriminator grammar. A stored value is written to a physical\n * column and read back by migrations and predicates, so it admits namespaced\n * and versioned spellings the public variant key does not.\n */\nconst STORED_VALUE = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,190}$/;\n\nconst THROUGH_ENTRY_KEYS = [\"table\", \"source\", \"target\"] as const;\n\n// =============================================================================\n// FACTORY-LEVEL TYPES\n// =============================================================================\n\nexport type VariantGetterMap = Readonly<Record<string, Getter>>;\n\n/**\n * The map overload's phantom refusal.\n *\n * It is NOT redundant with {@link GetterOnly}. With the map overload first and\n * an unconstrained getter overload second, a structurally-map argument that\n * fails this guard would otherwise fall through to the getter overload, whose\n * conditional return answers `never` — and `never` is assignable to a model\n * shape, so the refusal would disappear entirely. This guard uniquely owns\n * \"structurally a map, but not a legal variant map\"; `GetterOnly` uniquely owns\n * \"not a map at all and not a getter\".\n */\nexport type VariantMapGuard<Entries> = string extends keyof Entries\n ? {\n readonly \"a variant map needs literal keys, not a string index signature\": never;\n }\n : [keyof Entries] extends [never]\n ? { readonly \"a variant map needs at least one variant\": never }\n : unknown;\n\nexport type VariantOptions<Entries> = {\n readonly values: { readonly [Key in keyof Entries]: string };\n};\n\n/**\n * The whole options bag is exact, not only `values`: a NON-FRESH bag with a\n * sibling key beside `values` sails through excess-property checking, so the\n * unknown keys are refused structurally.\n */\nexport type ExactVariantOptions<Options, Entries> = Options extends undefined\n ? unknown\n : Record<Exclude<keyof Options, \"values\">, never> & {\n readonly values: Record<\n Exclude<\n keyof (Options extends { readonly values: infer Values }\n ? Values\n : never),\n keyof Entries\n >,\n never\n >;\n };\n\n/**\n * Normalized entries carry the getter's exact type and a plain `string` stored\n * value: the stored discriminator is runtime storage, never a public result\n * discriminator, so carrying its literal would be a public type parameter no\n * consumer reads.\n */\nexport type NormalizedOneEntries<Entries> = {\n readonly [Key in keyof Entries]: {\n readonly getter: Entries[Key];\n readonly storedValue: string;\n };\n};\n\nexport type NormalizedManyEntries<Entries> = {\n readonly [Key in keyof Entries]: {\n readonly getter: Entries[Key];\n readonly storedValue: string;\n readonly junction?: VariantJunctionOverride;\n };\n};\n\ntype VariantEntriesOfState<State> = State extends {\n readonly target: { readonly entries: infer Entries };\n}\n ? Entries\n : never;\n\ntype VariantThroughMap<Entries> = {\n readonly [Key in keyof Entries]: VariantJunctionOverride;\n};\n\ntype ExactVariantThroughMap<Given, Entries> = Record<\n Exclude<keyof Given, keyof Entries>,\n never\n> & {\n readonly [Key in keyof Given]: Record<\n Exclude<keyof Given[Key], keyof VariantJunctionOverride>,\n never\n >;\n};\n\n// =============================================================================\n// TERMINAL CAPABILITY SURFACES\n// =============================================================================\n\n/** A slot that holds at most one membership across its variants. */\nexport type VariantToOneRelation<State> = {\n readonly \"~\": RelationInternal<State>;\n name<const Name extends string>(\n name: Name\n ): VariantToOneRelation<Replace<State, { readonly name: Name }>>;\n optional(): VariantToOneRelation<Replace<State, { readonly optional: true }>>;\n};\n\n/**\n * A slot that holds a collection across its variants. No `.optional()`: an\n * empty collection is already the empty case.\n */\nexport type VariantToManyRelation<State> = {\n readonly \"~\": RelationInternal<State>;\n name<const Name extends string>(\n name: Name\n ): VariantToManyRelation<Replace<State, { readonly name: Name }>>;\n through<\n const ThroughMap extends VariantThroughMap<VariantEntriesOfState<State>>,\n >(\n map: ThroughMap &\n ExactVariantThroughMap<ThroughMap, VariantEntriesOfState<State>>\n ): VariantToManyRelation<State>;\n};\n\n// =============================================================================\n// NORMALIZATION\n// =============================================================================\n\n/**\n * Read the target map and its options ONCE, judge every structurally knowable\n * fact, and build the single normalized entry map. There is no separately\n * stored `targets`, `values` or `through` map to keep in sync.\n *\n * Every own property at both map levels is read exactly once here and pinned as\n * a plain value: a live accessor could otherwise answer validation with one\n * value and the storage builder with another. Reading a property's value does\n * not invoke a target thunk; getters are stored as functions and stay lazy.\n */\nexport function normalizeVariantEntries(\n builder: RelationBuilder,\n variants: unknown,\n options: unknown\n): Readonly<Record<string, VariantEntry>> {\n function fail(path: string, msg: string): never {\n refuseRelationInput(builder, path, msg);\n }\n if (!isPlainRecord(variants)) fail(\"target\", \"Invalid target\");\n const variantKeys = declaredKeys(variants);\n if (variantKeys.length === 0) fail(\"target\", \"Empty variant map\");\n const storedValues = readStoredValues(builder, variantKeys, options);\n const entries: Record<string, VariantEntry> = {};\n for (const k of variantKeys) {\n if (!isValidSchemaIdentifier(k))\n fail(`target.${k}`, `Invalid variant '${k}'`);\n const getter = readCallerProperty(builder, variants, k, `target.${k}`);\n if (typeof getter !== \"function\")\n fail(`target.${k}`, `Variant '${k}' must be a getter`);\n entries[k] = Object.freeze({\n getter,\n storedValue: storedValues[k] ?? k,\n });\n }\n return Object.freeze(entries);\n}\n\nconst exactRecord = (\n v: unknown,\n keys: readonly string[]\n): v is Record<string, unknown> =>\n isPlainRecord(v) && hasExactKeys(declaredKeys(v), keys);\n\nfunction readStoredValues(\n builder: RelationBuilder,\n variantKeys: readonly string[],\n options: unknown\n): Record<string, string> {\n if (options === undefined) return {};\n function fail(path: string, msg: string): never {\n refuseRelationInput(builder, path, msg);\n }\n if (!exactRecord(options, [\"values\"])) fail(\"options\", \"Expected { values }\");\n const values = readCallerProperty(\n builder,\n options,\n \"values\",\n \"options.values\"\n );\n if (!isPlainRecord(values)) fail(\"options.values\", \"Expected plain record\");\n if (!hasExactKeys(declaredKeys(values), variantKeys))\n fail(\"options.values\", `Must match ${renderKeys(variantKeys)}`);\n const storedValues: Record<string, string> = {};\n const claimed = new Set<string>();\n for (const k of variantKeys) {\n const v = readCallerProperty(builder, values, k, `options.values.${k}`);\n if (typeof v !== \"string\" || !STORED_VALUE.test(v))\n fail(`options.values.${k}`, `Invalid value for '${k}'`);\n if (claimed.has(v)) fail(`options.values.${k}`, `Duplicate value '${v}'`);\n claimed.add(v);\n storedValues[k] = v;\n }\n return storedValues;\n}\n\nfunction renderKeys(keys: readonly string[]): string {\n return `[${keys.map((key) => `'${key}'`).join(\", \")}]`;\n}\n\nfunction foldMemberJunctions(\n entries: Readonly<Record<string, VariantEntry>>,\n through: unknown\n): Readonly<Record<string, VariantManyEntry>> {\n const variantKeys = Object.keys(entries);\n if (!isPlainRecord(through))\n refuseRelationInput(\"s.toMany\", \"through\", \"Expected plain map\");\n if (!hasExactKeys(declaredKeys(through), variantKeys))\n refuseRelationInput(\n \"s.toMany\",\n \"through\",\n `Must match ${renderKeys(variantKeys)}`\n );\n const folded: Record<string, VariantManyEntry> = {};\n for (const [k, entry] of Object.entries(entries)) {\n const override = readCallerProperty(\"s.toMany\", through, k, `through.${k}`);\n folded[k] = Object.freeze({\n ...entry,\n junction: readJunctionOverride(k, override),\n });\n }\n return Object.freeze(folded);\n}\n\nfunction readJunctionOverride(\n variantKey: string,\n override: unknown\n): VariantJunctionOverride {\n const path = `through.${variantKey}`;\n function fail(msg: string): never {\n refuseRelationInput(\"s.toMany\", path, msg);\n }\n if (!isPlainRecord(override))\n fail(`Junction '${variantKey}' requires { table, source, target }`);\n const read = (k: string) =>\n readCallerProperty(\"s.toMany\", override, k, `${path}.${k}`);\n const table = read(\"table\");\n const source = read(\"source\");\n const target = read(\"target\");\n if (\n !hasExactKeys(declaredKeys(override), THROUGH_ENTRY_KEYS) ||\n typeof table !== \"string\" ||\n typeof source !== \"string\" ||\n typeof target !== \"string\"\n )\n fail(`Invalid junction '${variantKey}'`);\n return Object.freeze({ table, source, target });\n}\n\n// =============================================================================\n// TERMINALS\n// =============================================================================\n\nclass VariantTerminal<S extends VariantToOneState | VariantToManyState> {\n protected readonly state: S;\n readonly #internal: RelationInternal<S>;\n\n constructor(state: S) {\n this.state = Object.freeze(state);\n this.#internal = Object.freeze({\n state: this.state,\n settleTarget: createTargetSettlement((k) =>\n k === undefined ? undefined : this.state.target.entries[k]?.getter\n ),\n });\n }\n\n get \"~\"(): RelationInternal<S> {\n return this.#internal;\n }\n}\n\nclass VariantToOne extends VariantTerminal<VariantToOneState> {\n name(name: string): VariantToOne {\n return new VariantToOne({\n ...this.state,\n name: normalizeRelationName(\"s.toOne\", name),\n });\n }\n\n optional(): VariantToOne {\n return new VariantToOne({ ...this.state, optional: true });\n }\n}\n\nclass VariantToMany extends VariantTerminal<VariantToManyState> {\n name(name: string): VariantToMany {\n return new VariantToMany({\n ...this.state,\n name: normalizeRelationName(\"s.toMany\", name),\n });\n }\n\n through(map: unknown): VariantToMany {\n return new VariantToMany({\n ...this.state,\n target: {\n kind: \"variants\",\n entries: foldMemberJunctions(this.state.target.entries, map),\n },\n });\n }\n}\n\n/** Construct the row-held variant terminal for `s.toOne`. */\nexport function variantToOneTerminal(state: VariantToOneState): AnyRelation {\n return new VariantToOne(state);\n}\n\n/** Construct the member-junction variant terminal for `s.toMany`. */\nexport function variantToManyTerminal(state: VariantToManyState): AnyRelation {\n return new VariantToMany(state);\n}\n\n// =============================================================================\n// RESOLVED VARIANT STORAGE COLUMN\n// =============================================================================\n// Resolution OUTPUT, not declaration state: one private column the variant\n// row-storage owner derives, carried on the resolved edge and read by the\n// serializer and the engine. The descriptors that used to sit beside it are\n// gone — the resolved edge IS the topology, and a second copy of it on the\n// model was a second answer to every question the edge already answers.\n\nexport interface PolymorphicStorageColumn {\n readonly name: string;\n readonly scalar: Scalar;\n readonly nullable: boolean;\n /**\n * The KEY this private column stands in for, when it stands in for one.\n *\n * A row carrier's id column holds every variant's primary key, and what\n * those keys hold — an identifier domain above all — may be DERIVED rather\n * than declared: the ordinary one-to-one child whose primary key IS its\n * parent foreign key declares nothing and still holds uuids. The scalar\n * alone cannot answer that (derivation is keyed by model and field, never by\n * a scalar instance two models may share), so the column carries the pair\n * the one lookup takes. Every variant's key agrees on the answer or the\n * carrier does not exist — that agreement is what the identifier-domain\n * derivation refuses when it fails — so the FIRST member's key is the\n * carrier's key.\n *\n * The type discriminator column stands in for no key and carries none.\n */\n readonly reference?: {\n readonly model: Model<any>;\n readonly field: string;\n };\n}\n","// `s.toOne` — one of the two relation factories.\n//\n// The factory states the SLOT CARDINALITY (one) and its argument states the\n// TARGET DOMAIN (one model, or named variants). Which endpoint owns a foreign\n// key, whether the pair is one-to-one or many-to-one, and whether a model-target\n// slot may be empty are DERIVED later by the full-schema topology owner.\n\nimport {\n type ExactVariantOptions,\n type NormalizedOneEntries,\n normalizeVariantEntries,\n type VariantGetterMap,\n type VariantMapGuard,\n type VariantOptions,\n type VariantToOneRelation,\n variantToOneTerminal,\n} from \"./polymorphic\";\nimport {\n createTargetSettlement,\n normalizeFieldTuple,\n normalizeReferentialAction,\n normalizeRelationName,\n refuseRelationInput,\n} from \"./terminal\";\nimport type {\n AnyRelation,\n ForeignKeyDeclaration,\n Getter,\n GetterOnly,\n ModelToOneState,\n NonEmptyFieldTuple,\n ReferentialAction,\n RelationInternal,\n Replace,\n} from \"./types\";\n\n// =============================================================================\n// TERMINAL CAPABILITY SURFACE\n// =============================================================================\n\n/**\n * Referential actions exist only once a complete reference exists — they act on\n * a foreign key, and there is no foreign key to act on before\n * `.references(...)` completes the pair.\n */\ntype ForeignKeyActions<State> = {\n onDelete<const Action extends ReferentialAction>(\n action: Action\n ): ModelToOneRelation<\n State extends { readonly foreignKey: infer FK }\n ? Replace<\n State,\n { readonly foreignKey: Replace<FK, { onDelete: Action }> }\n >\n : State\n >;\n onUpdate<const Action extends ReferentialAction>(\n action: Action\n ): ModelToOneRelation<\n State extends { readonly foreignKey: infer FK }\n ? Replace<\n State,\n { readonly foreignKey: Replace<FK, { onUpdate: Action }> }\n >\n : State\n >;\n};\n\ntype ModelToOneCapabilities<State> = {\n readonly \"~\": RelationInternal<State>;\n name<const Name extends string>(\n name: Name\n ): ModelToOneRelation<Replace<State, { readonly name: Name }>>;\n fields<const Fields extends NonEmptyFieldTuple>(\n ...fields: Fields\n ): ReferencesStage<State, Fields>;\n};\n\n/**\n * A model-target singular slot. It exposes no `.optional()`: emptiness follows\n * from the nullability of a complete local foreign-key tuple, and a non-owning\n * singular view is derived nullable.\n */\nexport type ModelToOneRelation<State> = ModelToOneCapabilities<State> &\n (State extends { readonly foreignKey: ForeignKeyDeclaration }\n ? ForeignKeyActions<State>\n : unknown);\n\n/**\n * The transient value `.fields(...)` returns.\n *\n * It carries NO relation brand, so neither `ModelShape` nor any downstream\n * relation consumer can mistake an incomplete foreign key for trusted schema\n * state, and `s.model(...)` refuses it outright. It exposes only\n * `.references(...)` and `.name(...)`: a name must not be able to turn an\n * incomplete pair into schema truth.\n */\nexport type ReferencesStage<State, Fields extends NonEmptyFieldTuple> = {\n references<\n const References extends NonEmptyFieldTuple & {\n readonly length: Fields[\"length\"];\n },\n >(\n ...references: References\n ): ModelToOneRelation<\n Replace<\n State,\n {\n readonly foreignKey: Replace<\n State extends { readonly foreignKey: infer FK } ? FK : unknown,\n { readonly fields: Fields; readonly references: References }\n >;\n }\n >\n >;\n name<const Name extends string>(\n name: Name\n ): ReferencesStage<Replace<State, { readonly name: Name }>, Fields>;\n};\n\n// =============================================================================\n// PRIVATE TERMINALS\n// =============================================================================\n\nclass ModelToOne {\n readonly #state: ModelToOneState;\n readonly #internal: RelationInternal<ModelToOneState>;\n\n constructor(state: ModelToOneState) {\n this.#state = Object.freeze(state);\n this.#internal = Object.freeze({\n state: this.#state,\n settleTarget: createTargetSettlement(() => this.#state.target.getter),\n });\n }\n\n name(name: string): ModelToOne {\n return new ModelToOne({\n ...this.#state,\n name: normalizeRelationName(\"s.toOne\", name),\n });\n }\n\n fields(...fields: string[]): PendingReferences {\n return new PendingReferences(\n this.#state,\n normalizeFieldTuple(\"s.toOne\", \"fields\", fields)\n );\n }\n\n onDelete(action: ReferentialAction): ModelToOne {\n return this.#withForeignKeyAction(\"onDelete\", action);\n }\n\n onUpdate(action: ReferentialAction): ModelToOne {\n return this.#withForeignKeyAction(\"onUpdate\", action);\n }\n\n /**\n * The type surface hides both action setters until `.references(...)` has\n * completed a foreign key. This refusal covers the route a type pin cannot:\n * a JavaScript caller placing a referential action on a slot that owns no\n * foreign key, where the action would otherwise have nowhere to be stored and\n * would be silently dropped.\n */\n #withForeignKeyAction(\n action: \"onDelete\" | \"onUpdate\",\n value: ReferentialAction\n ): ModelToOne {\n const foreignKey = this.#state.foreignKey;\n if (foreignKey === undefined) {\n refuseRelationInput(\n \"s.toOne\",\n action,\n `'${action}' requires \\`.fields().references()\\` first`\n );\n }\n return new ModelToOne({\n ...this.#state,\n foreignKey: Object.freeze({\n ...foreignKey,\n [action]: normalizeReferentialAction(action, value),\n }),\n });\n }\n\n get \"~\"(): RelationInternal<ModelToOneState> {\n return this.#internal;\n }\n}\n\n/**\n * The transient references stage. It has no `\"~\"` accessor by design: that\n * absence is what makes an incomplete chain unusable as a model member.\n */\nclass PendingReferences {\n readonly #state: ModelToOneState;\n readonly #localFields: NonEmptyFieldTuple;\n\n constructor(state: ModelToOneState, localFields: NonEmptyFieldTuple) {\n this.#state = state;\n this.#localFields = localFields;\n }\n\n name(name: string): PendingReferences {\n return new PendingReferences(\n { ...this.#state, name: normalizeRelationName(\"s.toOne\", name) },\n this.#localFields\n );\n }\n\n references(...references: string[]): ModelToOne {\n const referenced = normalizeFieldTuple(\"s.toOne\", \"references\", references);\n if (referenced.length !== this.#localFields.length)\n refuseReferenceArity(referenced.length, this.#localFields.length);\n // Completing a second stage replaces the pair atomically and preserves the\n // endpoint's name and referential actions; the prior terminal is untouched.\n const prior = this.#state.foreignKey;\n const foreignKey: ForeignKeyDeclaration = {\n fields: this.#localFields,\n references: referenced,\n ...(prior?.onDelete === undefined ? {} : { onDelete: prior.onDelete }),\n ...(prior?.onUpdate === undefined ? {} : { onUpdate: prior.onUpdate }),\n };\n return new ModelToOne({\n ...this.#state,\n foreignKey: Object.freeze(foreignKey),\n });\n }\n}\n\n/**\n * Is this model member a transient references stage?\n *\n * Deliberately nominal: a stage is only ever produced by `.fields(...)`, so an\n * `instanceof` test cannot be spoofed by a look-alike record, and the\n * `s.model(...)` boundary can refuse the one member shape that would otherwise\n * be silently dropped.\n */\nexport function isReferencesStage(value: unknown): boolean {\n return value instanceof PendingReferences;\n}\n\n// =============================================================================\n// FACTORY\n// =============================================================================\n\n/**\n * Declare a slot that holds AT MOST ONE membership.\n *\n * The map overload is declared first so a variant map is never swallowed by the\n * broad getter overload. Dispatch examines only the argument representation and\n * never invokes a getter.\n */\nexport function toOne<\n const Entries extends VariantGetterMap,\n const Options extends VariantOptions<Entries> | undefined = undefined,\n>(\n variants: Entries & VariantMapGuard<Entries>,\n options?: Options & ExactVariantOptions<Options, Entries>\n): VariantToOneRelation<{\n readonly kind: \"relation\";\n readonly cardinality: \"one\";\n readonly target: {\n readonly kind: \"variants\";\n readonly entries: NormalizedOneEntries<Entries>;\n };\n}>;\nexport function toOne<const G>(getter: G & GetterOnly<G>): G extends Getter\n ? ModelToOneRelation<{\n readonly kind: \"relation\";\n readonly cardinality: \"one\";\n readonly target: { readonly kind: \"model\"; readonly getter: G };\n }>\n : never;\nexport function toOne(target: unknown, options?: unknown): AnyRelation {\n if (typeof target === \"function\") {\n // biome-ignore lint/complexity/noArguments: distinguishes omission from explicit undefined without changing the factory's public arity\n if (arguments.length > 1) {\n refuseRelationInput(\n \"s.toOne\",\n \"options\",\n \"Model-target relation takes one argument\"\n );\n }\n return new ModelToOne({\n kind: \"relation\",\n cardinality: \"one\",\n target: { kind: \"model\", getter: target },\n });\n }\n return variantToOneTerminal({\n kind: \"relation\",\n cardinality: \"one\",\n target: {\n kind: \"variants\",\n entries: normalizeVariantEntries(\"s.toOne\", target, options),\n },\n });\n}\n\nfunction refuseReferenceArity(referenced: number, local: number): never {\n return refuseRelationInput(\n \"s.toOne\",\n \"references\",\n `\\`.references()\\` has ${referenced} field(s), expected ${local}`\n );\n}\n","import { emptyRecord } from \"@schema/record\";\nimport type { AnyRelation } from \"@schema/relation\";\nimport { refuseRelationInput } from \"@schema/relation/terminal\";\n// Deep import: the references-stage predicate is the `s.model(...)` boundary's\n// own instrument and is deliberately not part of the relation package surface.\nimport { isReferencesStage } from \"@schema/relation/to-one\";\nimport type { Scalar } from \"@schema/scalars/base\";\n\n/**\n * Record of model fields - the canonical type for scalar and relation definitions.\n * A model field is either a scalar or a relation; ONE relation map holds both\n * target domains.\n */\nexport type AnyModelField = Scalar | AnyRelation;\nexport type ModelShape = Record<string, AnyModelField>;\n\n/**\n * The shape `s.model(...)` and `.extends(...)` accept: a model shape with no\n * member named `_count`, `_aggregate` or `_distance`, the names a selection's\n * own outputs reserve (relation counts and aggregates, a distance). This is\n * the compile-time spelling of\n * rule F010 for TypeScript callers; F010 (`memberNamesAreNotReserved`) stays\n * the contract for every caller. It constrains keys only and never reads a\n * member's type, so it cannot change what a shape infers. Each key's type is\n * its reason spelled as a string literal, so the diagnostic a caller reads\n * names it: no model member is a string, so nothing a shape can hold\n * satisfies it. `$through` is a selection's own key too, refused at runtime as\n * no identifier (F001); this names the reason a caller would otherwise guess at.\n */\nexport type DeclaredModelShape = ModelShape & {\n readonly _count?: \"`_count` is reserved for relation counts (F010)\";\n readonly _aggregate?: \"`_aggregate` is reserved for relation aggregates (F010)\";\n readonly _distance?: \"`_distance` is reserved for distance results (F010)\";\n readonly $through?: \"`$through` is reserved for a relation's link row (F010)\";\n};\n\nexport type NameFromKeys<\n TFields extends string[],\n TName extends string = \"\",\n> = TFields extends readonly [\n infer F extends string,\n ...infer R extends string[],\n]\n ? R extends []\n ? `${TName}_${F}`\n : NameFromKeys<R, TName extends \"\" ? F : `${TName}_${F}`>\n : never;\n\nexport interface CompoundConstraint<\n TFields extends string[],\n TName extends string | undefined = undefined,\n> {\n fields: TFields;\n name: TName extends undefined ? NameFromKeys<TFields> : TName;\n}\n\n/** Any compound constraint (for loose typing) */\nexport type AnyCompoundConstraint = CompoundConstraint<string[]>;\n\nexport type ToString<T> = T extends\n | string\n | number\n | bigint\n | boolean\n | null\n | undefined\n ? `${T}`\n : never;\n\nexport type StringKeyOf<T extends Record<string, any>> = {\n [K in keyof T]: K extends string ? K : never;\n}[keyof T];\n\nexport type ScalarKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends Scalar ? ToString<K> : never;\n}[keyof T];\n\n/** Fixed-decimal list keys, which have value semantics but no key semantics. */\nexport type DecimalListScalarKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends Scalar\n ? T[K][\"~\"][\"state\"] extends { type: \"decimal\"; array: true }\n ? ToString<K>\n : never\n : never;\n}[keyof T];\n\n/** GeoPoint keys have value semantics but no portable key/order semantics. */\nexport type PointScalarKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends Scalar\n ? T[K][\"~\"][\"state\"][\"type\"] extends \"point\"\n ? ToString<K>\n : never\n : never;\n}[keyof T];\n\nexport type NonNullablePointScalarKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends Scalar\n ? T[K][\"~\"][\"state\"][\"type\"] extends \"point\"\n ? T[K][\"~\"][\"state\"][\"nullable\"] extends true\n ? never\n : ToString<K>\n : never\n : never;\n}[keyof T];\n\nexport type NonPointScalarKeys<T extends ModelShape> = Exclude<\n ScalarKeys<T>,\n string extends keyof T ? never : PointScalarKeys<T>\n>;\n\n/** Scalar keys except fixed-decimal lists, which cannot be physical keys. */\nexport type NonDecimalListScalarKeys<T extends ModelShape> = Exclude<\n ScalarKeys<T>,\n string extends keyof T ? never : DecimalListScalarKeys<T>\n>;\n\n/** Scalar keys admitted in IDs, unique constraints, and foreign-key identity. */\nexport type PortableKeyScalarKeys<T extends ModelShape> = Exclude<\n NonDecimalListScalarKeys<T>,\n string extends keyof T ? never : PointScalarKeys<T>\n>;\n\n/** Extract relation keys from ModelState */\nexport type RelationKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends AnyRelation ? ToString<K> : never;\n}[keyof T];\n\nexport type RequiredScalarKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends Scalar\n ? T[K][\"~\"][\"state\"][\"optional\"] extends true\n ? never\n : ToString<K>\n : never;\n}[keyof T];\n\nexport type UniqueScalarKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends Scalar\n ? T[K][\"~\"][\"state\"][\"isId\"] extends true\n ? ToString<K>\n : T[K][\"~\"][\"state\"][\"isUnique\"] extends true\n ? ToString<K>\n : never\n : never;\n}[keyof T];\n\n/** Numeric scalar types for aggregations (avg, sum) */\nexport type NumericScalarType = \"int\" | \"number\" | \"decimal\" | \"bigint\";\n\n/** Extract keys of numeric scalars from a ModelShape */\nexport type NumericScalarKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends Scalar\n ? T[K][\"~\"][\"state\"][\"array\"] extends true\n ? never\n : T[K][\"~\"][\"state\"][\"type\"] extends NumericScalarType\n ? ToString<K>\n : never\n : never;\n}[keyof T];\n\nexport type ScalarMap<T extends ModelShape> = {\n [K in ScalarKeys<T>]: T[K] extends Scalar ? T[K] : never;\n};\n\nexport type RelationMap<T extends ModelShape> = {\n [K in RelationKeys<T>]: T[K] extends AnyRelation ? T[K] : never;\n};\n\nexport type UniqueScalarMap<T extends ModelShape> = {\n [K in UniqueScalarKeys<T>]: T[K] extends Scalar ? T[K] : never;\n};\n\n/**\n * ONE relation boundary, keyed on the internal brand.\n *\n * Trusted relation state originates only in `s.toOne` / `s.toMany`, and both\n * target domains carry `kind: \"relation\"` — so a model has one relation map and\n * no consumer has to ask which family a member belongs to. Scalars keep\n * `state.type`, so the two brands cannot collide.\n */\nconst SCALAR_TYPES = new Set<string>([\n \"string\",\n \"int\",\n \"number\",\n \"decimal\",\n \"boolean\",\n \"datetime\",\n \"date\",\n \"time\",\n \"bigint\",\n \"json\",\n \"blob\",\n \"vector\",\n \"point\",\n \"enum\",\n]);\n\nfunction internalState(value: unknown): object | undefined {\n if (\n (typeof value !== \"object\" || value === null) &&\n typeof value !== \"function\"\n )\n return undefined;\n const internal = Reflect.get(value, \"~\");\n if (typeof internal !== \"object\" || internal === null) return undefined;\n const state = Reflect.get(internal, \"state\");\n return typeof state === \"object\" && state !== null ? state : undefined;\n}\n\nfunction isScalar(value: unknown, state: object): value is Scalar {\n const type = Reflect.get(state, \"type\");\n return typeof type === \"string\" && SCALAR_TYPES.has(type);\n}\n\nfunction isRelation(value: unknown, state: object): value is AnyRelation {\n return Reflect.get(state, \"kind\") === \"relation\";\n}\n\n/** Classify a model shape into its scalar, relation, and unique-scalar maps in one pass. */\nexport const classifyShape = <T extends ModelShape>(fields: T) => {\n const scalars = emptyRecord<Scalar>();\n const relations = emptyRecord<AnyRelation>();\n const uniques = emptyRecord<Scalar>();\n for (const [key, value] of Object.entries(fields)) {\n const state = internalState(value);\n if (state !== undefined) {\n if (isScalar(value, state)) {\n scalars[key] = value;\n if (value[\"~\"].state.isUnique || value[\"~\"].state.isId)\n uniques[key] = value;\n continue;\n }\n if (isRelation(value, state)) {\n relations[key] = value;\n continue;\n }\n }\n if (isReferencesStage(value)) {\n refuseRelationInput(\n \"s.model\",\n key,\n `Relation '${key}' started \\`.fields(...)\\` without \\`.references(...)\\``\n );\n }\n }\n return {\n scalars: scalars as ScalarMap<T>,\n relations: relations as RelationMap<T>,\n uniques: uniques as UniqueScalarMap<T>,\n };\n};\n\nexport const getNameFromKeys = <\n Name extends string | undefined,\n TFields extends any[],\n>(\n name: Name,\n fields: TFields\n) => {\n return (\n name ??\n (fields.join(\"_\") as Name extends undefined ? NameFromKeys<TFields> : Name)\n );\n};\n","// Model Class Implementation\n// Defines database models with scalars and relations\n\nimport type { ObjectSchema, VibSchema } from \"@validation\";\nimport v from \"@validation/primitives/v\";\nimport { isRecord } from \"@validation/value-guards\";\nimport { emptyRecord, put, stateOf } from \"../record\";\nimport type { AnyRelation } from \"../relation\";\nimport type { Scalar } from \"../scalars/base\";\nimport type { HydratedSchemaNames, SchemaNames } from \"../scalars/common\";\nimport {\n type DeclaredViewState,\n type MaterializedOptions,\n type MaterializedViewState,\n viewFacts,\n} from \"../view/facts\";\nimport {\n classifyShape,\n type DeclaredModelShape,\n getNameFromKeys,\n type ModelShape,\n type NameFromKeys,\n type NonNullablePointScalarKeys,\n type PortableKeyScalarKeys,\n type RelationMap,\n type ScalarMap,\n type StringKeyOf,\n type UniqueScalarMap,\n} from \"./helper\";\n// Re-export types from helpers for external use\n\n// =============================================================================\n// TYPE INFERENCE HELPER\n// =============================================================================\n\nexport interface ModelState {\n shape: ModelShape;\n compoundId:\n | Record<string, ObjectSchema<Record<string, VibSchema>>>\n | undefined;\n compoundUniques:\n | Record<string, ObjectSchema<Record<string, VibSchema>>>\n | undefined;\n tableName: string | undefined;\n indexes: IndexDefinition[];\n omit: Record<string, true> | undefined;\n scalars: Record<string, Scalar>;\n /** ONE canonical relation map, holding both target domains in shape order. */\n relations: Record<string, AnyRelation>;\n uniques: Record<string, Scalar>;\n}\n\n/** Initial model projections stay named when a consumer emits recursive graphs. */\nexport interface InitialModelState<Shape extends ModelShape>\n extends ModelState {\n shape: Shape;\n scalars: ScalarMap<Shape>;\n relations: RelationMap<Shape>;\n uniques: UniqueScalarMap<Shape>;\n omit: undefined;\n}\n\n/**\n * Internal accessor return type for Model[\"~\"]\n * Explicit type annotation to avoid TS7056 (type too complex to serialize)\n */\nexport interface ModelInternal<T extends ModelState> {\n state: T;\n names: SchemaNames;\n nameRegistry: {\n fields: Map<string, SchemaNames>;\n };\n getFieldName: (key: string) => HydratedSchemaNames;\n /** Cached scalar field names (computed once on first access) */\n scalarFieldNames: string[];\n /** Cached relation names (computed once on first access) */\n relationNames: string[];\n /** Indexes in the database's own language: see {@link Model.rawIndex}. */\n readonly rawIndexes: readonly RawIndexDefinition[];\n /** SQLite clusters the table by its primary key: see {@link Model.withoutRowid}. */\n readonly withoutRowid: boolean;\n}\n\n/**\n * The index kinds a schema may declare. The union is the whole of what any\n * dialect accepts, not what all of them accept — `validateIndexType` in\n * `migrations/drivers/base.ts` refuses each one on the dialects whose\n * `supportsIndexTypes` does not list it, by name, at push time.\n *\n * `fulltext` and `spatial` are here because MySQL's whole round trip already\n * exists and only this union could not spell it: the emitter writes the\n * `FULLTEXT`/`SPATIAL` prefix and refuses to combine either with `UNIQUE`\n * (`mysql/index.ts`), the introspection reads them back and normalizes MySQL's\n * `RTREE` to `spatial` (`mysql/introspect.ts`), the migration snapshot's\n * `IndexDef` already carries both (`migrations/types.ts`), and the capability\n * list already declares them. See Phase 10 item 6 in\n * `docs/architecture/query-performance-plan.md`.\n */\nexport type IndexType =\n | \"btree\"\n | \"hash\"\n | \"gin\"\n | \"gist\"\n | \"fulltext\"\n | \"spatial\";\n\nexport interface IndexOptions {\n name?: string;\n unique?: boolean;\n type?: IndexType;\n where?: string; // For partial indexes (PostgreSQL)\n}\n\ntype OrdinaryIndexOptions = Omit<IndexOptions, \"type\"> & {\n type?: Exclude<IndexType, \"spatial\">;\n};\n\ntype GeoPointSpatialIndexOptions = {\n name?: string;\n type: \"spatial\";\n unique?: never;\n where?: never;\n};\n\n/**\n * One index per dialect, written in that database's own language, for what the\n * index declaration cannot say (pgvector's HNSW, SurrealDB's HNSW, an expression).\n * Each text is a template: `{name}`, `{table}` and `{<field>}` become the driver's\n * escaped identifiers, the table qualified by the bound namespace. A dialect\n * without a text has no such index.\n */\nexport interface RawIndexTemplates {\n pg?: string;\n mysql?: string;\n sqlite?: string;\n surrealdb?: string;\n}\n\nexport interface RawIndexDefinition {\n readonly name: string;\n readonly templates: Readonly<RawIndexTemplates>;\n}\n\nexport interface IndexDefinition<\n Keys extends string[] = string[],\n O extends IndexOptions = IndexOptions,\n> {\n fields: Keys;\n options: O;\n}\n\n/** A partial index cannot constrain rows excluded by its predicate. */\nexport function isTotalIndex(options: Pick<IndexOptions, \"where\">): boolean {\n return !options.where;\n}\n\nexport type UpdateIndexDefinition<\n State extends ModelState,\n Index extends IndexDefinition,\n> = [...State[\"indexes\"], Index];\n\n/** The name a compound `.id()` / `.unique()` constraint may be given. */\nexport interface CompoundKeyOptions {\n name?: string;\n}\n\n/**\n * An options bag that carries the surface's own keys and NOTHING else.\n *\n * A generic `O extends Options` is no guard on its own: when inference produces\n * a bag the constraint would reject, TypeScript CLAMPS `O` to the constraint and\n * only excess-property checking is left to catch the stray key — and that needs\n * a fresh object literal, so `.index([\"a\"], sharedIndexOptions)` sails through\n * with `uniqu: true` recorded as nothing at all. Demanding `never` for the\n * unknown keys refuses structurally instead, whatever the argument's freshness.\n * Same instrument as `UnknownOmitKeys` below.\n */\ntype ExactOptions<Given, Allowed> = Given &\n Record<Exclude<keyof Given, keyof Allowed>, never>;\n\n/**\n * The constraint name: the caller's `name` when they gave one, otherwise the\n * underscore-joined field names. Read off the options bag rather than a separate\n * inferred parameter so that ONE type parameter carries the whole literal — the\n * parameter `ExactOptions` needs in order to see the unknown keys.\n */\ntype CompoundKeyName<\n Keys extends string[],\n O extends CompoundKeyOptions,\n> = O extends { name: infer N extends string } ? N : NameFromKeys<Keys>;\n\nexport const mergeIndexDefinitions = <\n State extends ModelState,\n Index extends IndexDefinition,\n>(\n state: State,\n index: Index\n): UpdateIndexDefinition<State, Index> => {\n return [...state.indexes, index] as UpdateIndexDefinition<State, Index>;\n};\n\n// Publish the same completed state as fluent returns so a legacy explicit\n// Model<UpdateState<...>> annotation retains exact relation-link identity.\nexport type UpdateState<\n State extends ModelState,\n Update extends Partial<ModelState>,\n> = {\n [P in keyof (Omit<State, keyof Update> & Update)]: (Omit<\n State,\n keyof Update\n > &\n Update)[P];\n};\n\n/**\n * The keys a proposed `.omit()` names that this model does NOT have as a\n * scalar: the typos and the relation names.\n *\n * `Hidden` is inferred from the argument's own keys and is deliberately NOT\n * constrained to the scalar names. A constrained type parameter is no guard\n * here: when inference produces something the constraint rejects, TypeScript\n * silently CLAMPS the parameter to the constraint and only excess-property\n * checking — which needs a fresh object literal — is left to catch the bad\n * key. Anything non-fresh (`as const`, a spread, an annotated variable, a\n * widened `Record<string, true>`) then sails through and records a\n * hidden-column claim nobody wrote. Excluding the unknown keys and demanding\n * `never` for them refuses structurally instead, whatever the argument's\n * freshness, and a `never` the caller cannot produce is a compile error at the\n * offending key.\n *\n * Relations are absent from the accepted set because `State[\"scalars\"]` is the\n * scalar half of the shape (`ScalarMap`), the same source `.index()` /\n * `.id()` / `.unique()` key off. Reading it never touches a relation's\n * `getter`, the member that must not be resolved while two model consts still\n * refer to each other (see `RelationState.getter`).\n */\ntype UnknownOmitKeys<Hidden extends string, State extends ModelState> = Exclude<\n Hidden,\n StringKeyOf<State[\"scalars\"]>\n>;\n\n/**\n * This model's scalar names, each optionally flagged `true`.\n *\n * It carries NO refusal — `UnknownOmitKeys` does that — and it adds no\n * requirement, every key being optional. It is in the parameter for one\n * reason: an editor offers the keys of a CONCRETE contextual type, and\n * `Record<Hidden, true>` is not concrete until `Hidden` has been inferred from\n * the very literal being typed. Without this member `.omit({ ` autocompletes\n * the global scope; with it, the model's scalars.\n */\nexport type ModelOmitInput<State extends ModelState> = Partial<\n Record<StringKeyOf<State[\"scalars\"]>, true>\n>;\n\n/**\n * Merge a new compound constraint into the existing record so repeated\n * .id()/.unique() calls accumulate instead of replacing each other.\n * Resolves to just `Added` when nothing was set yet.\n */\ntype MergeCompound<Existing, Added> = Added &\n (Existing extends Record<string, ObjectSchema<Record<string, VibSchema>>>\n ? Existing\n : unknown);\n\n/**\n * Resolve compound-key members to their base schemas, refusing any name that\n * is not a scalar of the model AT THE DECLARING SITE. The typed surface\n * already refuses these names; this throw is the runtime backstop for\n * untyped callers and JSON documents (the document interpreter relocates it\n * onto the `ids[]`/`uniques[]` node that wrote it), and it must fire on the\n * rule-free paths (`serializeModels`, `generate`,\n * `push({ skipValidation: true })`) that never run the advisory rules. I003\n * keeps its own coverage: post-construction shape drift (`.extends()`\n * shadowing a key member) is invisible to this constructor.\n *\n * A module function rather than a `Model` method: adding members to the class\n * perturbs how TS compares mutually-recursive model instantiations.\n */\nfunction compoundMembers(\n state: ModelState,\n fields: readonly string[],\n label: string\n): Record<string, VibSchema> {\n refuseDuplicateModelKeyMembers(fields, label);\n const members = emptyRecord<VibSchema>();\n for (const fieldName of fields) {\n // `in` is exact here: both maps come from the extractors, which build\n // prototype-free records, so no key can resolve an inherited member.\n const scalar =\n fieldName in state.scalars ? state.scalars[fieldName] : undefined;\n if (!scalar) {\n throw new Error(\n fieldName in state.relations\n ? `${label} field '${fieldName}' is a relation`\n : `${label} field '${fieldName}' does not exist`\n );\n }\n put(members, fieldName, stateOf(scalar).base);\n }\n return members;\n}\n\nfunction withCompound(\n state: ModelState,\n slot: \"compoundId\" | \"compoundUniques\",\n label: \"Compound ID\" | \"Compound unique\",\n fields: readonly string[],\n options: CompoundKeyOptions | undefined\n): Model<any> {\n const storedFields = snapshotModelKeyMembers(fields, label);\n const name = getNameFromKeys(options?.name, storedFields);\n if (Object.hasOwn(state[slot] ?? {}, name)) {\n throw new Error(`${label} name '${name}' already used`);\n }\n const fieldsRecord = compoundMembers(state, storedFields, label);\n return new Model({\n ...state,\n [slot]: {\n ...state[slot],\n [name]: v.object(fieldsRecord, { partial: false }),\n },\n });\n}\n\n/** Snapshot one declaration tuple without consulting caller iteration hooks. */\nfunction snapshotModelKeyMembers(fields: unknown, label: string): string[] {\n function fail(): never {\n throw new Error(`${label} fields must be strings`);\n }\n if (!Array.isArray(fields)) fail();\n const members = new Array<string>(fields.length);\n for (let i = 0; i < fields.length; i++) {\n if (!Object.hasOwn(fields, i) || typeof fields[i] !== \"string\") fail();\n members[i] = fields[i];\n }\n return members;\n}\n\n/** Snapshot the four public index options, including inherited accessors. */\nfunction snapshotIndexOptions(options: IndexOptions): IndexOptions {\n const { name, unique, type, where } = options;\n const out: IndexOptions = {};\n if (name !== undefined) out.name = name;\n if (unique !== undefined) out.unique = unique;\n if (type !== undefined) out.type = type;\n if (where !== undefined) out.where = where;\n return out;\n}\n\n/** One physical key/index tuple cannot name the same column twice. */\nfunction refuseDuplicateModelKeyMembers(\n fields: readonly string[],\n label: string\n): void {\n if (new Set(fields).size !== fields.length) {\n throw new Error(`${label} duplicate field`);\n }\n}\n\n/**\n * Name registry for scalars and relations.\n * Maps scalar/relation keys to their resolved names (ts and sql).\n * This is populated during hydration.\n */\nexport interface NameRegistry {\n /** Scalar names: key -> {ts, sql} */\n fields: Map<string, SchemaNames>;\n}\n\nexport class Model<State extends ModelState> {\n // biome-ignore lint/style/useReadonlyClassProperties: <it is reassigned when hydrating schemas>\n #names: SchemaNames = {};\n // biome-ignore lint/style/useReadonlyClassProperties: <it is reassigned when hydrating schemas>\n #nameRegistry: NameRegistry = {\n fields: new Map(),\n };\n readonly #state: State;\n\n // Cached field metadata (lazily computed on first access)\n #scalarFieldNames: string[] | undefined;\n #relationNames: string[] | undefined;\n #internal: ModelInternal<State> | undefined;\n\n constructor(state: State) {\n this.#state = state;\n }\n\n // Materialize each completed modifier state inline before a recursive getter\n // captures it. A helper alias retains the whole prior modifier chain.\n /**\n * Maps the model to a specific database table name\n */\n map<Name extends string>(tableName: Name) {\n return new Model({ ...this.#state, tableName }) as unknown as Model<{\n [KState in keyof UpdateState<State, { tableName: Name }>]: UpdateState<\n State,\n { tableName: Name }\n >[KState];\n }>;\n }\n\n /**\n * Hide scalars from every result of this model — the schema-level exclusion.\n *\n * Keyed to the model's own SCALARS, so a typo or a relation name is a\n * compile error instead of an `omit` that quietly hides nothing. That\n * matters more here than anywhere else the builder takes field names: this\n * is the spelling used for secrets, and a silently-ignored key is a leaked\n * column. The refusal is per KEY, not per call: `{ secret: true, tokne:\n * true }` fails on `tokne` even though `secret` is real — two secrets with\n * one misspelled is the realistic case, and it is exactly the case an\n * excess-property-only refusal would wave through (see `UnknownOmitKeys`).\n *\n * Every value must be `true`. `false` has no meaning here (model-level omit\n * only ever hides) and a flag that may be `undefined` hides nothing at\n * runtime — `projectableScalarNames` compares against `true` — so\n * `Record<Hidden, true>` refuses both rather than recording a claim the\n * runtime would not honor.\n *\n * The literal survives the round trip — `.omit({ secret: true })` carries\n * exactly `{ secret: true }` into the state, not a widened record — which is\n * what every downstream `keyof State[\"omit\"]` reads. `Hidden` defaults to\n * `never` for the one call with nothing to infer from, `.omit({})`: a bare\n * `extends string` would fall back to `string` there and hand the state a\n * record keyed by every conceivable name.\n */\n omit<Hidden extends string = never>(\n items: Record<Hidden, true> &\n Record<UnknownOmitKeys<Hidden, State>, never> &\n ModelOmitInput<State>\n ) {\n return new Model({\n ...this.#state,\n omit: items,\n }) as unknown as Model<{\n [KState in keyof UpdateState<\n State,\n { omit: Record<Hidden, true> }\n >]: UpdateState<State, { omit: Record<Hidden, true> }>[KState];\n }>;\n }\n\n index<\n const Keys extends PortableKeyScalarKeys<State[\"scalars\"]>[],\n O extends OrdinaryIndexOptions = OrdinaryIndexOptions,\n >(\n fields: Keys,\n options?: ExactOptions<O, OrdinaryIndexOptions>\n ): Model<{\n [KState in keyof UpdateState<\n State,\n { indexes: UpdateIndexDefinition<State, { fields: Keys; options: O }> }\n >]: UpdateState<\n State,\n { indexes: UpdateIndexDefinition<State, { fields: Keys; options: O }> }\n >[KState];\n }>;\n index<\n const Key extends NonNullablePointScalarKeys<State[\"scalars\"]>,\n const O extends GeoPointSpatialIndexOptions,\n >(\n fields: [Key],\n options: ExactOptions<O, GeoPointSpatialIndexOptions>\n ): Model<{\n [KState in keyof UpdateState<\n State,\n { indexes: UpdateIndexDefinition<State, { fields: [Key]; options: O }> }\n >]: UpdateState<\n State,\n { indexes: UpdateIndexDefinition<State, { fields: [Key]; options: O }> }\n >[KState];\n }>;\n index(fields: string[], options: IndexOptions = {}): Model<any> {\n const storedFields = snapshotModelKeyMembers(fields, \"Index\");\n refuseDuplicateModelKeyMembers(storedFields, \"Index\");\n const storedOptions = snapshotIndexOptions(options);\n return new Model({\n ...this.#state,\n indexes: mergeIndexDefinitions(this.#state, {\n fields: storedFields,\n options: storedOptions,\n }),\n });\n }\n\n /**\n * An index the declaration cannot say, in each database's own language, which\n * migrations create, recognize and recreate when its text changes. It is never a\n * key and never covers a foreign key.\n */\n rawIndex(name: string, templates: RawIndexTemplates): Model<State> {\n // The migration that renders a template is what checks it. The list rides\n // the state object, so every builder's spread carries it, but not its type:\n // every state type maps over ModelState's keys, per model.\n const state = {\n ...this.#state,\n rawIndexes: [\n ...this[\"~\"].rawIndexes,\n { name, templates: { ...templates } },\n ],\n };\n return new Model<State>(state);\n }\n\n /**\n * On SQLite, a `WITHOUT ROWID` table: rows are stored in the primary key's\n * order, with no hidden rowid. Migrations create, recreate and verify it\n * so; other databases ignore it. A key generated by `.increment()` refuses\n * it (SQLite has no AUTOINCREMENT without a rowid).\n */\n withoutRowid(): Model<State> {\n // Held beside the typed state, as `rawIndex` is: see there.\n return new Model<State>({ ...this.#state, withoutRowid: true });\n }\n\n /**\n * A view whose rows the database stores: on PostgreSQL a materialized view,\n * which `.index()` may index and `$refresh()` recomputes. Elsewhere it is an\n * ordinary view. With `refresh: \"auto\"`, a table on every database, kept\n * current by triggers on its source at each write (SurrealDB keeps every\n * view so), for a view of one table's own fields. Only a view is\n * materialized: the `this` type refuses a table, and the call refuses one\n * a cast lets through.\n *\n * Generic over `this`, and marked by an intersection rather than a mapped\n * state: every signature of `Model` is compared whenever two model types\n * are, and a mapped return type cost a schema without a view 4,300\n * instantiations (+0.8 %) on the packed 50-model extended fixture.\n */\n materialized<\n S extends State & DeclaredViewState,\n const O extends MaterializedOptions = Record<never, never>,\n >(\n this: Model<S>,\n options?: ExactOptions<O, MaterializedOptions>\n ): Model<S & MaterializedViewState> {\n const view = viewFacts(this);\n if (view === undefined) throw new Error(\"Only views are materialized\");\n if (\n options !== undefined &&\n (!isRecord(options) ||\n Object.keys(options).some((key) => key !== \"refresh\") ||\n (options.refresh !== undefined && options.refresh !== \"auto\"))\n )\n throw new Error('materialized() takes { refresh?: \"auto\" }');\n return new Model({\n ...this.#state,\n view: {\n ...view,\n materialized: true,\n refresh: options?.refresh,\n },\n }) as never;\n }\n\n id<\n const Keys extends PortableKeyScalarKeys<State[\"scalars\"]>[],\n const O extends CompoundKeyOptions = Record<never, never>,\n >(fields: Keys, options?: ExactOptions<O, CompoundKeyOptions>) {\n return withCompound(\n this.#state,\n \"compoundId\",\n \"Compound ID\",\n fields,\n options\n ) as unknown as Model<{\n [KState in keyof UpdateState<\n State,\n {\n compoundId: MergeCompound<\n State[\"compoundId\"],\n {\n [K in CompoundKeyName<Keys, O>]: ObjectSchema<{\n [K2 in Keys[number]]: State[\"scalars\"][K2][\"~\"][\"state\"][\"base\"];\n }>;\n }\n >;\n }\n >]: UpdateState<\n State,\n {\n compoundId: MergeCompound<\n State[\"compoundId\"],\n {\n [K in CompoundKeyName<Keys, O>]: ObjectSchema<{\n [K2 in Keys[number]]: State[\"scalars\"][K2][\"~\"][\"state\"][\"base\"];\n }>;\n }\n >;\n }\n >[KState];\n }>;\n }\n\n unique<\n const Keys extends PortableKeyScalarKeys<State[\"scalars\"]>[],\n const O extends CompoundKeyOptions = Record<never, never>,\n >(fields: Keys, options?: ExactOptions<O, CompoundKeyOptions>) {\n return withCompound(\n this.#state,\n \"compoundUniques\",\n \"Compound unique\",\n fields,\n options\n ) as unknown as Model<{\n [KState in keyof UpdateState<\n State,\n {\n compoundUniques: MergeCompound<\n State[\"compoundUniques\"],\n {\n [K in CompoundKeyName<Keys, O>]: ObjectSchema<{\n [K2 in Keys[number]]: State[\"scalars\"][K2][\"~\"][\"state\"][\"base\"];\n }>;\n }\n >;\n }\n >]: UpdateState<\n State,\n {\n compoundUniques: MergeCompound<\n State[\"compoundUniques\"],\n {\n [K in CompoundKeyName<Keys, O>]: ObjectSchema<{\n [K2 in Keys[number]]: State[\"scalars\"][K2][\"~\"][\"state\"][\"base\"];\n }>;\n }\n >;\n }\n >[KState];\n }>;\n }\n\n extends<ETShape extends DeclaredModelShape>(shape: ETShape) {\n const newShape = { ...this.#state.shape, ...shape } as State[\"shape\"] &\n ETShape;\n return new Model({\n ...this.#state,\n shape: newShape,\n ...classifyShape(newShape),\n }) as unknown as Model<\n UpdateState<\n State,\n {\n shape: State[\"shape\"] & ETShape;\n scalars: ScalarMap<State[\"shape\"] & ETShape>;\n relations: RelationMap<State[\"shape\"] & ETShape>;\n uniques: UniqueScalarMap<State[\"shape\"] & ETShape>;\n }\n >\n >;\n }\n\n get \"~\"(): ModelInternal<State> {\n if (this.#internal) {\n return this.#internal;\n }\n // Capture model instance for use in getters\n const model = this;\n\n this.#internal = {\n state: this.#state,\n // getters so hydration after first access is still observed\n get names() {\n return model.#names;\n },\n get nameRegistry() {\n return model.#nameRegistry;\n },\n /**\n * Get the resolved names for a field.\n * Throws if the schema has not been hydrated.\n */\n getFieldName: (key: string): HydratedSchemaNames => {\n const registered = model.#nameRegistry.fields.get(key);\n if (registered) {\n return registered as HydratedSchemaNames;\n }\n throw new Error(`Unknown scalar \"${key}\"`);\n },\n /** Cached scalar field names (computed once on first access) */\n get scalarFieldNames(): string[] {\n return (model.#scalarFieldNames ??= Object.keys(model.#state.scalars));\n },\n /** Cached relation names (computed once on first access) */\n get relationNames(): string[] {\n return (model.#relationNames ??= Object.keys(model.#state.relations));\n },\n get rawIndexes(): readonly RawIndexDefinition[] {\n // Held beside the typed state: see Model.rawIndex.\n return (\n (model.#state as { rawIndexes?: readonly RawIndexDefinition[] })\n .rawIndexes ?? []\n );\n },\n get withoutRowid(): boolean {\n return (model.#state as { withoutRowid?: true }).withoutRowid === true;\n },\n };\n return this.#internal;\n }\n}\n\nexport const model = <TShape extends DeclaredModelShape>(\n shape: TShape\n): Model<InitialModelState<TShape>> =>\n new Model({\n compoundId: undefined,\n compoundUniques: undefined,\n tableName: undefined,\n indexes: [],\n omit: undefined,\n shape,\n ...classifyShape(shape),\n });\n\nexport type AnyModel = Model<any>;\n\n/**\n * SQL table name for a model: hydrated name, then .map() tableName, then\n * the given fallback.\n */\nexport function getTableName(model: AnyModel, fallback = \"unknown\"): string {\n return model[\"~\"].names.sql ?? stateOf(model).tableName ?? fallback;\n}\n\n/**\n * SQL column name for a field, resolved through the model's nameRegistry\n * (supports field reuse across models) with .map() and field-name fallbacks.\n */\nexport function getColumnName(model: AnyModel, fieldName: string): string {\n return model[\"~\"].getFieldName(fieldName).sql;\n}\n"],"mappings":"obAsBA,SAAgB,GAAoC,CAClD,OAAO,OAAO,OAAO,KAAK,CAI5B,SAAgB,GAAO,EAA2B,EAAa,EAAgB,CAC7E,OAAO,eAAe,EAAQ,EAAK,CACjC,QACA,WAAY,GACZ,SAAU,GACV,aAAc,GACf,CAAC,CAIJ,SAAgB,GACd,EACA,EACe,CACX,SAAW,IAAA,IAAa,CAAC,OAAO,OAAO,EAAQ,EAAI,EACvD,OAAO,EAAO,GAIhB,MAAa,EACX,GACoB,EAAE,KAAK,MAG7B,SAAgB,GAAc,EAAkB,EAAQ,EAAgB,CACtE,IAAM,EAAOA,EAAI,IAAI,EAAI,CACrB,EAAM,EAAK,KAAK,EAAM,CACrB,EAAI,IAAI,EAAK,CAAC,EAAM,CAAC,CAI5B,SAAgB,GACd,EACA,EACA,EACG,CACH,IAAI,EAAQA,EAAI,IAAI,EAAI,CAKxB,OAJI,IAAU,IAAA,KACZ,EAAQ,GAAM,CACd,EAAI,IAAI,EAAK,EAAM,EAEd,EC7CT,SAAgB,EACd,EACoB,CAEpB,IAAM,EAAW,EAAK,aAAa,SAE7B,EAAS,EACb,QACC,GAAU,GAAc,EAAO,EAAS,CAC1C,CAID,MAFC,GAAe,KAAO,EAEhB,ECVT,MAAM,GAA6B,EAAW,sBAAsB,CAK9D,EAA8B,OAAO,eAAe,WAAW,UAAU,CA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