viborm 1.2.4 → 1.3.1

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.
Files changed (275) hide show
  1. package/README.md +6 -1
  2. package/dist/{adapter-internals-n3Mf3css.mjs → adapter-internals-AGgQRu5t.mjs} +1 -1
  3. package/dist/{adapter-internals-n3Mf3css.mjs.map → adapter-internals-AGgQRu5t.mjs.map} +1 -1
  4. package/dist/adapter-namespace-BpMbLKpL.mjs +2 -0
  5. package/dist/{adapter-namespace-DqkJQdrD.mjs.map → adapter-namespace-BpMbLKpL.mjs.map} +1 -1
  6. package/dist/adapters.d.mts +1 -1
  7. package/dist/adapters.mjs +1 -1
  8. package/dist/{array-literal-BsbbSLw3.mjs → array-literal-BKdLfNzM.mjs} +1 -1
  9. package/dist/{array-literal-BsbbSLw3.mjs.map → array-literal-BKdLfNzM.mjs.map} +1 -1
  10. package/dist/{base-AdXAoy6l.mjs → base-D3m1S7Uc.mjs} +2 -2
  11. package/dist/{base-AdXAoy6l.mjs.map → base-D3m1S7Uc.mjs.map} +1 -1
  12. package/dist/{batch-refs-4L8ECdPU.mjs → batch-refs-B4zn-FAu.mjs} +2 -2
  13. package/dist/{batch-refs-4L8ECdPU.mjs.map → batch-refs-B4zn-FAu.mjs.map} +1 -1
  14. package/dist/{bind-parameter-capacity-CjPgqnmx.mjs → bind-parameter-capacity-qfEejeOX.mjs} +2 -2
  15. package/dist/{bind-parameter-capacity-CjPgqnmx.mjs.map → bind-parameter-capacity-qfEejeOX.mjs.map} +1 -1
  16. package/dist/builder-s1ySUuMb.mjs +2 -0
  17. package/dist/builder-s1ySUuMb.mjs.map +1 -0
  18. package/dist/bun-sql.d.mts +3 -1
  19. package/dist/bun-sql.mjs +1 -1
  20. package/dist/bun-sql.mjs.map +1 -1
  21. package/dist/bun-sqlite.d.mts +1 -1
  22. package/dist/bun-sqlite.mjs +1 -1
  23. package/dist/cache/cloudflare-kv.d.mts +1 -1
  24. package/dist/cache/cloudflare-kv.mjs +1 -1
  25. package/dist/cache/memory.d.mts +1 -1
  26. package/dist/cache/memory.mjs +1 -1
  27. package/dist/{cache-BO57X0TT.mjs → cache-CIPRF-pz.mjs} +2 -2
  28. package/dist/{cache-BO57X0TT.mjs.map → cache-CIPRF-pz.mjs.map} +1 -1
  29. package/dist/cache.d.mts +1 -1
  30. package/dist/cache.mjs +1 -1
  31. package/dist/cache.mjs.map +1 -1
  32. package/dist/{canonical-json-rfC2Dg0X.mjs → canonical-json-BReb5nFO.mjs} +2 -2
  33. package/dist/{canonical-json-rfC2Dg0X.mjs.map → canonical-json-BReb5nFO.mjs.map} +1 -1
  34. package/dist/chain-7qiFSE8J.mjs +2 -0
  35. package/dist/chain-7qiFSE8J.mjs.map +1 -0
  36. package/dist/cli.mjs +2 -2
  37. package/dist/cli.mjs.map +1 -1
  38. package/dist/client-6YgGlXzN.mjs +2 -0
  39. package/dist/client-6YgGlXzN.mjs.map +1 -0
  40. package/dist/{client-CUnPXifK.d.mts → client-70MrTq1E.d.mts} +3 -3
  41. package/dist/client-BgJ7Faln.mjs +49 -0
  42. package/dist/{client-B3VWFhv_.mjs.map → client-BgJ7Faln.mjs.map} +1 -1
  43. package/dist/client.d.mts +2 -2
  44. package/dist/client.mjs +1 -1
  45. package/dist/{clock-CK41KO7t.mjs → clock-C24RcpwO.mjs} +1 -1
  46. package/dist/{clock-CK41KO7t.mjs.map → clock-C24RcpwO.mjs.map} +1 -1
  47. package/dist/config.d.mts +2 -2
  48. package/dist/config.mjs +1 -1
  49. package/dist/controls-KQ85SWfT.mjs +2 -0
  50. package/dist/controls-KQ85SWfT.mjs.map +1 -0
  51. package/dist/{current-DyzK6OCh.mjs → current-oXcxSCBQ.mjs} +1 -1
  52. package/dist/{current-DyzK6OCh.mjs.map → current-oXcxSCBQ.mjs.map} +1 -1
  53. package/dist/d1.d.mts +1 -1
  54. package/dist/d1.mjs +1 -1
  55. package/dist/d1.mjs.map +1 -1
  56. package/dist/{datetime-physical-codec-oIhiYZEP.mjs → datetime-physical-codec-BEqQbIP_.mjs} +2 -2
  57. package/dist/{datetime-physical-codec-oIhiYZEP.mjs.map → datetime-physical-codec-BEqQbIP_.mjs.map} +1 -1
  58. package/dist/driver-B9fIori_.mjs +2 -0
  59. package/dist/driver-B9fIori_.mjs.map +1 -0
  60. package/dist/{driver-B19QlFqn.mjs → driver-vn-9CN0y.mjs} +2 -2
  61. package/dist/{driver-B19QlFqn.mjs.map → driver-vn-9CN0y.mjs.map} +1 -1
  62. package/dist/driver.d.mts +1 -1
  63. package/dist/driver.mjs +1 -1
  64. package/dist/error-mapping-C9WgitPi.mjs +2 -0
  65. package/dist/error-mapping-C9WgitPi.mjs.map +1 -0
  66. package/dist/every-CcpKWCVo.mjs +2 -0
  67. package/dist/{every-o-Nu9Em8.mjs.map → every-CcpKWCVo.mjs.map} +1 -1
  68. package/dist/{execution-context-BKR3bgES.mjs → execution-context-rJXTRVrJ.mjs} +1 -1
  69. package/dist/{execution-context-BKR3bgES.mjs.map → execution-context-rJXTRVrJ.mjs.map} +1 -1
  70. package/dist/{fs-estate-CAhDg7nY.mjs → fs-estate-i8Zlr1OQ.mjs} +2 -2
  71. package/dist/{fs-estate-CAhDg7nY.mjs.map → fs-estate-i8Zlr1OQ.mjs.map} +1 -1
  72. package/dist/{geo-area-codec-1SY9im7O.mjs → geo-area-codec-CbkmFArQ.mjs} +2 -2
  73. package/dist/{geo-area-codec-1SY9im7O.mjs.map → geo-area-codec-CbkmFArQ.mjs.map} +1 -1
  74. package/dist/geo-point-codec-DyEHMdJg.mjs +2 -0
  75. package/dist/geo-point-codec-DyEHMdJg.mjs.map +1 -0
  76. package/dist/hydration-BsPZI4jE.mjs +2 -0
  77. package/dist/{hydration-CAxOL4aI.mjs.map → hydration-BsPZI4jE.mjs.map} +1 -1
  78. package/dist/identifier-conversion-BneQiLxQ.mjs +2 -0
  79. package/dist/{identifier-conversion-GgbwHc2G.mjs.map → identifier-conversion-BneQiLxQ.mjs.map} +1 -1
  80. package/dist/{identity-CLFhCTZx.mjs → identity-oQvIe7u8.mjs} +2 -2
  81. package/dist/{identity-CLFhCTZx.mjs.map → identity-oQvIe7u8.mjs.map} +1 -1
  82. package/dist/{index-B0b7asA4.d.mts → index-VsM29vYN.d.mts} +5257 -4915
  83. package/dist/index.d.mts +3 -3
  84. package/dist/index.mjs +1 -1
  85. package/dist/index.mjs.map +1 -1
  86. package/dist/instrumentation.d.mts +1 -1
  87. package/dist/instrumentation.mjs +1 -1
  88. package/dist/{invariant-BnLYqsHO.mjs → invariant-D57gi_yW.mjs} +1 -1
  89. package/dist/{invariant-BnLYqsHO.mjs.map → invariant-D57gi_yW.mjs.map} +1 -1
  90. package/dist/{json-number-CGXpPu4D.mjs → json-number-DvmiNx0n.mjs} +1 -1
  91. package/dist/{json-number-CGXpPu4D.mjs.map → json-number-DvmiNx0n.mjs.map} +1 -1
  92. package/dist/key-D9LtHxVK.mjs +2 -0
  93. package/dist/{key-BeoOwGr3.mjs.map → key-D9LtHxVK.mjs.map} +1 -1
  94. package/dist/{libsql-Drp-zaxq.mjs → libsql-BlSBYwd_.mjs} +3 -3
  95. package/dist/{libsql-Drp-zaxq.mjs.map → libsql-BlSBYwd_.mjs.map} +1 -1
  96. package/dist/libsql.d.mts +1 -1
  97. package/dist/libsql.mjs +1 -1
  98. package/dist/{memory-CDTUZQWL.mjs → memory-C0k-_S_n.mjs} +2 -2
  99. package/dist/{memory-CDTUZQWL.mjs.map → memory-C0k-_S_n.mjs.map} +1 -1
  100. package/dist/migrations/mysql.d.mts +5 -5
  101. package/dist/migrations/mysql.mjs +1 -1
  102. package/dist/migrations/postgres.d.mts +5 -5
  103. package/dist/migrations/postgres.mjs +1 -1
  104. package/dist/migrations/sqlite.d.mts +5 -5
  105. package/dist/migrations/sqlite.mjs +1 -1
  106. package/dist/migrations/storage/durable-object.d.mts +1 -1
  107. package/dist/migrations/storage/durable-object.mjs +1 -1
  108. package/dist/migrations/storage/fs.d.mts +1 -1
  109. package/dist/migrations/storage/fs.mjs +1 -1
  110. package/dist/migrations/storage/r2.d.mts +1 -1
  111. package/dist/migrations/storage/r2.mjs +1 -1
  112. package/dist/migrations/tenant.d.mts +3 -3
  113. package/dist/migrations/tenant.mjs +1 -1
  114. package/dist/{migrations-DTObIjAm.mjs → migrations-Bn1SatyB.mjs} +2 -2
  115. package/dist/{migrations-DTObIjAm.mjs.map → migrations-Bn1SatyB.mjs.map} +1 -1
  116. package/dist/migrations.d.mts +5 -5
  117. package/dist/migrations.mjs +1 -1
  118. package/dist/{mysql-D7zC03yD.mjs → mysql-DOLHwIM_.mjs} +6 -6
  119. package/dist/{mysql-D7zC03yD.mjs.map → mysql-DOLHwIM_.mjs.map} +1 -1
  120. package/dist/mysql-adapter-C6c5govr.mjs +2 -0
  121. package/dist/{mysql-adapter-DkJPfoGf.mjs.map → mysql-adapter-C6c5govr.mjs.map} +1 -1
  122. package/dist/mysql2.d.mts +1 -1
  123. package/dist/mysql2.mjs +1 -1
  124. package/dist/{native-types-veeTk36s.mjs → native-types-asNCr26n.mjs} +1 -1
  125. package/dist/{native-types-veeTk36s.mjs.map → native-types-asNCr26n.mjs.map} +1 -1
  126. package/dist/neon-http.d.mts +3 -1
  127. package/dist/neon-http.mjs +1 -1
  128. package/dist/neon-http.mjs.map +1 -1
  129. package/dist/{object-store-DQR6bTBY.mjs → object-store-ChYHlOMD.mjs} +2 -2
  130. package/dist/{object-store-DQR6bTBY.mjs.map → object-store-ChYHlOMD.mjs.map} +1 -1
  131. package/dist/{object-store-DMFXXQEC.d.mts → object-store-D9mvOHP4.d.mts} +4 -4
  132. package/dist/{observation-DUSm7oXK.mjs → observation-Co72iCd1.mjs} +2 -2
  133. package/dist/{observation-DUSm7oXK.mjs.map → observation-Co72iCd1.mjs.map} +1 -1
  134. package/dist/permissions.d.mts +424 -0
  135. package/dist/permissions.mjs +2 -0
  136. package/dist/permissions.mjs.map +1 -0
  137. package/dist/pg.d.mts +9 -1
  138. package/dist/pg.mjs +1 -1
  139. package/dist/pg.mjs.map +1 -1
  140. package/dist/pglite.d.mts +3 -1
  141. package/dist/pglite.mjs +1 -1
  142. package/dist/pglite.mjs.map +1 -1
  143. package/dist/{physical-6V_LNU3L.mjs → physical-CAOaNM4R.mjs} +2 -2
  144. package/dist/{physical-6V_LNU3L.mjs.map → physical-CAOaNM4R.mjs.map} +1 -1
  145. package/dist/{pinned-session-CLxj5M5e.mjs → pinned-session-BTplL3iZ.mjs} +2 -2
  146. package/dist/{pinned-session-CLxj5M5e.mjs.map → pinned-session-BTplL3iZ.mjs.map} +1 -1
  147. package/dist/planetscale.d.mts +1 -1
  148. package/dist/planetscale.mjs +1 -1
  149. package/dist/{planner-C0Q7ks-V.d.mts → planner-C1NzLBge.d.mts} +1 -1
  150. package/dist/{postgres-Dv-QnnbD.mjs → postgres-DQVSTqVm.mjs} +4 -4
  151. package/dist/{postgres-Dv-QnnbD.mjs.map → postgres-DQVSTqVm.mjs.map} +1 -1
  152. package/dist/postgres-adapter-CGthb5yh.mjs +2 -0
  153. package/dist/postgres-adapter-CGthb5yh.mjs.map +1 -0
  154. package/dist/postgres-adapter-CxEit2-v.mjs +2 -0
  155. package/dist/postgres-adapter-CxEit2-v.mjs.map +1 -0
  156. package/dist/{postgres-result-7F0DllQe.mjs → postgres-result-KyBKBNJr.mjs} +2 -2
  157. package/dist/{postgres-result-7F0DllQe.mjs.map → postgres-result-KyBKBNJr.mjs.map} +1 -1
  158. package/dist/postgres.d.mts +3 -1
  159. package/dist/postgres.mjs +1 -1
  160. package/dist/postgres.mjs.map +1 -1
  161. package/dist/{provider-limits-BHATED_m.mjs → provider-limits-Da00ilvv.mjs} +2 -2
  162. package/dist/{provider-limits-BHATED_m.mjs.map → provider-limits-Da00ilvv.mjs.map} +1 -1
  163. package/dist/{result-parsing-DRXC89ek.mjs → result-parsing-8wEK3GY1.mjs} +1 -1
  164. package/dist/{result-parsing-DRXC89ek.mjs.map → result-parsing-8wEK3GY1.mjs.map} +1 -1
  165. package/dist/result-shape-B6yWtnx_.mjs +2 -0
  166. package/dist/result-shape-B6yWtnx_.mjs.map +1 -0
  167. package/dist/scalar-CpEwuJvn.mjs +4 -0
  168. package/dist/scalar-CpEwuJvn.mjs.map +1 -0
  169. package/dist/schema/json.d.mts +1 -1
  170. package/dist/schema/json.mjs +1 -1
  171. package/dist/schema/json.mjs.map +1 -1
  172. package/dist/schema-BnzGHn7k.mjs +2 -0
  173. package/dist/{schema-Cjem1-0f.mjs.map → schema-BnzGHn7k.mjs.map} +1 -1
  174. package/dist/{schema-introspection-DEYGC2qg.mjs → schema-introspection-DZsdP6bi.mjs} +4 -4
  175. package/dist/{schema-introspection-DEYGC2qg.mjs.map → schema-introspection-DZsdP6bi.mjs.map} +1 -1
  176. package/dist/schema.d.mts +1 -1
  177. package/dist/schema.mjs +1 -1
  178. package/dist/{select-assembly-f1UGoblh.mjs → select-assembly-CkGe2ABs.mjs} +2 -2
  179. package/dist/{select-assembly-f1UGoblh.mjs.map → select-assembly-CkGe2ABs.mjs.map} +1 -1
  180. package/dist/{settle-B9Vg1FnP.mjs → settle-CS_k6Ztm.mjs} +2 -2
  181. package/dist/{settle-B9Vg1FnP.mjs.map → settle-CS_k6Ztm.mjs.map} +1 -1
  182. package/dist/soft-delete.d.mts +27 -96
  183. package/dist/soft-delete.mjs +1 -1
  184. package/dist/soft-delete.mjs.map +1 -1
  185. package/dist/sql-Bhxq9arK.mjs +2 -0
  186. package/dist/sql-Bhxq9arK.mjs.map +1 -0
  187. package/dist/{sql-BvfwUKIh.d.mts → sql-EsoN_7Et.d.mts} +24 -0
  188. package/dist/{sql-statement-tokens-BBcoGmJb.mjs → sql-statement-tokens-CFi1y3bK.mjs} +1 -1
  189. package/dist/{sql-statement-tokens-BBcoGmJb.mjs.map → sql-statement-tokens-CFi1y3bK.mjs.map} +1 -1
  190. package/dist/sql.d.mts +1 -1
  191. package/dist/sql.mjs +1 -1
  192. package/dist/sqlite-adapter-BXAJy3mI.mjs +2 -0
  193. package/dist/sqlite-adapter-BXAJy3mI.mjs.map +1 -0
  194. package/dist/{sqlite-utils-DlgokMJN.mjs → sqlite-utils-D_cypcyW.mjs} +2 -2
  195. package/dist/{sqlite-utils-DlgokMJN.mjs.map → sqlite-utils-D_cypcyW.mjs.map} +1 -1
  196. package/dist/sqlite3.d.mts +3 -1
  197. package/dist/sqlite3.mjs +1 -1
  198. package/dist/sqlite3.mjs.map +1 -1
  199. package/dist/{standard-sql-Bk4RZPqJ.mjs → standard-sql-CoGqv-iX.mjs} +3 -3
  200. package/dist/standard-sql-CoGqv-iX.mjs.map +1 -0
  201. package/dist/{suppressed-failure-BwULh-8h.mjs → suppressed-failure-Bdo2aK81.mjs} +1 -1
  202. package/dist/{suppressed-failure-BwULh-8h.mjs.map → suppressed-failure-Bdo2aK81.mjs.map} +1 -1
  203. package/dist/to-many-C5RMZl05.mjs +2 -0
  204. package/dist/to-many-C5RMZl05.mjs.map +1 -0
  205. package/dist/{transaction-Bnl6ULTw.mjs → transaction-4dfqals6.mjs} +2 -2
  206. package/dist/{transaction-Bnl6ULTw.mjs.map → transaction-4dfqals6.mjs.map} +1 -1
  207. package/dist/{transaction-operation-CKK3l_9x.mjs → transaction-operation-CU1zlxiG.mjs} +2 -2
  208. package/dist/{transaction-operation-CKK3l_9x.mjs.map → transaction-operation-CU1zlxiG.mjs.map} +1 -1
  209. package/dist/{types-C4v6iAmY.mjs → types-C5Oxz9yp.mjs} +1 -1
  210. package/dist/{types-C4v6iAmY.mjs.map → types-C5Oxz9yp.mjs.map} +1 -1
  211. package/dist/{utils-CZNaOZR7.mjs → utils-C3r4gO3Y.mjs} +4 -4
  212. package/dist/{utils-CZNaOZR7.mjs.map → utils-C3r4gO3Y.mjs.map} +1 -1
  213. package/dist/v-DtLdBQYg.mjs +2 -0
  214. package/dist/v-DtLdBQYg.mjs.map +1 -0
  215. package/dist/validation-BQtO6srU.mjs +2 -0
  216. package/dist/{validation-PF9-_nKd.mjs.map → validation-BQtO6srU.mjs.map} +1 -1
  217. package/dist/validation-BamBwne9.mjs +2 -0
  218. package/dist/validation-BamBwne9.mjs.map +1 -0
  219. package/dist/validation.d.mts +1 -1
  220. package/dist/validation.mjs +1 -1
  221. package/dist/validator-CVSrhn0u.mjs +2 -0
  222. package/dist/validator-CVSrhn0u.mjs.map +1 -0
  223. package/dist/version-C8QLCt1n.mjs +2 -0
  224. package/dist/{version-nt0parEY.mjs.map → version-C8QLCt1n.mjs.map} +1 -1
  225. package/package.json +36 -9
  226. package/dist/adapter-namespace-DqkJQdrD.mjs +0 -2
  227. package/dist/builder-Ycvq3ETg.mjs +0 -2
  228. package/dist/builder-Ycvq3ETg.mjs.map +0 -1
  229. package/dist/chain-Dh0FV72b.mjs +0 -2
  230. package/dist/chain-Dh0FV72b.mjs.map +0 -1
  231. package/dist/client-B3VWFhv_.mjs +0 -49
  232. package/dist/client-BLiBmykn.mjs +0 -2
  233. package/dist/client-BLiBmykn.mjs.map +0 -1
  234. package/dist/controls-DXgIn4zh.mjs +0 -2
  235. package/dist/controls-DXgIn4zh.mjs.map +0 -1
  236. package/dist/driver-BlnKXPFF.mjs +0 -2
  237. package/dist/driver-BlnKXPFF.mjs.map +0 -1
  238. package/dist/error-mapping-CnPCv1dm.mjs +0 -2
  239. package/dist/error-mapping-CnPCv1dm.mjs.map +0 -1
  240. package/dist/every-o-Nu9Em8.mjs +0 -2
  241. package/dist/geo-point-codec-lhxH42SK.mjs +0 -2
  242. package/dist/geo-point-codec-lhxH42SK.mjs.map +0 -1
  243. package/dist/hydration-CAxOL4aI.mjs +0 -2
  244. package/dist/identifier-conversion-GgbwHc2G.mjs +0 -2
  245. package/dist/identifier-hQCs8M1n.mjs +0 -2
  246. package/dist/identifier-hQCs8M1n.mjs.map +0 -1
  247. package/dist/key-BeoOwGr3.mjs +0 -2
  248. package/dist/mysql-adapter-DkJPfoGf.mjs +0 -2
  249. package/dist/postgres-adapter-B3SQvcV1.mjs +0 -2
  250. package/dist/postgres-adapter-B3SQvcV1.mjs.map +0 -1
  251. package/dist/postgres-adapter-CQD2oGuD.mjs +0 -2
  252. package/dist/postgres-adapter-CQD2oGuD.mjs.map +0 -1
  253. package/dist/registration-preflight-DEjv050M.mjs +0 -4
  254. package/dist/registration-preflight-DEjv050M.mjs.map +0 -1
  255. package/dist/result-shape-CTNdNSW3.mjs +0 -2
  256. package/dist/result-shape-CTNdNSW3.mjs.map +0 -1
  257. package/dist/scalar-U0wD5bKy.mjs +0 -2
  258. package/dist/scalar-U0wD5bKy.mjs.map +0 -1
  259. package/dist/schema-Cjem1-0f.mjs +0 -2
  260. package/dist/sql-Bp7jicEX.mjs +0 -2
  261. package/dist/sql-Bp7jicEX.mjs.map +0 -1
  262. package/dist/sqlite-adapter-CW_3l6ea.mjs +0 -2
  263. package/dist/sqlite-adapter-CW_3l6ea.mjs.map +0 -1
  264. package/dist/standard-sql-Bk4RZPqJ.mjs.map +0 -1
  265. package/dist/terminal-C8cq1WWX.mjs +0 -2
  266. package/dist/terminal-C8cq1WWX.mjs.map +0 -1
  267. package/dist/v-D5Z06FKN.mjs +0 -2
  268. package/dist/v-D5Z06FKN.mjs.map +0 -1
  269. package/dist/validation-Dk9Q_-C7.mjs +0 -2
  270. package/dist/validation-Dk9Q_-C7.mjs.map +0 -1
  271. package/dist/validation-PF9-_nKd.mjs +0 -2
  272. package/dist/validator-X9-bwtRo.mjs +0 -2
  273. package/dist/validator-X9-bwtRo.mjs.map +0 -1
  274. package/dist/version-nt0parEY.mjs +0 -2
  275. /package/dist/{contract-CIIqgFyb.d.mts → contract-Dw0FR78e.d.mts} +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"utils-CZNaOZR7.mjs","names":[],"sources":["../src/cli/utils.ts"],"sourcesContent":["/**\n * CLI Utilities\n *\n * Configuration loading and other CLI utilities.\n *\n * Config file pattern similar to:\n * - drizzle.config.ts\n * - prisma (uses schema.prisma but we use TS)\n */\n\nimport { existsSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { loadEnvFile } from \"node:process\";\nimport { createJiti } from \"jiti\";\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { withSuppressedFailure } from \"../drivers/shared/suppressed-failure\";\nimport { isVibORMError } from \"../errors\";\nimport type { MigrationClient } from \"../migrations/push/planner\";\nimport type { MigrationStorageWriter } from \"../migrations/storage/contract\";\nimport type { ResolveCallback } from \"../migrations/types\";\nimport type { AnyModel } from \"../schema/model\";\nimport { validateSchemaOrThrow } from \"../schema/validation\";\n\n// =============================================================================\n// CONFIG TYPES\n// =============================================================================\n\n/**\n * Migration configuration options.\n */\nexport interface MigrationConfig {\n /** Estate directory (default: \"./migrations\") */\n dir?: string;\n /** Immutable exact physical table scope; include junctions and rename destinations. */\n tables?: readonly string[];\n /** Explicit rename, destructive-change and enum-value decisions for CLI planning. */\n resolve?: ResolveCallback;\n /**\n * Estate storage writer. Defaults to filesystem storage at `dir`.\n *\n * @example\n * ```ts\n * import { createFsStorageWriter } from \"viborm/migrations/storage/fs\";\n *\n * migrations: {\n * storage: createFsStorageWriter(\"./migrations\"),\n * }\n * ```\n */\n storage?: MigrationStorageWriter;\n}\n\n/**\n * VibORM configuration file format.\n *\n * Example viborm.config.ts:\n * ```ts\n * import { defineConfig } from \"viborm/config\";\n * import { client } from \"./src/db\";\n *\n * export default defineConfig({\n * client,\n * });\n * ```\n */\nexport interface VibORMConfig {\n /** VibORM client instance */\n client: MigrationClient & { $disconnect(): Promise<void> };\n /** Optional: Migration configuration */\n migrations?: MigrationConfig;\n}\n\nexport interface LoadConfigOptions {\n /** Path to config file (default: ./viborm.config.ts) */\n config?: string;\n /** Leave validation to the caller (`viborm check` reports every issue). */\n skipValidation?: boolean;\n}\n\nexport interface LoadedConfig {\n client: VibORMConfig[\"client\"];\n driver: AnyDriver;\n models: Record<string, AnyModel>;\n migrations?: MigrationConfig;\n}\n\n// =============================================================================\n// CONFIG FILE DISCOVERY\n// =============================================================================\n\nconst CONFIG_FILES = [\n \"viborm.config.ts\",\n \"viborm.config.mts\",\n \"viborm.config.js\",\n \"viborm.config.mjs\",\n];\n\n/**\n * Finds the first existing file from a list of candidates.\n */\nfunction findFile(cwd: string, candidates: string[]): string | null {\n for (const candidate of candidates) {\n const fullPath = resolve(cwd, candidate);\n if (existsSync(fullPath)) {\n return fullPath;\n }\n }\n return null;\n}\n\n// =============================================================================\n// CONFIG LOADING\n// =============================================================================\n\n/**\n * Loads VibORM configuration from viborm.config.ts file.\n *\n * The config file should export a default configuration object with:\n * - client: VibORM client instance created with createClient()\n */\nexport function failCli(error: unknown, json = false): never {\n const trusted = isVibORMError(error);\n const message =\n error instanceof Error\n ? error.message\n : typeof error === \"string\"\n ? error\n : \"CLI operation failed\";\n const code = trusted ? error.code : undefined;\n const exitCode = code?.startsWith(\"V11\")\n ? Number(code.slice(1)) - 11_000 + 10\n : trusted\n ? 2\n : 1;\n process.stderr.write(\n json\n ? `${JSON.stringify({ error: trusted ? error.toJSON() : { name: error instanceof Error ? error.name : \"Error\", message }, exitCode })}\\n`\n : `${code ? `[${code}] ` : \"\"}${message}\\n`\n );\n process.exit(exitCode);\n}\n\n/** Await owned CLI cleanup before reporting either the primary or cleanup failure. */\nexport async function finishCli(\n client: { $disconnect(): Promise<void> } | undefined,\n failure: { value: unknown } | undefined,\n json = false\n): Promise<void> {\n let outcome = failure;\n try {\n await client?.$disconnect();\n } catch (cleanup) {\n outcome = {\n value: failure ? withSuppressedFailure(failure.value, cleanup) : cleanup,\n };\n }\n if (outcome) {\n if (json) failCli(outcome.value, true);\n else failCli(outcome.value);\n }\n}\n\n/** Every command's frame: load the config, own its client, report through {@link finishCli}. */\nexport async function runCli(\n load: LoadConfigOptions,\n json: boolean | undefined,\n body: (config: LoadedConfig) => Promise<void>\n): Promise<void> {\n let client: { $disconnect(): Promise<void> } | undefined;\n let failure: { value: unknown } | undefined;\n try {\n const config = await loadConfig(load);\n client = config.client;\n await body(config);\n } catch (error) {\n failure = { value: error };\n } finally {\n await finishCli(client, failure, json);\n }\n}\n\n/** JSON for `--json`, else an indented outline of the same value. */\nexport function printJson(value: unknown, json: boolean): void {\n if (json) {\n process.stdout.write(`${JSON.stringify(value, null, 2)}\\n`);\n return;\n }\n const lines: string[] = [];\n const render = (item: unknown, indent = \"\") => {\n if (Array.isArray(item)) {\n for (const entry of item) {\n lines.push(`${indent}-`);\n render(entry, `${indent} `);\n }\n if (item.length === 0) lines.push(`${indent}(none)`);\n } else if (item !== null && typeof item === \"object\") {\n for (const [key, entry] of Object.entries(item)) {\n if (entry !== null && typeof entry === \"object\") {\n lines.push(`${indent}${key}:`);\n render(entry, `${indent} `);\n } else lines.push(`${indent}${key}: ${String(entry)}`);\n }\n } else lines.push(`${indent}${String(item)}`);\n };\n render(value);\n process.stdout.write(`${lines.join(\"\\n\")}\\n`);\n}\n\nexport async function loadConfig(\n options: LoadConfigOptions = {}\n): Promise<LoadedConfig> {\n const cwd = process.cwd();\n const envPath = resolve(cwd, \".env\");\n if (existsSync(envPath)) loadEnvFile(envPath);\n\n // Find config file\n const configPath = options.config\n ? resolve(cwd, options.config)\n : findFile(cwd, CONFIG_FILES);\n\n if (!(configPath && existsSync(configPath))) {\n const searchedPaths = options.config ? [options.config] : CONFIG_FILES;\n\n throw new Error(\n \"Could not find VibORM configuration file.\\n\\n\" +\n `Searched for:\\n${searchedPaths.map((f) => ` - ${f}`).join(\"\\n\")}\\n\\n` +\n \"Create a viborm.config.ts file:\\n\\n\" +\n ` import { defineConfig } from \"viborm/config\";\\n` +\n ` import { client } from \"./src/db\";\\n\\n` +\n \" export default defineConfig({\\n\" +\n \" client,\\n\" +\n \" });\\n\"\n );\n }\n\n // Load the config file\n const configModule = await loadCliModule<\n VibORMConfig & { default?: VibORMConfig; config?: VibORMConfig }\n >(configPath);\n\n // Extract config (handle both default export and named export)\n const config: VibORMConfig =\n (Object.hasOwn(configModule, \"default\") && configModule.default) ||\n configModule.config ||\n configModule;\n\n // Validate client\n if (!config.client) {\n throw new Error(\n `Missing \"client\" in ${configPath}.\\n\\n` +\n \"Your config should include a VibORM client:\\n\\n\" +\n ` import { createClient } from \"viborm\";\\n` +\n \" const client = createClient({ driver, schema });\\n\\n\" +\n \" export default defineConfig({\\n\" +\n \" client,\\n\" +\n \" });\\n\"\n );\n }\n\n if (!isValidClient(config.client)) {\n throw new Error(\n `Invalid \"client\" in ${configPath}.\\n\\n` +\n \"The client must be created with createClient().\\n\"\n );\n }\n\n // Extract driver and schema from client\n const driver = config.client.$driver;\n const schemaInput = config.client.$schema;\n\n // Extract models from schema (filter out non-model exports)\n const models = extractModels(schemaInput);\n\n if (Object.keys(models).length === 0) {\n throw new Error(\n `No models found in client schema from ${configPath}.\\n\\n` +\n \"Make sure your client was created with schema models:\\n\\n\" +\n \" // src/schema.ts\\n\" +\n ` import { s } from \"viborm\";\\n\\n` +\n \" export const user = s.model({\\n\" +\n \" id: s.string().id(),\\n\" +\n \" name: s.string(),\\n\" +\n \" });\\n\"\n );\n }\n\n // Validate schema before proceeding\n if (!options.skipValidation) validateSchemaOrThrow(models);\n\n return {\n client: config.client,\n driver,\n models,\n migrations: config.migrations,\n };\n}\n\n/**\n * Dynamically imports a TypeScript/JavaScript module.\n */\nexport function loadCliModule<T>(filePath: string): Promise<T> {\n // Dependency imports need CJS interop; consumers select only authored defaults.\n return createJiti(filePath, {\n tsconfigPaths: true,\n interopDefault: true,\n }).import<T>(filePath);\n}\n\n/**\n * Extracts model objects from a module by checking for Model instances.\n */\nfunction extractModels(\n schema: Record<string, unknown>\n): Record<string, AnyModel> {\n const models: Record<string, AnyModel> = {};\n\n for (const [key, value] of Object.entries(schema)) {\n if (isModel(value)) {\n models[key] = value;\n }\n }\n\n return models;\n}\n\n/**\n * Checks if a value is a VibORM Model instance.\n */\nfunction isModel(value: unknown): value is AnyModel {\n if (value === null || typeof value !== \"object\") return false;\n const metadata = Reflect.get(value, \"~\");\n if (metadata === null || typeof metadata !== \"object\") return false;\n const state = Reflect.get(metadata, \"state\");\n // Model state exposes `scalars`/`relations` (never `fields`); the rest of\n // the codebase discriminates models the same way (see serializer).\n return state !== null && typeof state === \"object\" && \"scalars\" in state;\n}\n\n/**\n * Checks if a value is a valid VibORM client instance.\n */\nfunction isValidClient(value: unknown): boolean {\n // The client is a Proxy whose only trap is `get`, so `\"$driver\" in value`\n // (which triggers the `has` trap / falls back to the bare target) is always\n // false. Probe via property access instead.\n // `typeof null === \"object\"`, so null has to be refused here: Reflect.get\n // throws on it rather than answering undefined.\n if (\n value === null ||\n (typeof value !== \"object\" && typeof value !== \"function\")\n ) {\n return false;\n }\n return (\n Reflect.get(value, \"$driver\") !== undefined &&\n Reflect.get(value, \"$schema\") !== undefined\n );\n}\n\n// =============================================================================\n// DEFINE CONFIG HELPER\n// =============================================================================\n\n/**\n * Helper function for defining VibORM configuration with type safety.\n *\n * @example\n * ```ts\n * // viborm.config.ts\n * import { defineConfig } from \"viborm/config\";\n * import { client } from \"./src/db\";\n *\n * export default defineConfig({\n * client,\n * });\n * ```\n */\nexport function defineConfig<const C extends VibORMConfig>(\n config: C &\n Record<Exclude<keyof C, keyof VibORMConfig>, never> &\n (C extends { migrations: infer M }\n ? {\n migrations: M &\n Record<Exclude<keyof M, keyof MigrationConfig>, never>;\n }\n : unknown)\n): C {\n return config;\n}\n"],"mappings":"qUA0FA,MAAM,EAAe,CACnB,mBACA,oBACA,mBACA,oBACD,CAKD,SAAS,SAAS,EAAa,EAAqC,CAClE,IAAK,IAAM,KAAa,EAAY,CAClC,IAAM,EAAW,EAAQ,EAAK,EAAU,CACxC,GAAI,EAAW,EAAS,CACtB,OAAO,EAGX,OAAO,KAaT,SAAgB,QAAQ,EAAgB,EAAO,GAAc,CAC3D,IAAM,EAAU,EAAc,EAAM,CAC9B,EACJ,aAAiB,MACb,EAAM,QACN,OAAO,GAAU,SACf,EACA,uBACF,EAAO,EAAU,EAAM,KAAO,IAAA,GAC9B,EAAW,GAAM,WAAW,MAAM,CACpC,OAAO,EAAK,MAAM,EAAE,CAAC,CAAG,KAAS,GACjC,EACE,EACA,EACN,QAAQ,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C,CAAC,OAAU,EAAS,CAMxB,SAAS,cACP,EAC0B,CAC1B,IAAM,EAAmC,EAAE,CAE3C,IAAK,GAAM,CAAC,EAAK,KAAU,OAAO,QAAQ,EAAO,CAC3C,QAAQ,EAAM,GAChB,EAAO,GAAO,GAIlB,OAAO,EAMT,SAAS,QAAQ,EAAmC,CAClD,GAAsB,OAAO,GAAU,WAAnC,EAA6C,MAAO,GACxD,IAAM,EAAW,QAAQ,IAAI,EAAO,IAAI,CACxC,GAAyB,OAAO,GAAa,WAAzC,EAAmD,MAAO,GAC9D,IAAM,EAAQ,QAAQ,IAAI,EAAU,QAAQ,CAG5C,OAAyB,OAAO,GAAU,YAAnC,GAA+C,YAAa,EAMrE,SAAS,cAAc,EAAyB,CAY9C,OALE,IAAU,MACT,OAAO,GAAU,UAAY,OAAO,GAAU,WAExC,GAGP,QAAQ,IAAI,EAAO,UAAU,GAAK,IAAA,IAClC,QAAQ,IAAI,EAAO,UAAU,GAAK,IAAA,GAsBtC,SAAgB,aACd,EAQG,CACH,OAAO"}
1
+ {"version":3,"file":"utils-C3r4gO3Y.mjs","names":[],"sources":["../src/cli/utils.ts"],"sourcesContent":["/**\n * CLI Utilities\n *\n * Configuration loading and other CLI utilities.\n *\n * Config file pattern similar to:\n * - drizzle.config.ts\n * - prisma (uses schema.prisma but we use TS)\n */\n\nimport { existsSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { loadEnvFile } from \"node:process\";\nimport { createJiti } from \"jiti\";\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { withSuppressedFailure } from \"../drivers/shared/suppressed-failure\";\nimport { isVibORMError } from \"../errors\";\nimport type { MigrationClient } from \"../migrations/push/planner\";\nimport type { MigrationStorageWriter } from \"../migrations/storage/contract\";\nimport type { ResolveCallback } from \"../migrations/types\";\nimport type { AnyModel } from \"../schema/model\";\nimport { validateSchemaOrThrow } from \"../schema/validation\";\n\n// =============================================================================\n// CONFIG TYPES\n// =============================================================================\n\n/**\n * Migration configuration options.\n */\nexport interface MigrationConfig {\n /** Estate directory (default: \"./migrations\") */\n dir?: string;\n /** Immutable exact physical table scope; include junctions and rename destinations. */\n tables?: readonly string[];\n /** Explicit rename, destructive-change and enum-value decisions for CLI planning. */\n resolve?: ResolveCallback;\n /**\n * Estate storage writer. Defaults to filesystem storage at `dir`.\n *\n * @example\n * ```ts\n * import { createFsStorageWriter } from \"viborm/migrations/storage/fs\";\n *\n * migrations: {\n * storage: createFsStorageWriter(\"./migrations\"),\n * }\n * ```\n */\n storage?: MigrationStorageWriter;\n}\n\n/**\n * VibORM configuration file format.\n *\n * Example viborm.config.ts:\n * ```ts\n * import { defineConfig } from \"viborm/config\";\n * import { client } from \"./src/db\";\n *\n * export default defineConfig({\n * client,\n * });\n * ```\n */\nexport interface VibORMConfig {\n /** VibORM client instance */\n client: MigrationClient & { $disconnect(): Promise<void> };\n /** Optional: Migration configuration */\n migrations?: MigrationConfig;\n}\n\nexport interface LoadConfigOptions {\n /** Path to config file (default: ./viborm.config.ts) */\n config?: string;\n /** Leave validation to the caller (`viborm check` reports every issue). */\n skipValidation?: boolean;\n}\n\nexport interface LoadedConfig {\n client: VibORMConfig[\"client\"];\n driver: AnyDriver;\n models: Record<string, AnyModel>;\n migrations?: MigrationConfig;\n}\n\n// =============================================================================\n// CONFIG FILE DISCOVERY\n// =============================================================================\n\nconst CONFIG_FILES = [\n \"viborm.config.ts\",\n \"viborm.config.mts\",\n \"viborm.config.js\",\n \"viborm.config.mjs\",\n];\n\n/**\n * Finds the first existing file from a list of candidates.\n */\nfunction findFile(cwd: string, candidates: string[]): string | null {\n for (const candidate of candidates) {\n const fullPath = resolve(cwd, candidate);\n if (existsSync(fullPath)) {\n return fullPath;\n }\n }\n return null;\n}\n\n// =============================================================================\n// CONFIG LOADING\n// =============================================================================\n\n/**\n * Loads VibORM configuration from viborm.config.ts file.\n *\n * The config file should export a default configuration object with:\n * - client: VibORM client instance created with createClient()\n */\nexport function failCli(error: unknown, json = false): never {\n const trusted = isVibORMError(error);\n const message =\n error instanceof Error\n ? error.message\n : typeof error === \"string\"\n ? error\n : \"CLI operation failed\";\n const code = trusted ? error.code : undefined;\n const exitCode = code?.startsWith(\"V11\")\n ? Number(code.slice(1)) - 11_000 + 10\n : trusted\n ? 2\n : 1;\n process.stderr.write(\n json\n ? `${JSON.stringify({ error: trusted ? error.toJSON() : { name: error instanceof Error ? error.name : \"Error\", message }, exitCode })}\\n`\n : `${code ? `[${code}] ` : \"\"}${message}\\n`\n );\n process.exit(exitCode);\n}\n\n/** Await owned CLI cleanup before reporting either the primary or cleanup failure. */\nexport async function finishCli(\n client: { $disconnect(): Promise<void> } | undefined,\n failure: { value: unknown } | undefined,\n json = false\n): Promise<void> {\n let outcome = failure;\n try {\n await client?.$disconnect();\n } catch (cleanup) {\n outcome = {\n value: failure ? withSuppressedFailure(failure.value, cleanup) : cleanup,\n };\n }\n if (outcome) {\n if (json) failCli(outcome.value, true);\n else failCli(outcome.value);\n }\n}\n\n/** Every command's frame: load the config, own its client, report through {@link finishCli}. */\nexport async function runCli(\n load: LoadConfigOptions,\n json: boolean | undefined,\n body: (config: LoadedConfig) => Promise<void>\n): Promise<void> {\n let client: { $disconnect(): Promise<void> } | undefined;\n let failure: { value: unknown } | undefined;\n try {\n const config = await loadConfig(load);\n client = config.client;\n await body(config);\n } catch (error) {\n failure = { value: error };\n } finally {\n await finishCli(client, failure, json);\n }\n}\n\n/** JSON for `--json`, else an indented outline of the same value. */\nexport function printJson(value: unknown, json: boolean): void {\n if (json) {\n process.stdout.write(`${JSON.stringify(value, null, 2)}\\n`);\n return;\n }\n const lines: string[] = [];\n const render = (item: unknown, indent = \"\") => {\n if (Array.isArray(item)) {\n for (const entry of item) {\n lines.push(`${indent}-`);\n render(entry, `${indent} `);\n }\n if (item.length === 0) lines.push(`${indent}(none)`);\n } else if (item !== null && typeof item === \"object\") {\n for (const [key, entry] of Object.entries(item)) {\n if (entry !== null && typeof entry === \"object\") {\n lines.push(`${indent}${key}:`);\n render(entry, `${indent} `);\n } else lines.push(`${indent}${key}: ${String(entry)}`);\n }\n } else lines.push(`${indent}${String(item)}`);\n };\n render(value);\n process.stdout.write(`${lines.join(\"\\n\")}\\n`);\n}\n\nexport async function loadConfig(\n options: LoadConfigOptions = {}\n): Promise<LoadedConfig> {\n const cwd = process.cwd();\n const envPath = resolve(cwd, \".env\");\n if (existsSync(envPath)) loadEnvFile(envPath);\n\n // Find config file\n const configPath = options.config\n ? resolve(cwd, options.config)\n : findFile(cwd, CONFIG_FILES);\n\n if (!(configPath && existsSync(configPath))) {\n const searchedPaths = options.config ? [options.config] : CONFIG_FILES;\n\n throw new Error(\n \"Could not find VibORM configuration file.\\n\\n\" +\n `Searched for:\\n${searchedPaths.map((f) => ` - ${f}`).join(\"\\n\")}\\n\\n` +\n \"Create a viborm.config.ts file:\\n\\n\" +\n ` import { defineConfig } from \"viborm/config\";\\n` +\n ` import { client } from \"./src/db\";\\n\\n` +\n \" export default defineConfig({\\n\" +\n \" client,\\n\" +\n \" });\\n\"\n );\n }\n\n // Load the config file\n const configModule = await loadCliModule<\n VibORMConfig & { default?: VibORMConfig; config?: VibORMConfig }\n >(configPath);\n\n // Extract config (handle both default export and named export)\n const config: VibORMConfig =\n (Object.hasOwn(configModule, \"default\") && configModule.default) ||\n configModule.config ||\n configModule;\n\n // Validate client\n if (!config.client) {\n throw new Error(\n `Missing \"client\" in ${configPath}.\\n\\n` +\n \"Your config should include a VibORM client:\\n\\n\" +\n ` import { createClient } from \"viborm\";\\n` +\n \" const client = createClient({ driver, schema });\\n\\n\" +\n \" export default defineConfig({\\n\" +\n \" client,\\n\" +\n \" });\\n\"\n );\n }\n\n if (!isValidClient(config.client)) {\n throw new Error(\n `Invalid \"client\" in ${configPath}.\\n\\n` +\n \"The client must be created with createClient().\\n\"\n );\n }\n\n // Extract driver and schema from client\n const driver = config.client.$driver;\n const schemaInput = config.client.$schema;\n\n // Extract models from schema (filter out non-model exports)\n const models = extractModels(schemaInput);\n\n if (Object.keys(models).length === 0) {\n throw new Error(\n `No models found in client schema from ${configPath}.\\n\\n` +\n \"Make sure your client was created with schema models:\\n\\n\" +\n \" // src/schema.ts\\n\" +\n ` import { s } from \"viborm\";\\n\\n` +\n \" export const user = s.model({\\n\" +\n \" id: s.string().id(),\\n\" +\n \" name: s.string(),\\n\" +\n \" });\\n\"\n );\n }\n\n // Validate schema before proceeding\n if (!options.skipValidation) validateSchemaOrThrow(models);\n\n return {\n client: config.client,\n driver,\n models,\n migrations: config.migrations,\n };\n}\n\n/**\n * Dynamically imports a TypeScript/JavaScript module.\n */\nexport function loadCliModule<T>(filePath: string): Promise<T> {\n // Dependency imports need CJS interop; consumers select only authored defaults.\n return createJiti(filePath, {\n tsconfigPaths: true,\n interopDefault: true,\n }).import<T>(filePath);\n}\n\n/**\n * Extracts model objects from a module by checking for Model instances.\n */\nfunction extractModels(\n schema: Record<string, unknown>\n): Record<string, AnyModel> {\n const models: Record<string, AnyModel> = {};\n\n for (const [key, value] of Object.entries(schema)) {\n if (isModel(value)) {\n models[key] = value;\n }\n }\n\n return models;\n}\n\n/**\n * Checks if a value is a VibORM Model instance.\n */\nfunction isModel(value: unknown): value is AnyModel {\n if (value === null || typeof value !== \"object\") return false;\n const metadata = Reflect.get(value, \"~\");\n if (metadata === null || typeof metadata !== \"object\") return false;\n const state = Reflect.get(metadata, \"state\");\n // Model state exposes `scalars`/`relations` (never `fields`); the rest of\n // the codebase discriminates models the same way (see serializer).\n return state !== null && typeof state === \"object\" && \"scalars\" in state;\n}\n\n/**\n * Checks if a value is a valid VibORM client instance.\n */\nfunction isValidClient(value: unknown): boolean {\n // The client is a Proxy whose only trap is `get`, so `\"$driver\" in value`\n // (which triggers the `has` trap / falls back to the bare target) is always\n // false. Probe via property access instead.\n // `typeof null === \"object\"`, so null has to be refused here: Reflect.get\n // throws on it rather than answering undefined.\n if (\n value === null ||\n (typeof value !== \"object\" && typeof value !== \"function\")\n ) {\n return false;\n }\n return (\n Reflect.get(value, \"$driver\") !== undefined &&\n Reflect.get(value, \"$schema\") !== undefined\n );\n}\n\n// =============================================================================\n// DEFINE CONFIG HELPER\n// =============================================================================\n\n/**\n * Helper function for defining VibORM configuration with type safety.\n *\n * @example\n * ```ts\n * // viborm.config.ts\n * import { defineConfig } from \"viborm/config\";\n * import { client } from \"./src/db\";\n *\n * export default defineConfig({\n * client,\n * });\n * ```\n */\nexport function defineConfig<const C extends VibORMConfig>(\n config: C &\n Record<Exclude<keyof C, keyof VibORMConfig>, never> &\n (C extends { migrations: infer M }\n ? {\n migrations: M &\n Record<Exclude<keyof M, keyof MigrationConfig>, never>;\n }\n : unknown)\n): C {\n return config;\n}\n"],"mappings":"0UA0FA,MAAM,EAAe,CACnB,mBACA,oBACA,mBACA,oBACD,CAKD,SAAS,SAAS,EAAa,EAAqC,CAClE,IAAK,IAAM,KAAa,EAAY,CAClC,IAAM,EAAW,EAAQ,EAAK,EAAU,CACxC,GAAI,EAAW,EAAS,CACtB,OAAO,EAGX,OAAO,KAaT,SAAgB,QAAQ,EAAgB,EAAO,GAAc,CAC3D,IAAM,EAAU,EAAc,EAAM,CAC9B,EACJ,aAAiB,MACb,EAAM,QACN,OAAO,GAAU,SACf,EACA,uBACF,EAAO,EAAU,EAAM,KAAO,IAAA,GAC9B,EAAW,GAAM,WAAW,MAAM,CACpC,OAAO,EAAK,MAAM,EAAE,CAAC,CAAG,KAAS,GACjC,EACE,EACA,EACN,QAAQ,OAAO,MACb,EACI,GAAG,KAAK,UAAU,CAAE,MAAO,EAAU,EAAM,QAAQ,CAAG,CAAE,KAAM,aAAiB,MAAQ,EAAM,KAAO,QAAS,UAAS,CAAE,WAAU,CAAC,CAAC,IACpI,GAAG,EAAO,IAAI,EAAK,IAAM,KAAK,EAAQ,IAC3C,CACD,QAAQ,KAAK,EAAS,CAIxB,eAAsB,UACpB,EACA,EACA,EAAO,GACQ,CACf,IAAI,EAAU,EACd,GAAI,CACF,MAAM,GAAQ,aAAa,OACpB,EAAS,CAChB,EAAU,C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9D,IAAM,EAAQ,QAAQ,IAAI,EAAU,QAAQ,CAG5C,OAAyB,OAAO,GAAU,YAAnC,GAA+C,YAAa,EAMrE,SAAS,cAAc,EAAyB,CAY9C,OALE,IAAU,MACT,OAAO,GAAU,UAAY,OAAO,GAAU,WAExC,GAGP,QAAQ,IAAI,EAAO,UAAU,GAAK,IAAA,IAClC,QAAQ,IAAI,EAAO,UAAU,GAAK,IAAA,GAsBtC,SAAgB,aACd,EAQG,CACH,OAAO"}
@@ -0,0 +1,2 @@
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{a as t,c as n,i as r,n as i,o as a,r as o,s}from"./value-guards-CK9guf2Z.mjs";import{t as c}from"./validation-BamBwne9.mjs";import{$ as l,I as u,L as ee,N as te,P as d,Pt as f,Q as p,R as ne,X as m,Y as re,Z as h,a as g,d as ie,f as _,i as ae,jt as v,nt as oe,o as se,p as y,r as ce,rt as b,tt as x,z as S}from"./geo-point-codec-DyEHMdJg.mjs";import{o as le,r as C}from"./sql-Bhxq9arK.mjs";const w=Symbol.for(`viborm.field-ref`);function isFieldRef(e){if(typeof e!=`object`||!e)return!1;let t=e[w];return typeof t==`object`&&!!t}function fieldRefPayload(e){return e[w]}function formatFieldRef(e){let t=fieldRefPayload(e);return`${t.model}.${t.field}`}function createFieldRef(e,t,n,r){return Object.freeze({[w]:Object.freeze({model:e,field:t,type:n,list:r})})}const UNKNOWN_FIELD=(e,t,n)=>Error(`Unknown scalar field "${t}" on model '${e}'. Known fields: ${n.join(`, `)}.`);function createModelFieldRefs(e,t){let n=new Map,r=t[`~`].state.scalars,i=Object.keys(r).filter(e=>r[e][`~`].state.type!==`point`),a=new Set(i);return new Proxy(Object.create(null),{get(t,o){if(typeof o!=`string`)return;let s=n.get(o);if(s)return s;let c=a.has(o)?r[o]:void 0;if(!c)throw UNKNOWN_FIELD(e,o,i);let l=c[`~`].state,u=createFieldRef(e,o,l.type,l.array);return n.set(o,u),u},has:(e,t)=>typeof t==`string`&&a.has(t),ownKeys:()=>i,getOwnPropertyDescriptor:(e,t)=>typeof t==`string`&&a.has(t)?{enumerable:!0,configurable:!0}:void 0})}const T=Symbol.for(`viborm.json-null`);var JsonNullSentinel=class{[T];kind;constructor(e){this[T]=e,this.kind=e,Object.freeze(this)}toString(){return this.kind}toJSON(){return`viborm.json-null:${this.kind}`}};const ue=new JsonNullSentinel(`DbNull`),E=new JsonNullSentinel(`JsonNull`),de=new JsonNullSentinel(`AnyNull`),fe=new Set([`DbNull`,`JsonNull`,`AnyNull`]);function isJsonNullSentinel(e){if(typeof e!=`object`||!e)return!1;let t=e[T];return typeof t==`string`&&fe.has(t)}function jsonNullKindOf(e){return isJsonNullSentinel(e)?e.kind:void 0}function refuseRelationInput(e,t,n,r){throw new c({kind:`schema-builder`,builder:e,path:t},[{path:t,message:n}],r===void 0?void 0:{cause:r})}function isPlainRecord(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function declaredKeys(e){return Object.keys(e)}function hasExactKeys(e,t){return e.length===t.length&&t.every(t=>e.includes(t))}function readCallerProperty(e,t,n,r){try{return Reflect.get(t,n)}catch(t){refuseRelationInput(e,r,`Could not read relation input '${r}'`,normalizeThrown(t,`Reading relation input '${r}' threw a non-Error value`))}}function normalizeRelationName(e,t){return(typeof t!=`string`||t.length===0)&&refuseRelationInput(e,`name`,`A relation name must be a non-empty string`),t}function normalizeReferentialAction(e,t){if(t===`cascade`||t===`setNull`||t===`restrict`||t===`noAction`)return t;refuseRelationInput(`s.toOne`,e,`A referential action must be one of 'cascade', 'setNull', 'restrict' or 'noAction'`)}function normalizeJunctionAction(e,t){if(t===`cascade`||t===`restrict`||t===`noAction`)return t;refuseRelationInput(`s.toMany`,e,`A junction referential action must be one of 'cascade', 'restrict' or 'noAction'; 'setNull' cannot null a membership-key member`)}function normalizeJunctionActions(e,t){if(typeof t!=`object`||!t){let n=normalizeJunctionAction(e,t);return Object.freeze({source:n,target:n})}isPlainRecord(t)&&hasExactKeys(declaredKeys(t),[`source`,`target`])||refuseRelationInput(`s.toMany`,e,`A junction '${e}' map is a plain record naming exactly 'source' (the foreign key to the declaring model) and 'target' (the foreign key to its target model)`);let side=n=>normalizeJunctionAction(`${e}.${n}`,readCallerProperty(`s.toMany`,t,n,`${e}.${n}`));return Object.freeze({source:side(`source`),target:side(`target`)})}function normalizeJunctionToken(e,t){return f(t)||refuseRelationInput(`s.toMany`,e,`Junction '${e}' must be a valid schema identifier`),t}function normalizeFieldTuple(e,t,n){let[r,...i]=n;return r===void 0&&refuseRelationInput(e,t,`'${t}' requires at least one field key`),new Set(n).size!==n.length&&refuseRelationInput(e,t,`'${t}' cannot repeat a field key in one foreign-key tuple`),[r,...i]}function createTargetSettlement(e){let t=new Map;return n=>{let r=n??``,i=t.get(r);if(i===void 0&&(i=settleTargetOnce(e,n),t.set(r,i)),i.settled===`value`)return i.value;throw i.error}}function settleTargetOnce(e,t){let n=e(t);if(typeof n!=`function`)return{settled:`error`,error:Error(`Relation target getter is not a function`)};try{return{settled:`value`,value:n()}}catch(e){return{settled:`error`,error:normalizeThrown(e,`Relation target getter threw a non-Error value`)}}}function normalizeThrown(e,t){if(e instanceof Error)return e;let n;try{n=typeof e==`symbol`?e.toString():String(e)}catch{n=`<unrenderable non-Error value>`}return Error(`${t}: ${n}`)}function array(e){let t=e[`~standard`].validate,n=h(`array`,e=>oe(e,t));return n.item=e,n}const D=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected Uint8Array`})])}),O=Object.getPrototypeOf(Uint8Array.prototype);function localBufferPrototype(){try{let e=Reflect.get(globalThis,`Buffer`);if(typeof e!=`function`)return;let t=Reflect.get(e,`prototype`);if(typeof t==`object`&&t&&Object.getPrototypeOf(t)===Uint8Array.prototype)return t}catch{return}}const pe=localBufferPrototype();function hasOwnViewMetadata(e){return Object.getOwnPropertyDescriptor(e,`buffer`)!==void 0||Object.getOwnPropertyDescriptor(e,`byteOffset`)!==void 0||Object.getOwnPropertyDescriptor(e,`byteLength`)!==void 0}function hasTrustedLocalPrototype(e){let t=Object.getPrototypeOf(e);return(t===Uint8Array.prototype||t===pe)&&!hasOwnViewMetadata(e)}function validateBlob(e){try{if(!n(e))return D;let t=Reflect.get(O,`buffer`,e),r=Reflect.get(O,`byteOffset`,e),i=Reflect.get(O,`byteLength`,e),a=hasTrustedLocalPrototype(e),o=new Uint8Array(t,r,i);return l(a?e:o)}catch{return D}}function blob(e){return m(`blob`,validateBlob,e)}const k=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected boolean`})])});function validateBoolean(e){return i(e)?l(e):k}function boolean(e){return m(`boolean`,validateBoolean,e)}const A=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected Date`})])}),j=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected valid Date`})])});function validateDate(e){if(!o(e))return A;let t=Date.prototype.getTime.call(e);return Number.isNaN(t)?j:e instanceof Date?l(e):l(new Date(t))}function date(e){return m(`date`,validateDate,e)}const M=Object.freeze({issues:Object.freeze([Object.freeze({message:d})])});function validateDecimal(e){let t=u(e);return t===void 0?M:l(t)}function buildDecimalValueValidator(e){let t=e?.schema,n=e?.decimal,validate=validateDecimal;if(t!==void 0){let e=t[`~standard`].validate,n=validate;validate=t=>{let r=n(t);if(r.issues)return r;let i=e(te(r.value));if(`then`in i)return v(i),p(`Async schemas are not supported`);if(i.issues)return x(i.issues);let a=ee(i.value);return a===void 0?p(`Expected a Decimal: a custom decimal schema may refine or brand the value it is given, but not return a string, a number, or a value of any other type`):l(a)}}if(n!==void 0){let e=validate;validate=t=>{let r=e(t);if(r.issues)return r;let i=ne(r.value,n.precision,n.scale);return i===void 0?r:p(i)}}return validate}function decimal(e){let t=e===void 0?void 0:{...e,schema:void 0};return m(`decimal`,buildDecimalValueValidator(e),t)}function enum_(e,t){let n=new Set(e),baseValidate=t=>s(t)&&n.has(t)?l(t):{issues:[{message:`Expected one of: ${e.join(` | `)}`}]};return m(`enum`,baseValidate,t,{values:e})}function getNestedValue(e,t){let n=t.split(`.`),r=e;for(let e of n){if(r==null)return;r=r[e]}return r}function declaresPath(e,t){let n=t.lastIndexOf(`.`),r=n===-1?e:getNestedValue(e,t.slice(0,n));return a(r)&&t.slice(n+1)in r}function entriesFromObject(e,t){let n={};for(let r of Object.keys(e)){let i=getNestedValue(e[r],t);i!==void 0&&(n[r]=i)}return Object.keys(e).length>0&&Object.keys(n).length===0&&refuseUnmatchedPath(e,t),n}function fromObject(e,t,n){return S(entriesFromObject(e,t),n)}function refuseUnmatchedPath(e,t){if(!Object.values(e).some(e=>declaresPath(e,t)))throw new c({kind:`schema-builder`,builder:`fromObject`,path:t},[{path:t,message:`fromObject path "${t}" did not match any entries in the source object`}])}const N=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,3})?(?:Z|[+-](\d{2}):(\d{2}))$/,P=/^(\d{4})-(\d{2})-(\d{2})$/,F=/^\d{2}:\d{2}:\d{2}(\.\d{1,3})?$/,I=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected string or Date`})])}),L=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected ISO timestamp format (YYYY-MM-DDTHH:mm:ss.sssZ)`})])}),R=Object.freeze({issues:Object.freeze([Object.freeze({message:`Invalid date in ISO timestamp`})])});function validateIsoTimestamp(e){if(o(e))return _(Date.prototype.getTime.call(e))?l(Date.prototype.toISOString.call(e)):R;if(!s(e))return I;let t=N.exec(e);return t?!(y(Number(t[1]),Number(t[2]),Number(t[3]))&&ie(Number(t[4]),Number(t[5]),Number(t[6])))||Number(t[7]??0)>23||Number(t[8]??0)>59||!_(Date.parse(e))?R:l(new Date(e).toISOString()):L}function isoTimestamp(e){return m(`iso_timestamp`,validateIsoTimestamp,e)}const z=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected ISO date format (YYYY-MM-DD)`})])}),B=Object.freeze({issues:Object.freeze([Object.freeze({message:`Invalid date`})])});function validateIsoDate(e){if(o(e))return _(Date.prototype.getTime.call(e))?l(Date.prototype.toISOString.call(e).slice(0,10)):B;if(!s(e))return I;let t=P.exec(e);return t?y(Number(t[1]),Number(t[2]),Number(t[3]))?l(e):B:z}function isoDate(e){return m(`iso_date`,validateIsoDate,e)}const me=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected ISO time format (HH:mm:ss)`})])}),V=Object.freeze({issues:Object.freeze([Object.freeze({message:`Invalid time`})])});function validateIsoTime(e){if(o(e))return Number.isNaN(Date.prototype.getTime.call(e))?V:l(Date.prototype.toISOString.call(e).split(`T`)[1].replace(`Z`,``));if(!s(e))return I;if(!F.test(e))return me;let t=e.split(`:`),n=Number(t[0]),r=Number(t[1]),i=Math.trunc(Number(t[2]));return n<0||n>23||r<0||r>59||i<0||i>59?V:l(e.padEnd(12,e.includes(`.`)?`0`:`.000`))}function isoTime(e){return m(`iso_time`,validateIsoTime,e)}const he=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected JSON-compatible value`})])}),H=Symbol(`invalid JSON`);function normalizeJson(e,n=new WeakMap){if(e===null||s(e)||i(e))return e;if(t(e))return Number.isFinite(e)?e:H;if(!(a(e)||Array.isArray(e))||isFieldRef(e))return H;let r=n.get(e);if(r!==void 0)return r;if(n.set(e,H),Array.isArray(e)){let t=[];for(let r of e){let e=r===void 0?null:normalizeJson(r,n);if(e===H)return H;t.push(e)}return n.set(e,t),t}let o=Object.getPrototypeOf(e);if(o!==null&&o!==Object.prototype)return H;let c={};for(let t of Object.keys(e)){let r=e[t];if(r===void 0)continue;let i=normalizeJson(r,n);if(i===H)return H;Object.defineProperty(c,t,{value:i,enumerable:!0,configurable:!0,writable:!0})}return n.set(e,c),c}function validateJson(e){let t=normalizeJson(e);return t===H?he:l(t)}function json(e){return m(`json`,validateJson,e)}const U=[`DbNull`,`JsonNull`,`AnyNull`];function listKinds(e){return e.length===1?e[0]:`${e.slice(0,-1).join(`, `)} or ${e.at(-1)}`}function refuseSentinel(e,t,n){return p(`${U.filter(e=>!t.includes(e)).length===U.length?`JSON null sentinels are not supported in ${n}`:`${e.kind} is not supported in ${n}; that slot accepts ${listKinds(t)}`}.`)}function checkSentinel(e,t,n){return t.includes(e.kind)?l(e):refuseSentinel(e,t,n)}function copyOptionality(e,t,n){e.allowed=n,e.wrapped=t,e.acceptsUndefined=t.acceptsUndefined===!0}function jsonNullOr(e,t,n){let r=h(`json_null_or`,r=>isJsonNullSentinel(r)?checkSentinel(r,e,n):b(t,r));return copyOptionality(r,t,e),r}function jsonWrite(e,t,n,r){let i=h(`json_write`,i=>{if(isJsonNullSentinel(i))return checkSentinel(i,e,n);if(i===null)return p(r);let a=b(t,i);return!a.issues&&a.value===null&&i!==void 0?checkSentinel(E,e,n):a});return copyOptionality(i,t,e),i}function lazy(e){let t=e,n,resolve=()=>(t&&=(n=t(),void 0),n);return new Proxy({},{get(e,t,n){let i=resolve(),a=Reflect.get(i,t,n);return r(a)?a.bind(i):a},has(e,t){return Reflect.has(resolve(),t)},ownKeys(e){return Reflect.ownKeys(resolve())},getOwnPropertyDescriptor(e,t){return Reflect.getOwnPropertyDescriptor(resolve(),t)},getPrototypeOf(e){return Reflect.getPrototypeOf(resolve())}})}function lazyRef(e){let t=e,n,resolve=()=>(t&&=(n=t(),void 0),n);return{type:`lazyRef`,get wrapped(){return resolve()},get entries(){return resolve().entries},"~standard":{version:1,vendor:`viborm`,validate:e=>resolve()[`~standard`].validate(e),get jsonSchema(){return resolve()[`~standard`].jsonSchema}}}}function literal(e,t){let n=e===null?`null`:String(e),r=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected literal: ${n}`})])}),baseValidate=t=>t===e?l(t):r;return m(`literal`,baseValidate,t,{value:e})}function nullable(e){let t=e[`~standard`].validate,n=h(`nullable`,e=>e===null?l(null):t(e));return n.wrapped=e,n}function maybeNullable(e,t){return t?nullable(e):e}function omit(e,t){return S(e.entries,{...e.options||{},omit:t})}let W=0,G=!0;function withoutFilterDepthBound(e){let t=G;G=!1;try{return e()}finally{G=t}}function limitFilterDepth(e){let t=e[`~standard`].validate;return Object.defineProperty(e[`~standard`],`validate`,{value:e=>{if(G&&W>=16)return p(`Filter nesting exceeds 16 levels`);W++;try{return t(e)}finally{W--}}}),e}const K=new WeakSet,q=new WeakSet;let J,Y;function valueNodeOf(e){if(typeof e==`object`&&e&&K.has(e))return e;let t=J?.value(e);return t!==void 0&&K.add(t),t}function valueNodeOr(e){let t=h(`value_node_or`,t=>{let n=valueNodeOf(t);return n===void 0?b(e,t):l(n)});return Object.assign(t,{wrapped:e,acceptsUndefined:e.acceptsUndefined===!0}),t}function conditionNodeOr(e){let t=e[`~standard`],n=t.validate,admit=e=>{if(!(J&&a(e)&&Object.hasOwn(e,`$if`)))return n(e);let{$if:t,...r}=e,i=J.condition(t);return typeof i==`string`?p(i,[`$if`]):(q.add(i),Object.keys(r).length===0?l(i):n({AND:[r,i]}))};return Object.defineProperty(t,`validate`,{value:e=>{if(typeof e!=`object`||!e)return n(e);if(q.has(e))return l(e);let r=J&&Y;if(!r)return admit(e);let i=r.get(t);i===void 0&&r.set(t,i=new WeakMap);let a=i.get(e);if(a!==void 0)return a;let o=admit(e);return o.issues===void 0&&i.set(e,o),o}}),e}function admittingDomainPredicate(e,t,n=new WeakMap){let r=J,i=Y;J=e,Y=n;try{return withoutFilterDepthBound(t)}finally{J=r,Y=i}}function writtenDepth(e){let t=h(`written_depth`,t=>J&&(t===!0||typeof t==`object`&&t&&t.depth===void 0)?p(`A row predicate's recurse must write its depth (false, or a number)`):b(e,t));return Object.assign(t,{wrapped:e,acceptsUndefined:e.acceptsUndefined===!0}),t}let X;const Z=new WeakMap;function runInOperandScope(e,t){let n=X;X=e;try{return t()}finally{X=n}}function scopeOperands(e,t){let n=e[`~standard`],r=n.validate;return n.validate=e=>runInOperandScope(t,()=>r(e)),limitFilterDepth(e)}function currentContext(){let e=X;if(!e)return;let t=Z.get(e);if(t)return t;let n={fields:createModelFieldRefs(e[`~`].names.ts??`unknown`,e),sql:le};return Z.set(e,n),n}const Q="A filter callback must return a field reference (ctx.fields.<field>) or an SQL fragment (ctx.sql`…`)";function describe$1(e){return e===null?`null`:Array.isArray(e)?`an array`:`a value of type '${typeof e}'`}e(describe$1,`describe`);function resolveCallback(e,t){let n=currentContext();if(!n)return p(`A filter callback is only meaningful inside a model filter, where the model whose columns it names is known.`);let i;try{i=e(n)}catch(e){return p(`Filter callback threw: ${e instanceof Error?e.message:String(e)}`)}return isFieldRef(i)?checkRef(i,t):C(i)?l(i):a(i)&&r(i.then)?(v(i),p(`${Q}; it returned a promise. Validation is synchronous, so a filter callback cannot be async.`)):p(`${Q}; it returned ${describe$1(i)}.`)}function comparisonOperand(e,t){let n=h(`comparison_operand`,n=>{let i=valueNodeOf(n);return i===void 0?r(n)?resolveCallback(n,e):isFieldRef(n)?checkRef(n,e):C(n)?l(n):b(t,n):l(i)});return n.fieldType=e,n.wrapped=t,n.acceptsUndefined=t.acceptsUndefined===!0,n}function fieldRefOr(e,t){let n=h(`field_ref_or`,n=>{let r=valueNodeOf(n);return r===void 0?isFieldRef(n)?checkRef(n,e):b(t,n):l(r)});return n.fieldType=e,n.wrapped=t,n.acceptsUndefined=t.acceptsUndefined===!0,n}function closeOperands(e,t,n){let r=e[`~standard`],i={"~standard":{version:r.version,vendor:r.vendor,validate:r.validate}},a=h(`no_field_ref`,e=>{let r=findOpaqueOperand(e,n);if(r)return p(`${r} is not supported in ${t}.`);let a=b(i,e);if(a.issues)return a;let o=findOpaqueOperand(a.value,n);return o?p(`${o} is not supported in ${t}.`):a});return a.wrapped=e,a.acceptsUndefined=e.acceptsUndefined??!1,a}function noFieldRef(e,t){return closeOperands(e,t,!1)}function noOperandExpression(e,t){return closeOperands(e,t,!0)}function findOpaqueOperand(e,t){let n=new WeakSet,r=[e];for(;r.length>0;){let e=r.pop();if(t&&typeof e==`function`)return`A filter callback`;if(!(typeof e!=`object`||!e)){if(isFieldRef(e)){let t=fieldRefPayload(e);return`Field reference '${t.model}.${t.field}'`}if(t&&C(e))return`An SQL fragment`;if(!n.has(e)&&(n.add(e),!(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))){if(Array.isArray(e)){for(let t of e)r.push(t);continue}for(let t of Object.keys(e))r.push(e[t])}}}}function checkRef(e,t){let n=fieldRefPayload(e);return n.list?p(`Field reference '${n.model}.${n.field}' is a list field; list fields cannot be used as a comparison operand.`):n.type===t?l(e):p(`Field reference '${n.model}.${n.field}' is of type '${n.type}', but a '${t}' operand is required here.`)}function transform(e){return{type:`transform`,transform:e}}function pipe(e,...t){let n=h(`pipe`,n=>{let r=b(e,n);if(r.issues)return r;let i=r.value;for(let e of t)if(e.type===`transform`)try{i=e.transform(i)}catch(e){return p(`Transform failed: ${e instanceof Error?e.message:String(e)}`)}return l(i)});return n.schema=e,n.actions=t,n}function point(e){return m(`point`,ce,e)}function record(e,t){let n=h(`record`,n=>{if(!a(n))return p(`Expected object, received ${Array.isArray(n)?`array`:typeof n}`);let r={};for(let[i,a]of Object.entries(n)){let n=b(e,i);if(n.issues)return p(`Invalid key "${i}": ${n.issues[0].message}`,[i]);let o=b(t,a);if(o.issues){let e=o.issues[0],t=e.path?[i].concat(e.path):[i];return p(e.message,t)}r[n.value]=o.value}return l(r)});return n.key=e,n.value=t,n}function entriesFromKeys(e,t){let n={};for(let r of e)n[r]=t;return n}function fromKeys(e,t,n){return S(entriesFromKeys(e,t),n)}function refused(e){return h(`refused`,()=>p(e))}function coerce(e,t){let n=h(`transform`,n=>{let r=b(e,n);if(r.issues)return{issues:r.issues};try{return l(t(r.value))}catch(e){return p(`Transform failed: ${e instanceof Error?e.message:String(e)}`)}});return n.wrapped=e,n.acceptsUndefined=e.acceptsUndefined===!0,n}const ge=coerce,shorthandFilter=e=>coerce(e,e=>({equals:e})),shorthandUpdate=e=>coerce(e,e=>({set:e})),shorthandArray=e=>coerce(e,e=>[e]),_e=Object.freeze([Object.freeze({message:`Async schemas are not supported`})]);function tagsOf(e){let t,n=new Map;for(let r of e){let{type:e,entries:i,options:a}=r;if(e!==`object`||!i||a?.array===!0)return;t??=Object.keys(i).find(e=>isLiteral(i[e]));let o=t===void 0?void 0:i[t];if(!(isLiteral(o)&&o.acceptsUndefined!==!0)||n.has(o.value)||a?.omit?.includes(t))return;n.set(o.value,r[`~standard`].validate)}return t===void 0||n.size<2?void 0:{key:t,members:n}}function isLiteral(e){return a(e)&&e.type===`literal`}function settled(e){return`then`in e?(v(e),{issues:_e}):e}function describe({message:e,path:t}){return t?.length?`${t.join(`.`)}: ${e}`:e}function union(e){let t=e.map(e=>e[`~standard`].validate),n=null,r=h(`union`,r=>{n===null&&(n=tagsOf(e));let i=n&&a(r)&&n.members.get(r[n.key]);if(i)return settled(i(r));let o,s=-1,c;for(let e of t){let t=settled(e(r));if(!t.issues)return t;let{issues:n}=t,i=n[0].path?.length??0;if(i>s)o=n,s=i,c=void 0;else if(i===s){let e=describe(n[0]);c??=[describe(o[0])],c.includes(e)||c.push(e)}}return c&&c.length>1?p(c.join(`, or `)):o?{issues:o}:p(`Expected no value: the union has no member`)});return r.options=e,r}const singleOrArray=e=>union([coerce(e,e=>[e]),array(e)]),ve=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected string`})])});function validateString(e){return s(e)?l(e):ve}function string(e){return m(`string`,validateString,e)}const ye=Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected array of numbers`})])});function createVectorValidator(e){let n=e===void 0?null:Object.freeze({issues:Object.freeze([Object.freeze({message:`Expected vector of ${e} dimensions`})])});return r=>{if(!Array.isArray(r))return ye;let i=r.length;for(let e=0;e<i;e++)if(!(t(r[e])&&Number.isFinite(r[e])))return p(`Expected finite number at index ${e}`);return n&&i!==e?n:l(r)}}function vector(e,t){return m(`vector`,createVectorValidator(e),t,{dimensions:e})}const $={string,number:se,integer:g,boolean,bigint:re,decimal,literal,enum:enum_,json,date,isoTimestamp,isoDate,isoTime,blob,vector,point,array,nullable,maybeNullable,optional:ae,object:S,omit,fromObject,union,pipe,transformAction:transform,record,fromKeys,coerce,map:ge,lazy,lazyRef,singleOrArray,shorthandFilter,shorthandUpdate,shorthandArray,comparisonOperand,fieldRefOr,noFieldRef,noOperandExpression,jsonNullOr,jsonWrite,refused};var be=$;export{jsonNullKindOf as A,readCallerProperty as C,E as D,ue as E,fieldRefPayload as M,formatFieldRef as N,JsonNullSentinel as O,isFieldRef as P,normalizeRelationName as S,de as T,isPlainRecord as _,admittingDomainPredicate as a,normalizeJunctionToken as b,writtenDepth as c,validateIsoTime as d,validateIsoTimestamp as f,hasExactKeys as g,declaredKeys as h,scopeOperands as i,createModelFieldRefs as j,isJsonNullSentinel as k,limitFilterDepth as l,createTargetSettlement as m,be as n,conditionNodeOr as o,entriesFromObject as p,entriesFromKeys as r,valueNodeOr as s,$ as t,validateIsoDate as u,normalizeFieldTuple as v,refuseRelationInput as w,normalizeReferentialAction as x,normalizeJunctionActions as y};
2
+ //# sourceMappingURL=v-DtLdBQYg.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"v-DtLdBQYg.mjs","names":["record","parsed","values","result","value","describe","v","v"],"sources":["../src/schema/field-ref.ts","../src/schema/json-null.ts","../src/schema/relation/terminal.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/from-object.ts","../src/validation/primitives/iso.ts","../src/validation/primitives/json.ts","../src/validation/primitives/json-null.ts","../src/validation/primitives/lazy.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"],"sourcesContent":["/**\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 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 field \"${key}\" on model '${modelName}'. Known fields: ${known.join(\", \")}.`\n );\n\n/**\n * The reference table for ONE model: `{ likes, views, … }`, each entry built on\n * first read and memoized.\n *\n * This is what an operand callback receives as `ctx.fields`, built once per\n * model and cached there — a query that never compares columns never builds\n * one, and a model's table costs a single object until a field is read. The\n * model name is passed in because the token carries the model's SCHEMA KEY,\n * which is what the where-builder compares the query scope against (hydration\n * sets `names.ts` to that key — see `hydration.ts`).\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 = model[\"~\"].state.scalars;\n const referenceableNames = Object.keys(scalars).filter(\n (key) => scalars[key]![\"~\"].state.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 = scalar[\"~\"].state;\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","/**\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\"> = new JsonNullSentinel(\n \"DbNull\"\n);\n\n/** The JSON null: the column holds the JSON document `null`. */\nexport const JsonNull: JsonNullSentinel<\"JsonNull\"> = new JsonNullSentinel(\n \"JsonNull\"\n);\n\n/** Either null. Filter positions only — see the module header. */\nexport const AnyNull: JsonNullSentinel<\"AnyNull\"> = new JsonNullSentinel(\n \"AnyNull\"\n);\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","// 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 { ValidationError } from \"@errors\";\nimport { isValidSchemaIdentifier } from \"../identifier\";\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\n/**\n * The one construction-time refusal. Structural input the factories and\n * modifiers can judge on their own never reaches the schema resolver as a\n * `SchemaValidationIssue`; it fails here, at the call the author wrote.\n */\nexport function refuseRelationInput(\n builder: RelationBuilder,\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// =============================================================================\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 relation input '${path}'`,\n normalizeThrown(\n thrown,\n `Reading relation input '${path}' threw a non-Error value`\n )\n );\n }\n}\n\n// =============================================================================\n// MODIFIER TOKENS\n// =============================================================================\n\n/**\n * A relation name is a non-empty PAIRING LABEL, not a SQL identifier: an\n * explicit `.through(...)` lets `\"Post tags/v2\"` name a pair without pretending\n * the label is a database name.\n */\nexport function normalizeRelationName(\n builder: RelationBuilder,\n name: unknown\n): string {\n if (typeof name !== \"string\" || name.length === 0) {\n refuseRelationInput(\n builder,\n \"name\",\n \"A relation name must be a non-empty string\"\n );\n }\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(\n \"s.toOne\",\n path,\n \"A referential action must be one of 'cascade', 'setNull', 'restrict' or 'noAction'\"\n );\n}\n\n/** Junction actions exclude `setNull` at the type level and here. */\nfunction normalizeJunctionAction(\n path: string,\n action: unknown\n): JunctionReferentialAction {\n if (action === \"cascade\" || action === \"restrict\" || action === \"noAction\") {\n return action;\n }\n refuseRelationInput(\n \"s.toMany\",\n path,\n \"A junction referential action must be one of 'cascade', 'restrict' or 'noAction'; 'setNull' cannot null a membership-key member\"\n );\n}\n\n/**\n * The ONE normalization of a junction action declaration. A bare action is the\n * symmetric shorthand and becomes the same pair a `{ source, target }` map\n * spells, so trusted state holds one form and no consumer asks which spelling\n * declared it. The map names both sides and nothing else: an omitted side\n * would silently keep a default the author never chose. Every object is read\n * as a map, so an array or a class instance is told what a map must be rather\n * than which actions exist.\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 `A junction '${path}' map is a plain record naming exactly 'source' (the foreign key to the declaring model) and 'target' (the foreign key to its target model)`\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\n/** One junction table name or side naming token. */\nexport function normalizeJunctionToken(path: string, token: unknown): string {\n if (!isValidSchemaIdentifier(token)) {\n refuseRelationInput(\n \"s.toMany\",\n path,\n `Junction '${path}' must be a valid schema identifier`\n );\n }\n return token;\n}\n\n/** A non-empty foreign-key tuple whose members are distinct. */\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(\n builder,\n path,\n `'${path}' requires at least one field key`\n );\n }\n if (new Set(fields).size !== fields.length) {\n refuseRelationInput(\n builder,\n path,\n `'${path}' cannot repeat a field key in one foreign-key tuple`\n );\n }\n return [head, ...rest];\n}\n\n// =============================================================================\n// TARGET SETTLEMENT\n// =============================================================================\n\ntype SettledTarget =\n | { readonly settled: \"value\"; readonly value: unknown }\n | { readonly settled: \"error\"; readonly error: Error };\n\n/**\n * The declaration-lifetime target cell.\n *\n * A raw getter stays lazy, but it is invoked at most ONCE per target: the first\n * resolution settles its return or one normalized `Error`, and every later\n * consumer — including a second schema graph reusing the same immutable\n * terminal — observes that same outcome. A resolver-local cache alone would let\n * a stateful getter give validation, migrations and the query engine different\n * declaration truth.\n *\n * Only settled outcomes live here. The resolver decides whether a return is a\n * registered model and attaches its own model/field path to any issue, so\n * contextual diagnostics are never cached on the shared terminal.\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.settled === \"value\") return cell.value;\n throw cell.error;\n };\n}\n\nfunction settleTargetOnce(\n readGetter: (variantKey: string | undefined) => unknown,\n variantKey: string | undefined\n): SettledTarget {\n // READING the getter cannot fail: every `readGetter` handed to\n // {@link createTargetSettlement} is one property read over frozen\n // declaration state. INVOKING it can, and that is the one `try` below.\n const getter = readGetter(variantKey);\n // The read still may not produce one: a variant asked without a key or with\n // an unknown one has no entry, and a forged state can carry a non-function\n // target where the factories admit only a getter. Settling that as a failure\n // is what keeps every later consumer from re-reading a target that can never\n // resolve — and from reading `undefined` as a resolved one.\n if (typeof getter !== \"function\") {\n return {\n settled: \"error\",\n error: new Error(\"Relation target getter is not a function\"),\n };\n }\n try {\n return { settled: \"value\", value: getter() };\n } catch (thrown) {\n return {\n settled: \"error\",\n error: normalizeThrown(\n thrown,\n \"Relation target getter threw a non-Error value\"\n ),\n };\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","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, 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 = Object.freeze({\n issues: Object.freeze([Object.freeze({ message: \"Expected Uint8Array\" })]),\n});\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, 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 = Object.freeze({\n issues: Object.freeze([Object.freeze({ message: \"Expected boolean\" })]),\n});\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, 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 = Object.freeze({\n issues: Object.freeze([Object.freeze({ message: \"Expected Date\" })]),\n});\nconst INVALID_DATE_ERROR = Object.freeze({\n issues: Object.freeze([Object.freeze({ message: \"Expected valid Date\" })]),\n});\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 { discardAsyncValidationResult } from \"../parse-failure\";\nimport 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, ok, standardSchemaFailure } 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 = Object.freeze({\n issues: Object.freeze([Object.freeze({ message: DECIMAL_INPUT_REFUSAL })]),\n});\n\nconst DECIMAL_VALUE_ERROR =\n \"Expected a Decimal: a custom decimal schema may refine or brand the value it is given, but not return a string, a number, or a value of any other type\";\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 = refine(toDecimal(parsed.value));\n if (\"then\" in refined) {\n discardAsyncValidationResult(refined);\n return fail(\"Async schemas are not supported\");\n }\n if (refined.issues) {\n return standardSchemaFailure(refined.issues);\n }\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 { ValidationError } from \"@errors\";\nimport type { Cast, ThunkCast, VibSchema } from \"../types\";\nimport { isRecord } from \"../value-guards\";\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 * 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: `fromObject path \"${path}\" did not match any entries in the source object`,\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, 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\n// Pre-computed errors\nconst NOT_STRING_OR_DATE_ERROR = Object.freeze({\n issues: Object.freeze([\n Object.freeze({ message: \"Expected string or Date\" }),\n ]),\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 = Object.freeze({\n issues: Object.freeze([\n Object.freeze({\n message: \"Expected ISO timestamp format (YYYY-MM-DDTHH:mm:ss.sssZ)\",\n }),\n ]),\n});\nconst INVALID_TIMESTAMP_DATE = Object.freeze({\n issues: Object.freeze([\n Object.freeze({ message: \"Invalid date in ISO timestamp\" }),\n ]),\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 const epochMilliseconds = Date.prototype.getTime.call(value);\n if (!isDateTimeInstant(epochMilliseconds)) {\n return INVALID_TIMESTAMP_DATE;\n }\n return ok(Date.prototype.toISOString.call(value));\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 !isDateTimeInstant(Date.parse(value))\n ) {\n return INVALID_TIMESTAMP_DATE;\n }\n return ok(new Date(value).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 = Object.freeze({\n issues: Object.freeze([\n Object.freeze({\n message: \"Expected ISO date format (YYYY-MM-DD)\",\n }),\n ]),\n});\nconst INVALID_DATE = Object.freeze({\n issues: Object.freeze([Object.freeze({ message: \"Invalid date\" })]),\n});\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 if (!isDateTimeInstant(Date.prototype.getTime.call(value))) {\n return INVALID_DATE;\n }\n return ok(Date.prototype.toISOString.call(value).slice(0, 10));\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 = Object.freeze({\n issues: Object.freeze([\n Object.freeze({\n message: \"Expected ISO time format (HH:mm:ss)\",\n }),\n ]),\n});\nconst INVALID_TIME = Object.freeze({\n issues: Object.freeze([Object.freeze({ message: \"Invalid time\" })]),\n});\n\n/**\n * Validate ISO time format.\n * Accepts Date objects and extracts the time portion (HH:mm:ss.sss).\n */\nfunction validateIsoTime(value: unknown) {\n // Handle Date objects - extract time portion\n if (isDate(value)) {\n if (Number.isNaN(Date.prototype.getTime.call(value))) return INVALID_TIME;\n // Extract HH:mm:ss.sss from ISO string\n const isoString = Date.prototype.toISOString.call(value);\n const timePart = isoString.split(\"T\")[1]!.replace(\"Z\", \"\");\n return ok(timePart);\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 const hours = Number(parts[0]);\n const minutes = Number(parts[1]);\n const seconds = Math.trunc(Number(parts[2]));\n\n if (\n hours < 0 ||\n hours > 23 ||\n minutes < 0 ||\n minutes > 59 ||\n seconds < 0 ||\n seconds > 59\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","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, 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 = Object.freeze({\n issues: Object.freeze([\n Object.freeze({ message: \"Expected JSON-compatible value\" }),\n ]),\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","// 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 } 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\nconst ALL_KINDS: readonly JsonNullKind[] = [\"DbNull\", \"JsonNull\", \"AnyNull\"];\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\n/**\n * The refusal a disallowed sentinel gets. It names the token the caller used\n * and the ones this slot would have accepted, because the whole point of the\n * sentinels is that \"null\" alone never says enough.\n */\nfunction refuseSentinel(\n sentinel: AnyJsonNullSentinel,\n allowed: readonly JsonNullKind[],\n where: string\n) {\n const rejected = ALL_KINDS.filter((kind) => !allowed.includes(kind));\n const reason =\n rejected.length === ALL_KINDS.length\n ? `JSON null sentinels are not supported in ${where}`\n : `${sentinel.kind} is not supported in ${where}; that slot accepts ${listKinds(allowed)}`;\n return fail(`${reason}.`);\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\nfunction copyOptionality(\n schema: object,\n wrapped: VibSchema<any, any>,\n allowed: readonly JsonNullKind[]\n): void {\n (schema as { allowed: readonly JsonNullKind[] }).allowed = allowed;\n (schema as { wrapped: VibSchema<any, any> }).wrapped = wrapped;\n (schema as { acceptsUndefined: boolean }).acceptsUndefined =\n (wrapped as { acceptsUndefined?: boolean }).acceptsUndefined === true;\n}\n\n/**\n * A JSON FILTER operand that also accepts the sentinels in `allowed`.\n *\n * A bare `null` is NOT intercepted here: it keeps whatever the wrapped operand\n * already meant (at the document root, \"the column IS NULL\"; under a `path`,\n * \"the value at that path is the JSON null\"). That behavior predates the\n * sentinels and stays pinned — see the regression witnesses in\n * `tests/drivers/json-null-sentinel-behavior.ts`.\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 copyOptionality(schema, wrapped, allowed);\n return schema;\n}\n\n/**\n * A JSON WRITE slot: sentinels in `allowed`, any JSON document, no bare `null`.\n *\n * The bare-`null` refusal is the reason this is not just `jsonNullOr`. See\n * {@link JsonWriteSchema} for the rule and its citation.\n *\n * An OMITTED key is untouched: `undefined` falls through to the wrapped schema,\n * which applies the field's own default — for a nullable JSON field that\n * default is the database NULL, which is exactly what `DbNull` names. Only a\n * `null` the CALLER spelled is ambiguous, and only that one is refused.\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 // A supplied document transformed to null is JSON null; omitted nullable\n // defaults keep their separate SQL NULL path.\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 copyOptionality(schema, wrapped, allowed);\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 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: (value: unknown) => resolve()[\"~standard\"].validate(value),\n get jsonSchema() {\n return resolve()[\"~standard\"].jsonSchema;\n },\n },\n } as unknown as T;\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 } 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 const validate = schema[\"~standard\"].validate;\n Object.defineProperty(schema[\"~standard\"], \"validate\", {\n value: (value: unknown) => {\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 return schema;\n}\n","// A domain predicate (an extension's `rows`) 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 its `$if` stands for: the schemas, which own which place\n// is a value and which a filter, are the one judge of where a marker can sit.\n// The nodes the admission answers are registered here and kept as they are,\n// by identity, so an admitted predicate admits again as itself. Nothing else\n// can produce one: the registries are module-private, so a caller's payload\n// never carries a node.\n\nimport type { VibSchema } from \"../types\";\nimport { isRecord } from \"../value-guards\";\nimport { withoutFilterDepthBound } from \"./filter-depth\";\nimport { createSchema, fail, ok, validateSchema } from \"./helpers\";\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 /** The node a `$if` stands for, or why it is refused. */\n condition(spec: unknown): object | string;\n}\n\n/** The key that holds a condition in a filter: no field name starts with `$`. */\nconst CONDITION = \"$if\";\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 Object.assign(schema, {\n wrapped,\n acceptsUndefined:\n (wrapped as { acceptsUndefined?: boolean }).acceptsUndefined === true,\n });\n return schema 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 its `$if` as one, conjoined with the filter it sits beside.\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 const validate = standard.validate;\n const admit = (value: unknown) => {\n if (!(admitting && isRecord(value) && Object.hasOwn(value, CONDITION)))\n return validate(value);\n const { [CONDITION]: spec, ...filter } = value;\n const node = admitting.condition(spec);\n if (typeof node === \"string\") return fail(node, [CONDITION]);\n conditions.add(node);\n return Object.keys(filter).length === 0\n ? ok(node)\n : validate({ AND: [filter, node] });\n };\n Object.defineProperty(standard, \"validate\", {\n value: (value: unknown) => {\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 return where;\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(\n \"A row predicate's recurse must write its depth (false, or a number)\"\n )\n : validateSchema(recurrence, value)\n );\n Object.assign(schema, {\n wrapped: recurrence,\n acceptsUndefined:\n (recurrence as { acceptsUndefined?: boolean }).acceptsUndefined === true,\n });\n return schema 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 { createSchema, fail, ok, validateSchema } 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 const standard = schema[\"~standard\"] as {\n validate: (value: unknown) => unknown;\n };\n const inner = standard.validate;\n standard.validate = (value: unknown) =>\n runInOperandScope(model, () => inner(value));\n return limitFilterDepth(schema);\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 =\n \"A filter callback is only meaningful inside a model filter, where the model whose columns it names is known.\";\n\nconst RETURN_REFUSAL =\n \"A filter callback must return a field reference (ctx.fields.<field>) or an SQL fragment (ctx.sql`…`)\";\n\nfunction describe(value: unknown): string {\n if (value === null) return \"null\";\n if (Array.isArray(value)) return \"an array\";\n return `a value of 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(\n `${RETURN_REFUSAL}; it returned a promise. Validation is synchronous, so a filter callback cannot be async.`\n );\n }\n return fail(`${RETURN_REFUSAL}; it returned ${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 */\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 const schema = createSchema<\n | InferInput<TSchema>\n | FieldRef<string, TType>\n | Sql\n | ((ctx: TCtx) => FieldRef<string, TType> | Sql),\n InferOutput<TSchema> | FieldRef<string, TType> | Sql\n >(\"comparison_operand\", (value) => {\n const node = valueNodeOf(value);\n if (node !== undefined) return ok(node) as never;\n if (isFunction(value)) {\n return resolveCallback(\n value as (ctx: AnyOperandCtx) => unknown,\n fieldType\n ) as never;\n }\n if (isFieldRef(value)) {\n return checkRef(value, fieldType) as never;\n }\n if (isSql(value)) {\n return ok(value) as never;\n }\n return validateSchema(wrapped, value) as never;\n }) as ComparisonOperandSchema<TType, TSchema, TCtx>;\n\n (schema as { fieldType: TType }).fieldType = fieldType;\n (schema as { wrapped: TSchema }).wrapped = wrapped;\n // Neither a reference, a fragment, nor a callback is ever a default;\n // optionality is entirely the wrapped schema's business, so mirror it for the\n // object validator's fast path.\n (schema as { acceptsUndefined: boolean }).acceptsUndefined =\n (wrapped as { acceptsUndefined?: boolean }).acceptsUndefined === true;\n\n return schema;\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 const schema = createSchema<\n InferInput<TSchema> | FieldRef<string, TType>,\n InferOutput<TSchema> | FieldRef<string, TType>\n >(\"field_ref_or\", (value) => {\n const node = valueNodeOf(value);\n if (node !== undefined) return ok(node) as never;\n if (isFieldRef(value)) {\n return checkRef(value, fieldType);\n }\n return validateSchema(wrapped, value) as never;\n }) as FieldRefOrSchema<TType, TSchema>;\n\n (schema as { fieldType: TType }).fieldType = fieldType;\n (schema as { wrapped: TSchema }).wrapped = wrapped;\n // A reference is never a default; optionality is entirely the wrapped\n // schema's business, so mirror it for the object validator's fast path.\n (schema as { acceptsUndefined: boolean }).acceptsUndefined =\n (wrapped as { acceptsUndefined?: boolean }).acceptsUndefined === true;\n\n return schema;\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 standard = wrapped[\"~standard\"];\n const captured = {\n \"~standard\": {\n version: standard.version,\n vendor: standard.vendor,\n validate: standard.validate,\n },\n };\n const schema = createSchema<InferInput<TSchema>, InferOutput<TSchema>>(\n \"no_field_ref\",\n (value) => {\n const inputOperand = findOpaqueOperand(value, fragments);\n if (inputOperand)\n return fail(`${inputOperand} is not supported in ${where}.`);\n const result = validateSchema(captured, value);\n if (result.issues) return result as never;\n const found = findOpaqueOperand(\n (result as { value: unknown }).value,\n fragments\n );\n if (found) {\n return fail(`${found} is not supported in ${where}.`);\n }\n return result as never;\n }\n ) as NoFieldRefSchema<TSchema>;\n\n (schema as { wrapped: TSchema }).wrapped = wrapped;\n (schema as { acceptsUndefined: boolean }).acceptsUndefined =\n (wrapped as { acceptsUndefined?: boolean }).acceptsUndefined ?? false;\n\n return schema;\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 const seen = new WeakSet<object>();\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.has(value)) continue;\n seen.add(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}' is a list field; list fields cannot be used as a comparison operand.`\n );\n }\n if (payload.type !== fieldType) {\n return fail(\n `Field reference '${payload.model}.${payload.field}' is of type '${payload.type}', but a '${fieldType}' operand is required here.`\n );\n }\n return ok(ref) as never;\n}\n","import type { InferInput, InferOutput, VibSchema } from \"../types\";\nimport { createSchema, fail, ok, 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 fail(\n `Transform failed: ${e instanceof Error ? e.message : String(e)}`\n );\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 { createSchema, fail, ok, validateSchema } 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 fail(\n `Transform failed: ${e instanceof Error ? e.message : String(e)}`\n );\n }\n }\n ) as TransformSchema<InferInput<S>, TOut> & { wrapped: S };\n\n (transformSchema as any).wrapped = schema;\n // Inherit acceptsUndefined from wrapped schema\n (transformSchema as any).acceptsUndefined =\n (schema as any).acceptsUndefined === true;\n\n return transformSchema;\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","import { 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\ntype MemberResult = ReturnType<VibSchema[\"~standard\"][\"validate\"]>;\n\n/** A member's result, an async member's promise being a refusal. */\nfunction settled(result: MemberResult): ValidationResult<unknown> {\n if (!(\"then\" in result)) return result as ValidationResult<unknown>;\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 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) {\n return settled(tagged(value)) as ValidationResult<\n InferOutput<TOptions[number]>\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 (const validate of validators) {\n const result = settled(validate(value));\n if (!result.issues) {\n return result as { value: InferOutput<TOptions[number]> };\n }\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\n ? { issues: deepest }\n : fail(\"Expected no value: the union has no member\");\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 return union([\n coerce(schema, (v: S[\" vibInferred\"][\"1\"]) => [v]),\n array(schema),\n ]);\n};\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// 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 = Object.freeze({\n issues: Object.freeze([Object.freeze({ message: \"Expected string\" })]),\n});\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, 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 = Object.freeze({\n issues: Object.freeze([\n Object.freeze({ message: \"Expected array of numbers\" }),\n ]),\n});\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 ? Object.freeze({\n issues: Object.freeze([\n Object.freeze({\n message: `Expected vector of ${dimensions} dimensions`,\n }),\n ]),\n })\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"],"mappings":"sbA8CA,MAAa,EAAiC,OAAO,IAAI,mBAAmB,CA0C5E,SAAgB,WAAW,EAAsC,CAC/D,GAAI,OAAO,GAAU,WAAY,EAAgB,MAAO,GACxD,IAAM,EAAW,EAA0C,GAC3D,OAAO,OAAO,GAAY,YAAY,EAIxC,SAAgB,gBAAgB,EAAmC,CACjE,OAAO,EAAI,GAIb,SAAgB,eAAe,EAA0B,CACvD,IAAM,EAA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,OAAO,CACpB,OAAO,OAAO,CACZ,QAAS,sBAAsB,EAAW,aAC3C,CAAC,CACH,CAAC,CACH,CAAC,CAGR,MAAQ,IAAmB,CACzB,GAAI,CAAC,MAAM,QAAQ,EAAM,CAAE,OAAO,GAElC,IAAM,EAAM,EAAM,OAClB,IAAK,IAAI,EAAI,EAAG,EAAI,EAAK,IACvB,GAAI,EAAE,EAAS,EAAM,GAAG,EAAI,OAAO,SAAS,EAAM,GAAG,EACnD,OAAO,EAAK,mCAAmC,IAAI,CAMvD,OAFI,GAAkB,IAAQ,EAAmB,EAE1C,EAAG,EAAkB,EAehC,SAAgB,OAGd,EACA,EAGA,CAEA,OAAO,EAAY,SADE,sBAAsB,EAAW,CACX,EAAS,CAClD,aACD,CAAC,CC+BJ,MAAa,EAAI,CAEf,OACA,UACA,UACA,QACA,UACA,QACA,QACA,KAAM,MACN,KAEA,KACA,aACA,QACA,QAEA,KACA,OACA,MAEA,MACA,SACA,cACA,YAEA,SACA,KACA,WAEA,MACA,KACA,gBAAA,UACA,OACA,SAEA,OACA,OAEA,KACA,QAEA,cAEA,gBACA,gBACA,eAGA,kBACA,WACA,WACA,oBAEA,WACA,UAEA,QACD,CAED,IAAA,GAAe"}
@@ -0,0 +1,2 @@
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t,o as n}from"./value-guards-CK9guf2Z.mjs";import{Nt as r,et as i,jt as a}from"./geo-point-codec-DyEHMdJg.mjs";const o=` vibInferred`,isPromiseLike=e=>n(e)&&`then`in e&&t(e.then),s={issues:[{message:`Async validation is not supported`}]},c={issues:[{message:`Schema returned a malformed validation result`}]};function parse(e,t,o){try{let r=i(o?.allIssues===!0,()=>e[`~standard`].validate(t));if(isPromiseLike(r))return a(r),s;if(!n(r))return c;let l=Reflect.get(r,`issues`);return l===void 0?`value`in r?{value:Reflect.get(r,`value`)}:c:Array.isArray(l)?{issues:l}:c}catch(e){return r(e)}}export{o as n,parse as t};
2
+ //# sourceMappingURL=validation-BQtO6srU.mjs.map