viborm 1.2.4 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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-Df24l2Bd.mjs +2 -0
  17. package/dist/builder-Df24l2Bd.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-C7c1YTXD.mjs +2 -0
  35. package/dist/chain-C7c1YTXD.mjs.map +1 -0
  36. package/dist/cli.mjs +2 -2
  37. package/dist/cli.mjs.map +1 -1
  38. package/dist/{client-CUnPXifK.d.mts → client-70MrTq1E.d.mts} +3 -3
  39. package/dist/client-DM1UHfYG.mjs +49 -0
  40. package/dist/{client-B3VWFhv_.mjs.map → client-DM1UHfYG.mjs.map} +1 -1
  41. package/dist/client-_WKrPNmm.mjs +2 -0
  42. package/dist/client-_WKrPNmm.mjs.map +1 -0
  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-Da-efekX.mjs +2 -0
  50. package/dist/controls-Da-efekX.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-CPD0Xxw2.mjs} +2 -2
  61. package/dist/{driver-B19QlFqn.mjs.map → driver-CPD0Xxw2.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-1pKZteeB.mjs +2 -0
  67. package/dist/{every-o-Nu9Em8.mjs.map → every-1pKZteeB.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-DsyHNSDS.mjs +2 -0
  77. package/dist/{hydration-CAxOL4aI.mjs.map → hydration-DsyHNSDS.mjs.map} +1 -1
  78. package/dist/identifier-conversion-DaZ9yNpv.mjs +2 -0
  79. package/dist/{identifier-conversion-GgbwHc2G.mjs.map → identifier-conversion-DaZ9yNpv.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-D_kagnFv.mjs +2 -0
  93. package/dist/{key-BeoOwGr3.mjs.map → key-D_kagnFv.mjs.map} +1 -1
  94. package/dist/{libsql-Drp-zaxq.mjs → libsql-DFAoHXrI.mjs} +3 -3
  95. package/dist/{libsql-Drp-zaxq.mjs.map → libsql-DFAoHXrI.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-GTWgeDNY.mjs} +2 -2
  99. package/dist/{memory-CDTUZQWL.mjs.map → memory-GTWgeDNY.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-adapter-C6c5govr.mjs +2 -0
  119. package/dist/{mysql-adapter-DkJPfoGf.mjs.map → mysql-adapter-C6c5govr.mjs.map} +1 -1
  120. package/dist/{mysql-D7zC03yD.mjs → mysql-xChEivOe.mjs} +6 -6
  121. package/dist/{mysql-D7zC03yD.mjs.map → mysql-xChEivOe.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-BqAxDWTQ.mjs} +4 -4
  151. package/dist/{postgres-Dv-QnnbD.mjs.map → postgres-BqAxDWTQ.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-CDgX_vzn.mjs +2 -0
  166. package/dist/result-shape-CDgX_vzn.mjs.map +1 -0
  167. package/dist/scalar-S8yMvdmx.mjs +4 -0
  168. package/dist/scalar-S8yMvdmx.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-9N9jQlVL.mjs +2 -0
  173. package/dist/{schema-Cjem1-0f.mjs.map → schema-9N9jQlVL.mjs.map} +1 -1
  174. package/dist/{schema-introspection-DEYGC2qg.mjs → schema-introspection-CyXKReK1.mjs} +4 -4
  175. package/dist/{schema-introspection-DEYGC2qg.mjs.map → schema-introspection-CyXKReK1.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-C1PuFIpf.mjs +2 -0
  204. package/dist/to-many-C1PuFIpf.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-CtFUE8UN.mjs} +4 -4
  212. package/dist/{utils-CZNaOZR7.mjs.map → utils-CtFUE8UN.mjs.map} +1 -1
  213. package/dist/v-CYTUI0H5.mjs +2 -0
  214. package/dist/v-CYTUI0H5.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-DgffZq9C.mjs +2 -0
  222. package/dist/validator-DgffZq9C.mjs.map +1 -0
  223. package/dist/version-CXuJzC-q.mjs +2 -0
  224. package/dist/{version-nt0parEY.mjs.map → version-CXuJzC-q.mjs.map} +1 -1
  225. package/package.json +35 -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 +0,0 @@
1
- {"version":3,"file":"geo-point-codec-lhxH42SK.mjs","names":["integer","optional","integer","#c","#scale","#at","result"],"sources":["../src/validation/primitives/bigint.ts","../src/validation/primitives/geo-values.ts","../src/validation/primitives/binary-shapes.ts","../src/validation/primitives/id-formats.ts","../src/validation/primitives/id-codec.ts","../src/validation/json-schema/types.ts","../src/validation/json-schema/converters.ts","../src/validation/json-schema/factory.ts","../src/validation/parse-failure.ts","../src/validation/primitives/helpers.ts","../src/validation/primitives/decimal-value.ts","../src/validation/primitives/decimal-codec.ts","../src/validation/primitives/object.ts","../src/validation/primitives/datetime-values.ts","../src/validation/primitives/number.ts","../src/validation/primitives/optional.ts","../src/validation/primitives/geo-point-codec.ts"],"sourcesContent":["import type {\n ComputeInput,\n ComputeOutput,\n ScalarOptions,\n VibSchema,\n} from \"../types\";\nimport { isBigInt } from \"../value-guards\";\nimport { buildSchema, ok } from \"./helpers\";\n\n// =============================================================================\n// BigInt Schema\n// =============================================================================\n\nexport interface BaseBigIntSchema<\n Opts extends ScalarOptions<bigint, any> | undefined = undefined,\n> extends VibSchema<ComputeInput<bigint, Opts>, ComputeOutput<bigint, Opts>> {}\n\nexport interface BigIntSchema<TInput = bigint, TOutput = bigint>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"bigint\";\n}\n\n// Pre-computed error for fast path\nconst BIGINT_ERROR = Object.freeze({\n issues: Object.freeze([\n Object.freeze({ message: \"Expected bigint or an integer string\" }),\n ]),\n});\n\n/**\n * The integer TEXT a bigint is also admitted as: what a JSON boundary carries,\n * since a JSON number past 2^53 has already lost digits. The JSON Schema\n * export states this same grammar as the bigint's `pattern`.\n */\nexport const BIGINT_TEXT_PATTERN = \"^[+-]?\\\\d+$\";\nconst BIGINT_TEXT = new RegExp(BIGINT_TEXT_PATTERN);\n\n/**\n * Validate that a value is a bigint, or an integer string read as one.\n */\nfunction validateBigInt(value: unknown) {\n if (isBigInt(value)) return ok(value);\n return typeof value === \"string\" && BIGINT_TEXT.test(value)\n ? ok(BigInt(value))\n : BIGINT_ERROR;\n}\n\n/**\n * Create a bigint schema.\n *\n * @example\n * const id = v.bigint();\n * const optionalId = v.bigint({ optional: true });\n */\nexport function bigint(): BigIntSchema<bigint, bigint>;\nexport function bigint<const Opts extends ScalarOptions<bigint, any>>(\n options: Opts\n): BigIntSchema<ComputeInput<bigint, Opts>, ComputeOutput<bigint, Opts>>;\nexport function bigint<\n const Opts extends ScalarOptions<bigint, any> | undefined,\n>(\n options?: Opts\n): BigIntSchema<ComputeInput<bigint, Opts>, ComputeOutput<bigint, Opts>> {\n return buildSchema(\"bigint\", validateBigInt, options) as BigIntSchema<\n ComputeInput<bigint, Opts>,\n ComputeOutput<bigint, Opts>\n >;\n}\n\n// Export the validate function for reuse\nexport { validateBigInt };\n","/**\n * The coordinate domain every geographic value shares: EPSG:4326 degrees,\n * longitude first. The codecs, the JSON Schema projection, and the SQLite\n * CHECK read these same constants.\n */\nexport const GEO_POINT_KEYS = [\"longitude\", \"latitude\"] as const;\nexport const GEO_LONGITUDE_MIN = -180;\nexport const GEO_LONGITUDE_MAX = 180;\nexport const GEO_LATITUDE_MIN = -90;\nexport const GEO_LATITUDE_MAX = 90;\nexport const GEO_BOUNDS_KEYS = [\"south\", \"west\", \"north\", \"east\"] as const;\nexport const GEO_POLYGON_MIN_RING_POINTS = 3;\n\n/** The sole public value represented by an `s.point()` field. */\nexport interface GeoPoint {\n longitude: number;\n latitude: number;\n}\n\n/** One inclusive latitude/longitude rectangle. */\nexport interface GeoBounds {\n south: number;\n west: number;\n north: number;\n east: number;\n}\n\n/** One simple geographic polygon with optional holes. */\nexport interface GeoPolygon {\n outer: readonly GeoPoint[];\n holes?: readonly (readonly GeoPoint[])[];\n}\n\n/** The two query-only geographic area forms. */\nexport type GeoArea =\n | { readonly bounds: GeoBounds }\n | { readonly polygon: GeoPolygon };\n","/**\n * The ONE normalization of every shape a driver spells binary bytes in.\n *\n * Nine drivers return the same column nine ways — a Node `Buffer`, a\n * `Uint8Array`, an `ArrayBuffer`, a plain array of byte numbers, PostgreSQL's\n * `\\x…` hex inside a JSON carrier, MySQL's `base64:typeNNN:…` inside one, and\n * the lowercase hex our own `blobToHex` cast emits — and every one of them\n * names the same bytes. Deciding which is which is a pure question about a\n * VALUE, not about a dialect or an operation, so it lives here as a leaf where\n * both readers of physical binary can share one answer: the blob scalar's\n * result parser and the identifier storage codec.\n *\n * It REPORTS rather than throws. The two callers are at different boundaries\n * and owe different messages — a blob column names the driver and the\n * operation, an identifier names the field and its declared format — so the\n * refusal's wording belongs to them and only the classification belongs here.\n */\n\nconst HEX_BYTES = /^(?:[0-9a-fA-F]{2})*$/;\nconst BASE64 =\n /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;\nconst BASE64_PROVIDER = /^base64:type\\d+:(.*)$/;\n\n/**\n * The bytes a driver value names, or the REPRESENTATION that could not be read.\n *\n * `unsupported` is the phrase a message says after \"an unsupported\": the shape\n * that was recognized but malformed (`\"hex string\"`, `\"base64 string\"`,\n * `\"byte array\"`), or the `typeof` of a value that is no binary shape at all.\n */\nexport type BinaryShape =\n | { readonly bytes: Uint8Array; readonly unsupported?: undefined }\n | { readonly bytes?: undefined; readonly unsupported: string };\n\nfunction hexBytes(hex: string): BinaryShape {\n if (!HEX_BYTES.test(hex)) return { unsupported: \"hex string\" };\n const out = new Uint8Array(hex.length / 2);\n for (let index = 0; index < out.length; index++) {\n out[index] = Number.parseInt(hex.slice(index * 2, index * 2 + 2), 16);\n }\n return { bytes: out };\n}\n\nfunction base64Bytes(base64: string): BinaryShape {\n if (!BASE64.test(base64)) return { unsupported: \"base64 string\" };\n // The pattern admitted canonical, padded base64 only, so `atob` decodes it\n // and cannot throw.\n const binary = atob(base64);\n const out = new Uint8Array(binary.length);\n for (let index = 0; index < out.length; index++) {\n out[index] = binary.charCodeAt(index);\n }\n return { bytes: out };\n}\n\n/** Normalize any driver binary representation to plain bytes, or say why not. */\nexport function normalizeBinaryValue(value: unknown): BinaryShape {\n if (value instanceof ArrayBuffer) {\n return { bytes: new Uint8Array(value.slice(0)) };\n }\n if (ArrayBuffer.isView(value)) {\n const view = new Uint8Array(\n value.buffer,\n value.byteOffset,\n value.byteLength\n );\n return { bytes: new Uint8Array(view) };\n }\n if (Array.isArray(value)) {\n for (const byte of value) {\n if (!Number.isInteger(byte) || byte < 0 || byte > 255) {\n return { unsupported: \"byte array\" };\n }\n }\n return { bytes: Uint8Array.from(value) };\n }\n if (typeof value === \"string\") {\n if (value.startsWith(\"\\\\x\")) return hexBytes(value.slice(2));\n if (value.startsWith(\"base64:type\")) {\n const match = BASE64_PROVIDER.exec(value);\n if (!match) return { unsupported: \"base64 string\" };\n const payloadStart = value.indexOf(\":\", \"base64:type\".length) + 1;\n return base64Bytes(value.slice(payloadStart));\n }\n return hexBytes(value);\n }\n return { unsupported: typeof value };\n}\n","// biome-ignore-all lint/suspicious/noBitwiseOperators: a version nibble, a\n// variant pair and a base32 digit are DEFINED as bit fields; expressing them\n// arithmetically would restate the same masks less legibly.\n\n/**\n * The ONE reversible representation of every fixed-width identifier format.\n *\n * UUID, ULID and KSUID each name the same value twice: as the TEXT a caller\n * writes and reads, and as the BYTES that text stands for. This module owns\n * both spellings and the conversion between them, plus the byte layout each\n * format's generator assembles. Nothing above it re-derives a width, an\n * alphabet, a padding rule, or a version bit.\n *\n * It is a LEAF on purpose. It imports no scalar class, no schema state and no\n * dialect, so the storage codec that will encode and decode these values at the\n * database boundary can consume the same conversions the generators use. Two\n * implementations of \"what a ULID is\" is exactly what this file exists to\n * prevent.\n *\n * Two asymmetries are deliberate:\n *\n * 1. TEXT -> BYTES returns `undefined` for anything outside the format. Text is\n * what a caller types, so a spelling the format does not have is a value to\n * refuse, and the boundary that asked owns the message.\n * 2. BYTES -> TEXT REFUSES a wrong width. A byte array is never typed by a\n * caller; it is produced by a generator or read out of a column, so a width\n * that is not the format's names a broken physical value rather than a\n * spelling question, and no caller above can say anything truer about it.\n *\n * Randomness is drawn HERE and only here, from `crypto.getRandomValues`. There\n * is no `Math.random()` path: an identifier that is not unpredictable is not an\n * identifier, so a runtime without secure randomness gets a refusal instead of\n * a weaker value.\n */\n\nimport { ValidationError } from \"@errors\";\n\n// =============================================================================\n// WIDTHS AND DOMAINS\n// =============================================================================\n\n/** Bytes in a UUID (RFC 9562 §4). */\nexport const UUID_BYTE_LENGTH = 16;\n\n/** Bytes in a ULID and characters in its Crockford base32 text. */\nexport const ULID_BYTE_LENGTH = 16;\nexport const ULID_TEXT_LENGTH = 26;\n\n/** Bytes in a KSUID and characters in its base62 text. */\nexport const KSUID_BYTE_LENGTH = 20;\nexport const KSUID_TEXT_LENGTH = 27;\n\n/** Random bytes a ULID carries after its 48-bit timestamp. */\nexport const ULID_RANDOM_LENGTH = 10;\n\n/** Random bytes a UUIDv7 carries after its 48-bit timestamp. */\nexport const UUIDV7_RANDOM_LENGTH = 10;\n\n/** Payload bytes a KSUID carries after its 32-bit timestamp. */\nexport const KSUID_PAYLOAD_LENGTH = 16;\n\n/**\n * The widest instant a 48-bit millisecond timestamp names: 2^48-1 ms after the\n * Unix epoch, which is in the year 10889. Shared by ULID and UUIDv7.\n */\nexport const MAX_MILLISECOND_TIMESTAMP = 281_474_976_710_655;\n\n/** KSUID counts seconds from 2014-05-13T16:53:20Z, not from the Unix epoch. */\nexport const KSUID_EPOCH_SECONDS = 1_400_000_000;\n\n/** The widest second a 32-bit KSUID timestamp names, as a Unix second. */\nexport const MAX_KSUID_UNIX_SECONDS = KSUID_EPOCH_SECONDS + 4_294_967_295;\n\n/**\n * Crockford's base32 alphabet: no `I`, `L`, `O` or `U`. VibORM does NOT map the\n * excluded letters onto digits — a ULID with an `I` in it was not produced by\n * this format, and silently reading it as `1` would make two different texts\n * the same identifier.\n */\nexport const CROCKFORD = \"0123456789ABCDEFGHJKMNPQRSTVWXYZ\";\n\n/**\n * The accepted spellings of one Crockford digit: canonical uppercase first,\n * its lowercase alias second, so `indexOf(char) % 32` is the digit's value and\n * anything else is not a digit at all.\n *\n * The lookup is by exact character rather than by case folding: `\"ſ\"`\n * upper-cases to `\"S\"`, and a ULID is an identity, not a piece of prose.\n */\nconst CROCKFORD_ALIASED = CROCKFORD + CROCKFORD.toLowerCase();\n\n/**\n * NanoID's URL-safe alphabet: 64 characters, so one random byte selects one\n * character through `byte & 63` with no bias and no rejection sampling.\n *\n * It lives HERE, beside the fixed-width alphabets, because a declared nanoid\n * field has to ADMIT the values it generates: the storage codec spells the\n * grammar from the same 64 characters the generator draws from, and two copies\n * of an alphabet is exactly how a generated value comes to be refused by its\n * own field.\n */\nexport const NANOID_ALPHABET =\n \"useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict\";\n\n/** The length `.nanoid()` takes when the declaration names none. */\nexport const NANOID_DEFAULT_LENGTH = 21;\n\n/**\n * The one spelling a CUID2 has: a lowercase letter then 23 lowercase\n * alphanumerics, which is what this port's generator emits at its fixed length\n * of 24 and what upstream's own validator accepts.\n */\nexport const CUID_TEXT = /^[a-z][0-9a-z]{23}$/;\n\n/**\n * KSUID's base62 alphabet, in ASCII order. The order is load-bearing: it makes\n * the text sort exactly as the bytes sort, which is what makes a KSUID\n * time-sortable as a string.\n */\nexport const BASE62 =\n \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n\n/** The first value 20 bytes cannot hold; some 27-character base62 texts exceed it. */\nconst KSUID_EXCLUSIVE_MAX = 2n ** 160n;\n\nexport const UUID_TEXT =\n /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;\n\nconst HEX_RADIX = 16;\nconst BASE62_RADIX = 62n;\nconst BYTE_RADIX = 256n;\nconst BYTE_MASK = 255n;\n\n// =============================================================================\n// THE ONE REFUSAL\n// =============================================================================\n\n/**\n * The one refusal an identifier declaration or generation raises.\n *\n * Every failure here is a DECLARATION failure in the end — a length the format\n * has no value for, an instant it cannot name, a prefix that contradicts one\n * already declared, or a runtime that cannot produce the entropy the declared\n * format requires — so they all name the builder that was spelled and the part\n * of the declaration at fault.\n */\nexport function refuseId(\n builder: string,\n path: string,\n message: string\n): never {\n throw new ValidationError({ kind: \"schema-builder\", builder, path }, [\n { path, message },\n ]);\n}\n\n// =============================================================================\n// SECURE RANDOMNESS\n// =============================================================================\n\n/**\n * The most bytes one call to the entropy source will serve.\n *\n * `crypto.getRandomValues` refuses a request larger than this with a\n * `QuotaExceededError` (Web Cryptography API §10.1), so it is the ceiling on\n * every length a caller can choose. It is published because a DECLARATION that\n * asks for more has to be refused where it is spelled, not at row-create time\n * inside a closure.\n */\nexport const MAX_RANDOM_BYTES = 65_536;\n\n/**\n * `length` unpredictable bytes, or a refusal.\n *\n * The ONE entropy source in the identifier language. It is read at GENERATION\n * time, never at import or declaration time, so loading VibORM and describing a\n * schema draw nothing.\n *\n * `format` names the generator that asked, because the message a developer sees\n * has to say what stopped working. It cannot name the FIELD: a generator is a\n * closure held in scalar state, and field keys belong to the model that later\n * mounts that scalar, so no field name exists at this point in the program.\n */\nexport function randomBytes(length: number, format: string): Uint8Array {\n const source = globalThis.crypto;\n if (typeof source?.getRandomValues !== \"function\") {\n refuseId(\n `s.string().${format}`,\n \"generate\",\n `Cannot generate a ${format} value: this runtime exposes no \\`crypto.getRandomValues\\`. VibORM never falls back to \\`Math.random()\\` for an identifier`\n );\n }\n return source.getRandomValues(new Uint8Array(length));\n}\n\n// =============================================================================\n// PREFIX\n// =============================================================================\n\n/**\n * Whether a declaration carries a prefix. An empty string is NOT a prefix: it\n * is how a caller spells \"no prefix\", and `${\"\"}-${value}` would otherwise make\n * a bare hyphen part of every value.\n */\nexport function hasIdPrefix(prefix: string | undefined): boolean {\n return prefix !== undefined && prefix !== \"\";\n}\n\n/**\n * The public value of a generated identifier: `prefix-payload`, or the bare\n * payload when no prefix was declared. The hyphen is part of the contract, and\n * a prefix is matched whole at admission — nothing splits generically on `-`.\n */\nexport function applyIdPrefix(\n prefix: string | undefined,\n payload: string\n): string {\n return hasIdPrefix(prefix) ? `${prefix}-${payload}` : payload;\n}\n\n// =============================================================================\n// EXACT-WIDTH INTEGERS\n// =============================================================================\n\n/**\n * Write `value` big-endian across exactly `byteLength` bytes.\n *\n * Callers have already proved the value fits — each format refuses its own\n * out-of-range instant with a message naming that format — so this writes\n * rather than checks. Arithmetic, not shifts: a 48-bit timestamp is wider than\n * the 32 bits JavaScript's bitwise operators work in.\n */\nfunction writeUintBE(\n view: DataView,\n offset: number,\n byteLength: number,\n value: number\n): void {\n let remaining = value;\n for (let index = byteLength - 1; index >= 0; index--) {\n view.setUint8(offset + index, remaining % 256);\n remaining = Math.floor(remaining / 256);\n }\n}\n\n/** Refuse an instant no 48-bit millisecond timestamp can name. */\nfunction assertMillisecondTimestamp(format: string, timeMillis: number): void {\n if (\n !Number.isInteger(timeMillis) ||\n timeMillis < 0 ||\n timeMillis > MAX_MILLISECOND_TIMESTAMP\n ) {\n refuseId(\n `s.string().${format}`,\n \"generate\",\n `A ${format} timestamp must be a whole number of milliseconds between 0 and ${MAX_MILLISECOND_TIMESTAMP}; received ${timeMillis}`\n );\n }\n}\n\n// =============================================================================\n// UUID\n// =============================================================================\n\n/**\n * Tag 16 random bytes as a UUIDv4 (RFC 9562 §5.4): version `0100` in the high\n * nibble of byte 6, variant `10` in the top two bits of byte 8. The 122 other\n * bits stay exactly as drawn.\n *\n * The argument is consumed: it is the generator's own fresh entropy, and\n * copying it would only make a second array to forget to clear.\n */\nexport function uuidV4Bytes(random: Uint8Array): Uint8Array {\n const view = new DataView(\n random.buffer,\n random.byteOffset,\n random.byteLength\n );\n view.setUint8(6, (view.getUint8(6) & 0x0f) | 0x40);\n view.setUint8(8, (view.getUint8(8) & 0x3f) | 0x80);\n return random;\n}\n\n/**\n * Assemble a UUIDv7 (RFC 9562 §5.7): a 48-bit big-endian Unix millisecond\n * timestamp, version `0111`, 12 random bits, variant `10`, 62 random bits.\n *\n * Time-sortable by construction. There is deliberately no same-millisecond\n * monotonic promise: RFC 9562 makes that optional, and the counter it would\n * take is ULID's job here.\n */\nexport function uuidV7Bytes(\n timeMillis: number,\n random: Uint8Array\n): Uint8Array {\n assertMillisecondTimestamp(\"uuidv7\", timeMillis);\n const bytes = new Uint8Array(UUID_BYTE_LENGTH);\n bytes.set(random, UUID_BYTE_LENGTH - UUIDV7_RANDOM_LENGTH);\n const view = new DataView(bytes.buffer);\n writeUintBE(view, 0, 6, timeMillis);\n view.setUint8(6, (view.getUint8(6) & 0x0f) | 0x70);\n view.setUint8(8, (view.getUint8(8) & 0x3f) | 0x80);\n return bytes;\n}\n\n/** The canonical text of 16 UUID bytes: lowercase hex, hyphenated 8-4-4-4-12. */\nexport function bytesToUuid(bytes: Uint8Array): string {\n if (bytes.length !== UUID_BYTE_LENGTH) {\n refuseId(\n \"s.string().uuid\",\n \"generate\",\n `A UUID is exactly ${UUID_BYTE_LENGTH} bytes; received ${bytes.length}`\n );\n }\n let hex = \"\";\n for (const byte of bytes) hex += byte.toString(HEX_RADIX).padStart(2, \"0\");\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n\n/**\n * The 16 bytes a canonical UUID text names, or `undefined`.\n *\n * Uppercase is an accepted ALIAS (RFC 9562 §4 requires readers to accept it),\n * so `A1B2…` and `a1b2…` are the same identifier and produce the same bytes.\n * Braces, URNs and unhyphenated forms are not spellings this format has.\n */\nexport function uuidToBytes(text: string): Uint8Array | undefined {\n if (!UUID_TEXT.test(text)) return;\n const hex = text.replaceAll(\"-\", \"\");\n const bytes = new Uint8Array(UUID_BYTE_LENGTH);\n for (let index = 0; index < UUID_BYTE_LENGTH; index++) {\n bytes[index] = Number.parseInt(\n hex.slice(index * 2, index * 2 + 2),\n HEX_RADIX\n );\n }\n return bytes;\n}\n\n// =============================================================================\n// ULID\n// =============================================================================\n\n/**\n * Assemble a ULID: a 48-bit big-endian millisecond timestamp followed by 80\n * bits of randomness.\n */\nexport function ulidBytes(timeMillis: number, random: Uint8Array): Uint8Array {\n assertMillisecondTimestamp(\"ulid\", timeMillis);\n const bytes = new Uint8Array(ULID_BYTE_LENGTH);\n bytes.set(random, ULID_BYTE_LENGTH - ULID_RANDOM_LENGTH);\n writeUintBE(new DataView(bytes.buffer), 0, 6, timeMillis);\n return bytes;\n}\n\n/**\n * The canonical text of 16 ULID bytes: 26 uppercase Crockford characters.\n *\n * 26 characters hold 130 bits and a ULID is 128, so the text is the value\n * left-padded with two zero bits. That padding is why a canonical ULID's first\n * character is always `0` through `7`.\n */\nexport function bytesToUlid(bytes: Uint8Array): string {\n if (bytes.length !== ULID_BYTE_LENGTH) {\n refuseId(\n \"s.string().ulid\",\n \"generate\",\n `A ULID is exactly ${ULID_BYTE_LENGTH} bytes; received ${bytes.length}`\n );\n }\n let text = \"\";\n let accumulator = 0;\n let bits = 2;\n for (const byte of bytes) {\n accumulator = (accumulator << 8) | byte;\n bits += 8;\n while (bits >= 5) {\n bits -= 5;\n text += CROCKFORD.charAt((accumulator >>> bits) & 31);\n }\n accumulator &= (1 << bits) - 1;\n }\n return text;\n}\n\n/**\n * The 16 bytes a canonical ULID text names, or `undefined`.\n *\n * Lowercase is an accepted alias and normalizes to the same bytes. A first\n * character above `7` sets one of the two padding bits, which names a value\n * wider than 128 bits: that text is not a ULID and is refused rather than\n * truncated.\n */\nexport function ulidToBytes(text: string): Uint8Array | undefined {\n if (text.length !== ULID_TEXT_LENGTH) return;\n const first = CROCKFORD_ALIASED.indexOf(text.charAt(0));\n if (first < 0) return;\n const leading = first % 32;\n if (leading > 7) return;\n const bytes = new Uint8Array(ULID_BYTE_LENGTH);\n let accumulator = leading;\n let bits = 3;\n let index = 0;\n for (const char of text.slice(1)) {\n const digit = CROCKFORD_ALIASED.indexOf(char);\n if (digit < 0) return;\n accumulator = (accumulator << 5) | (digit % 32);\n bits += 5;\n if (bits >= 8) {\n bits -= 8;\n bytes[index] = (accumulator >>> bits) & 255;\n index++;\n accumulator &= (1 << bits) - 1;\n }\n }\n return bytes;\n}\n\n// =============================================================================\n// KSUID\n// =============================================================================\n\n/**\n * Assemble a KSUID: a 32-bit big-endian count of seconds since\n * 2014-05-13T16:53:20Z followed by a 128-bit payload.\n *\n * The timestamp is given as a UNIX second — the offset epoch is this format's\n * private business, and a caller that had to subtract it would be a second\n * owner of the same constant.\n */\nexport function ksuidBytes(\n unixSeconds: number,\n payload: Uint8Array\n): Uint8Array {\n if (\n !Number.isInteger(unixSeconds) ||\n unixSeconds < KSUID_EPOCH_SECONDS ||\n unixSeconds > MAX_KSUID_UNIX_SECONDS\n ) {\n refuseId(\n \"s.string().ksuid\",\n \"generate\",\n `A KSUID timestamp must be a whole Unix second between ${KSUID_EPOCH_SECONDS} and ${MAX_KSUID_UNIX_SECONDS}; received ${unixSeconds}`\n );\n }\n const bytes = new Uint8Array(KSUID_BYTE_LENGTH);\n bytes.set(payload, KSUID_BYTE_LENGTH - KSUID_PAYLOAD_LENGTH);\n writeUintBE(\n new DataView(bytes.buffer),\n 0,\n 4,\n unixSeconds - KSUID_EPOCH_SECONDS\n );\n return bytes;\n}\n\n/**\n * The canonical text of 20 KSUID bytes: exactly 27 base62 characters, padded\n * with leading `0`s. The width is fixed rather than minimal, because a KSUID\n * that shortened itself for a small timestamp would stop sorting.\n */\nexport function bytesToKsuid(bytes: Uint8Array): string {\n if (bytes.length !== KSUID_BYTE_LENGTH) {\n refuseId(\n \"s.string().ksuid\",\n \"generate\",\n `A KSUID is exactly ${KSUID_BYTE_LENGTH} bytes; received ${bytes.length}`\n );\n }\n let value = 0n;\n for (const byte of bytes) value = value * BYTE_RADIX + BigInt(byte);\n return ksuidText(value);\n}\n\n/** A number below 2^160 as its fixed-width, zero-padded base62 text. */\nfunction ksuidText(value: bigint): string {\n const digits: string[] = [];\n let rest = value;\n for (let index = 0; index < KSUID_TEXT_LENGTH; index++) {\n digits.push(BASE62.charAt(Number(rest % BASE62_RADIX)));\n rest /= BASE62_RADIX;\n }\n return digits.reverse().join(\"\");\n}\n\n/**\n * The canonical text of the largest value 20 bytes hold. Every KSUID text is\n * at most this, and a 27-character base62 text above it names no KSUID.\n *\n * Because {@link BASE62} is in ASCII order and the width is fixed, \"at most\" is\n * a plain BYTE-wise string comparison — which is how a caller that cannot run\n * {@link ksuidToBytes}, such as SQL over a legacy text column, asks it. Under a\n * collation that folds case it is not: `a` sorts before `V` there.\n */\nexport const KSUID_MAX_TEXT = ksuidText(KSUID_EXCLUSIVE_MAX - 1n);\n\n/**\n * The 20 bytes a canonical KSUID text names, or `undefined`.\n *\n * Base62 is case-SENSITIVE — `A` and `a` are different digits — so there is no\n * alias to normalize. 27 base62 characters can express more than 2^160 values;\n * one that does names no 20-byte identifier and is refused.\n */\nexport function ksuidToBytes(text: string): Uint8Array | undefined {\n if (text.length !== KSUID_TEXT_LENGTH) return;\n let value = 0n;\n for (const char of text) {\n const digit = BASE62.indexOf(char);\n if (digit < 0) return;\n value = value * BASE62_RADIX + BigInt(digit);\n }\n if (value >= KSUID_EXCLUSIVE_MAX) return;\n const bytes = new Uint8Array(KSUID_BYTE_LENGTH);\n for (let index = KSUID_BYTE_LENGTH - 1; index >= 0; index--) {\n bytes[index] = Number(value & BYTE_MASK);\n value >>= 8n;\n }\n return bytes;\n}\n","/**\n * The ONE codec of a declared identifier DOMAIN.\n *\n * A domain is `{ format, prefix?, length? }` — exactly the facts a generator\n * modifier already recorded on the scalar, never a second declaration. This\n * module answers the three questions every boundary asks about a value in one:\n *\n * 1. Is this string IN the domain, and what is its canonical spelling?\n * (`canonicalizeId`: the uppercase UUID and the lowercase ULID are aliases,\n * and an identity-sensitive consumer — a cache key, a captured row key, an\n * `fkEquals` — must see one spelling for one identifier.)\n * 2. What does the column physically hold for it? (`encodePhysicalId`)\n * 3. Which public value did a physical one come back as? (`decodePhysicalId`)\n *\n * It is PURE and dialect-blind on purpose. It takes an\n * {@link IdRepresentation}, never a provider: choosing the representation is a\n * storage question, owned one layer up in\n * {@link file://../../schema/scalars/string/id-domain.ts}, and a codec that\n * knew about `bytea` could not be read by the validation schemas that run\n * before any adapter exists.\n *\n * Two things it deliberately does NOT do. It never splits a value on `-`: a\n * prefix is matched WHOLE, because `usr-01H…` and a UUID both contain hyphens\n * and a generic split would silently reinterpret one as the other. And it\n * never widens a format: a text that is not a spelling of the declared format\n * is `undefined` here, so the boundary that asked owns the message.\n */\n\nimport { normalizeBinaryValue } from \"./binary-shapes\";\nimport {\n applyIdPrefix,\n BASE62,\n bytesToKsuid,\n bytesToUlid,\n bytesToUuid,\n CROCKFORD,\n CUID_TEXT,\n hasIdPrefix,\n KSUID_BYTE_LENGTH,\n KSUID_MAX_TEXT,\n ksuidToBytes,\n NANOID_ALPHABET,\n NANOID_DEFAULT_LENGTH,\n ULID_BYTE_LENGTH,\n UUID_BYTE_LENGTH,\n UUID_TEXT,\n ulidToBytes,\n uuidToBytes,\n} from \"./id-formats\";\n\n// =============================================================================\n// THE DOMAIN\n// =============================================================================\n\n/** The six string generators that name an identifier domain. */\nexport type IdFormat = \"uuid\" | \"uuidv7\" | \"ulid\" | \"ksuid\" | \"nanoid\" | \"cuid\";\n\nconst ID_FORMATS: ReadonlySet<string> = new Set<IdFormat>([\n \"uuid\",\n \"uuidv7\",\n \"ulid\",\n \"ksuid\",\n \"nanoid\",\n \"cuid\",\n]);\n\n/** Whether a generator kind names an identifier domain. */\nexport function isIdFormat(kind: string | undefined): kind is IdFormat {\n return kind !== undefined && ID_FORMATS.has(kind);\n}\n\n/**\n * A declared or derived identifier domain.\n *\n * `prefix` is absent rather than empty when none was declared — `\"\"` is how a\n * caller spells \"no prefix\", and carrying it would make a bare `-` part of\n * every value. `length` belongs to `nanoid` alone; every other format's width\n * is the format's own.\n */\nexport interface IdDomain {\n readonly format: IdFormat;\n readonly prefix?: string | undefined;\n readonly length?: number | undefined;\n}\n\n/**\n * The four formats whose values are stored COMPACT — as bytes, or as a\n * PostgreSQL `uuid`.\n *\n * Compactness is what costs them `contains`/`startsWith`/`endsWith`/`mode`: a\n * substring of a 16-byte column is not a substring of the text a caller wrote.\n * `nanoid` and `cuid` stay text and keep every string operator.\n */\nexport function isCompactIdFormat(format: IdFormat): boolean {\n return (\n format === \"uuid\" ||\n format === \"uuidv7\" ||\n format === \"ulid\" ||\n format === \"ksuid\"\n );\n}\n\n/** Whether two domains admit exactly the same values and store them alike. */\nexport function sameIdDomain(\n left: IdDomain | undefined,\n right: IdDomain | undefined\n): boolean {\n if (left === undefined || right === undefined) return left === right;\n return (\n left.format === right.format &&\n idPrefixOf(left) === idPrefixOf(right) &&\n nanoidLengthOf(left) === nanoidLengthOf(right)\n );\n}\n\n/** The declared prefix, with `\"\"` read as the absence it spells. */\nfunction idPrefixOf(domain: IdDomain): string | undefined {\n return hasIdPrefix(domain.prefix) ? domain.prefix : undefined;\n}\n\n/** The width a nanoid domain admits; every other format has a fixed one. */\nfunction nanoidLengthOf(domain: IdDomain): number | undefined {\n if (domain.format !== \"nanoid\") return undefined;\n return domain.length ?? NANOID_DEFAULT_LENGTH;\n}\n\n/** One phrase naming a domain, for a refusal that has to say what was expected. */\nexport function describeIdDomain(domain: IdDomain): string {\n const prefix = idPrefixOf(domain);\n const width =\n domain.format === \"nanoid\" ? ` of length ${nanoidLengthOf(domain)}` : \"\";\n return prefix === undefined\n ? `a ${domain.format} value${width}`\n : `a ${domain.format} value${width} prefixed '${prefix}-'`;\n}\n\n/** The characters a pattern reads as syntax, escaped in a literal prefix. */\nconst PATTERN_SYNTAX = /[$()*+./?[\\\\\\]^{|}]/g;\n\n/**\n * The domain as one ECMAScript pattern, for a reader that cannot run\n * {@link canonicalizeId} — the JSON Schema export. A string matches it exactly\n * when `canonicalizeId` admits it: the declared prefix whole, then a payload\n * the format's own text conversion accepts, aliases included.\n */\nexport function idDomainPattern(domain: IdDomain): string {\n const prefix = idPrefixOf(domain);\n const marker =\n prefix === undefined ? \"\" : `${prefix.replace(PATTERN_SYNTAX, \"\\\\$&\")}-`;\n return `^${marker}${payloadPattern(domain)}$`;\n}\n\nfunction payloadPattern(domain: IdDomain): string {\n switch (domain.format) {\n case \"uuid\":\n case \"uuidv7\":\n return UUID_TEXT.source.slice(1, -1);\n case \"ulid\":\n // The first digit carries the top 3 of 128 bits, so it is at most 7.\n return `[0-7][${CROCKFORD}${CROCKFORD.toLowerCase()}]{25}`;\n case \"ksuid\":\n return base62NotAbove(KSUID_MAX_TEXT);\n case \"nanoid\":\n return `[${NANOID_ALPHABET.replace(\"-\", \"\\\\-\")}]{${nanoidLengthOf(domain)}}`;\n default:\n return CUID_TEXT.source.slice(1, -1);\n }\n}\n\n/**\n * A base62 text as wide as `max` and not above it. Base62's ASCII order is its\n * numeric order, so \"not above\" is: `max` itself, or a prefix of it followed by\n * a smaller digit and any digits after.\n */\nfunction base62NotAbove(max: string): string {\n const arms = [max];\n for (let index = 0; index < max.length; index++) {\n const below = base62Below(max[index]!);\n if (below !== \"\")\n arms.push(\n `${max.slice(0, index)}[${below}][0-9A-Za-z]{${max.length - index - 1}}`\n );\n }\n return `(?:${arms.join(\"|\")})`;\n}\n\nconst BASE62_RUN = /[0-9]{3,}|[A-Z]{3,}|[a-z]{3,}/g;\n\n/** The base62 digits below `digit`, runs of three or more as ranges. */\nfunction base62Below(digit: string): string {\n return BASE62.slice(0, BASE62.indexOf(digit)).replace(\n BASE62_RUN,\n (run) => `${run[0]}-${run.at(-1)}`\n );\n}\n\n// =============================================================================\n// ADMISSION\n// =============================================================================\n\n/**\n * The PAYLOAD of a public value: everything after an exactly-matched\n * `prefix-`, or the whole value when the domain declares no prefix.\n *\n * `undefined` means the prefix the domain declares is not the one this value\n * carries, which is a refusal and never a reason to try the bare payload.\n */\nfunction payloadOf(value: string, domain: IdDomain): string | undefined {\n const prefix = idPrefixOf(domain);\n if (prefix === undefined) return value;\n const marker = `${prefix}-`;\n return value.startsWith(marker) ? value.slice(marker.length) : undefined;\n}\n\n/** Whether every character of `text` is one this nanoid alphabet has. */\nfunction isNanoidPayload(text: string, length: number): boolean {\n if (text.length !== length) return false;\n for (const char of text) {\n if (!NANOID_ALPHABET.includes(char)) return false;\n }\n return true;\n}\n\n/**\n * The canonical spelling of one payload, or `undefined`.\n *\n * The compact formats normalize through their own byte conversion — the leaf\n * already owns which spellings are aliases and which are not values at all —\n * so a ULID whose first character exceeds `7` and a UUID with braces are\n * refused here for the same reason they are refused there. The text formats\n * are case-sensitive with no aliases, so their canonical form is themselves.\n */\nfunction canonicalizePayload(\n payload: string,\n domain: IdDomain\n): string | undefined {\n switch (domain.format) {\n case \"uuid\":\n case \"uuidv7\": {\n const bytes = uuidToBytes(payload);\n return bytes === undefined ? undefined : bytesToUuid(bytes);\n }\n case \"ulid\": {\n const bytes = ulidToBytes(payload);\n return bytes === undefined ? undefined : bytesToUlid(bytes);\n }\n case \"ksuid\":\n return ksuidToBytes(payload) === undefined ? undefined : payload;\n case \"nanoid\":\n return isNanoidPayload(payload, nanoidLengthOf(domain)!)\n ? payload\n : undefined;\n default:\n return CUID_TEXT.test(payload) ? payload : undefined;\n }\n}\n\n/**\n * The canonical PUBLIC value this domain names, or `undefined` when the input\n * is not one of its values.\n *\n * This is the admission every boundary shares: create and update values, unique\n * selectors, `equals`/`not`/`in`/`notIn`/`lt`/`lte`/`gt`/`gte` operands,\n * cursors, and every `connect`/`connectOrCreate`/`upsert` key. Normalizing HERE\n * — once, before anything identity-sensitive — is what keeps one identifier\n * from hashing to two cache keys.\n */\nexport function canonicalizeId(\n value: unknown,\n domain: IdDomain\n): string | undefined {\n if (typeof value !== \"string\") return undefined;\n const payload = payloadOf(value, domain);\n if (payload === undefined) return undefined;\n const canonical = canonicalizePayload(payload, domain);\n return canonical === undefined\n ? undefined\n : applyIdPrefix(idPrefixOf(domain), canonical);\n}\n\n// =============================================================================\n// PHYSICAL REPRESENTATION\n// =============================================================================\n\n/**\n * What a column physically holds for one identifier.\n *\n * - `\"text\"` — the whole PUBLIC string, prefix included. Every `nanoid` and\n * `cuid` field, and any domain field whose native type override keeps a text\n * column.\n * - `\"uuid\"` — the payload as canonical UUID text, which is what a PostgreSQL\n * `uuid` column takes and returns on the wire.\n * - `\"bytes\"` — the payload's own bytes: 16 for a UUID or ULID, 20 for a KSUID.\n *\n * A declared PREFIX is never stored. It is a fact of the declaration, identical\n * in every row, and re-applied on read — which is also why `\"uuid\"` and\n * `\"bytes\"` are not identity paths for a prefixed field.\n */\nexport type IdRepresentation = \"text\" | \"uuid\" | \"bytes\";\n\n/** The bytes a canonical payload names, for a domain that has a byte form. */\nfunction payloadBytes(\n payload: string,\n format: IdFormat\n): Uint8Array | undefined {\n switch (format) {\n case \"uuid\":\n case \"uuidv7\":\n return uuidToBytes(payload);\n case \"ulid\":\n return ulidToBytes(payload);\n case \"ksuid\":\n return ksuidToBytes(payload);\n default:\n return undefined;\n }\n}\n\n/** The byte width a compact format's column holds, or `undefined` for text. */\nexport function idByteLength(format: IdFormat): number | undefined {\n switch (format) {\n case \"uuid\":\n case \"uuidv7\":\n return UUID_BYTE_LENGTH;\n case \"ulid\":\n return ULID_BYTE_LENGTH;\n case \"ksuid\":\n return KSUID_BYTE_LENGTH;\n default:\n return undefined;\n }\n}\n\n/**\n * The public text a compact format's bytes name, or `undefined` on a bad width.\n *\n * The width guard is what makes the rest total: a text format has no byte\n * width, so `bytes.length !== undefined` is always true and `nanoid`/`cuid`\n * never reach the conversions below. A `default` arm here would be a case no\n * call can produce.\n */\nfunction textOfBytes(bytes: Uint8Array, format: IdFormat): string | undefined {\n if (bytes.length !== idByteLength(format)) return undefined;\n if (format === \"ulid\") return bytesToUlid(bytes);\n if (format === \"ksuid\") return bytesToKsuid(bytes);\n return bytesToUuid(bytes);\n}\n\n/**\n * The physical value to bind for one CANONICAL public string, or `undefined`\n * when the string is not in the domain.\n *\n * The caller has normally canonicalized already — the field's validation schema\n * did it on the way in — and passing a non-canonical alias here still works,\n * because the encoding goes through the same admission. What it will not do is\n * invent a value: a string outside the domain has no bytes, and binding one\n * would write a row no read could ever return.\n */\nexport function encodePhysicalId(\n value: string,\n domain: IdDomain,\n representation: IdRepresentation\n): string | Uint8Array | undefined {\n const canonical = canonicalizeId(value, domain);\n if (canonical === undefined) return undefined;\n if (representation === \"text\") return canonical;\n const payload = payloadOf(canonical, domain)!;\n if (representation === \"uuid\") return payload;\n return payloadBytes(payload, domain.format);\n}\n\n/**\n * The public string a physical value stands for, or `undefined` when the\n * column holds something this domain cannot name.\n *\n * The `\"bytes\"` arm accepts every shape a driver spells binary in — `Buffer`,\n * `Uint8Array`, `ArrayBuffer`, a byte array, PostgreSQL's `\\x…`, MySQL's\n * `base64:typeNNN:…`, and the lowercase hex a JSON carrier travels as —\n * through the one shared normalization, so a nested `include` and a flat select\n * decode the same row to the same string.\n */\nexport function decodePhysicalId(\n physical: unknown,\n domain: IdDomain,\n representation: IdRepresentation\n): string | undefined {\n if (representation === \"text\") {\n return canonicalizeId(physical, domain);\n }\n if (representation === \"uuid\") {\n if (typeof physical !== \"string\") return undefined;\n const bytes = uuidToBytes(physical);\n return bytes === undefined\n ? undefined\n : applyIdPrefix(idPrefixOf(domain), bytesToUuid(bytes));\n }\n const shape = normalizeBinaryValue(physical);\n if (shape.bytes === undefined) return undefined;\n const text = textOfBytes(shape.bytes, domain.format);\n return text === undefined\n ? undefined\n : applyIdPrefix(idPrefixOf(domain), text);\n}\n","/**\n * Standard JSON Schema types for VibORM.\n * Implements the StandardJSONSchemaV1 specification.\n * @see https://standardschema.dev/json-schema\n */\n\n// =============================================================================\n// JSON Schema Target Versions\n// =============================================================================\n\n/**\n * Supported JSON Schema target versions.\n * - draft-07: JSON Schema Draft 7 (widely used)\n * - draft-2020-12: JSON Schema Draft 2020-12 (latest)\n * - openapi-3.0: OpenAPI 3.0 compatible (superset of draft-04)\n */\nexport type JsonSchemaTarget =\n | \"draft-07\"\n | \"draft-2020-12\"\n | \"openapi-3.0\"\n | ({} & string); // Allows future targets\n\n/**\n * Supported targets for validation.\n */\nexport const SUPPORTED_TARGETS: JsonSchemaTarget[] = [\n \"draft-07\",\n \"draft-2020-12\",\n \"openapi-3.0\",\n];\n\n// =============================================================================\n// JSON Schema Options\n// =============================================================================\n\n/**\n * Options for JSON Schema conversion methods.\n */\nexport interface JsonSchemaOptions {\n /** Target JSON Schema version */\n readonly target: JsonSchemaTarget;\n /** Vendor-specific options */\n readonly libraryOptions?: Record<string, unknown> | undefined;\n}\n\n// =============================================================================\n// JSON Schema Types\n// =============================================================================\n\n/**\n * JSON Schema object type.\n * A flexible record that can hold any JSON Schema properties.\n */\nexport interface JsonSchema {\n $schema?: string;\n $defs?: Record<string, JsonSchema>;\n $ref?: string;\n type?: string | string[];\n const?: unknown;\n enum?: unknown[];\n properties?: Record<string, JsonSchema>;\n required?: string[];\n additionalProperties?: boolean | JsonSchema;\n items?: JsonSchema | JsonSchema[];\n prefixItems?: JsonSchema[];\n minItems?: number;\n maxItems?: number;\n uniqueItems?: boolean;\n anyOf?: JsonSchema[];\n oneOf?: JsonSchema[];\n allOf?: JsonSchema[];\n nullable?: boolean; // OpenAPI 3.0 specific\n format?: string;\n contentEncoding?: string;\n minimum?: number;\n maximum?: number;\n minLength?: number;\n maxLength?: number;\n pattern?: string;\n default?: unknown;\n description?: string;\n title?: string;\n [key: string]: unknown;\n}\n\n// =============================================================================\n// JSON Schema Converter Interface\n// =============================================================================\n\n/**\n * JSON Schema converter interface.\n * Provides methods to convert to input/output JSON Schema.\n */\nexport interface JsonSchemaConverter {\n /**\n * Converts the input type to JSON Schema.\n * @throws If conversion is not supported for the given target.\n */\n readonly input: (options: JsonSchemaOptions) => Record<string, unknown>;\n\n /**\n * Converts the output type to JSON Schema.\n * @throws If conversion is not supported for the given target.\n */\n readonly output: (options: JsonSchemaOptions) => Record<string, unknown>;\n}\n\n// =============================================================================\n// Conversion Context\n// =============================================================================\n\n/**\n * One schema whose conversion is currently OPEN — i.e. sits somewhere on the\n * conversion call stack. Reaching the same schema again (through a `lazyRef`\n * or a thunk) means the schema graph is cyclic, and JSON Schema spells a cycle\n * with `$ref` rather than by inlining forever.\n *\n * `pointer` is allocated LAZILY, the first time something actually refers back\n * to the frame: a frame nobody points at emits its body inline, exactly as\n * before cycles were understood at all.\n */\nexport interface ConversionFrame {\n /** The schema this frame is converting (identity, not structure). */\n schema: unknown;\n /** The `$ref` value pointing at this frame, or null while unreferenced. */\n pointer: string | null;\n /** The `$defs` key holding the body — null when the frame is the root. */\n name: string | null;\n}\n\n/**\n * Context for JSON Schema conversion.\n * Used to track definitions and references for circular schemas.\n */\nexport interface ConversionContext {\n /** Accumulated definitions for $defs */\n definitions: Record<string, JsonSchema>;\n /** Map of schema objects to their reference IDs */\n referenceMap: Map<unknown, string>;\n /** Schemas whose conversion is currently open, keyed by identity */\n activeFrames: Map<unknown, ConversionFrame>;\n /**\n * The schema at the document root, if known. A cycle back to it is the whole\n * document, so it is spelled `#` and needs no definition of its own.\n */\n rootSchema?: unknown;\n /** Counter for generating unique reference IDs */\n refCount: number;\n /** The target version being generated */\n target: JsonSchemaTarget;\n /**\n * Which side of a transforming schema is being described. Omission keeps\n * the historical input projection for callers that build a context.\n */\n direction?: \"input\" | \"output\";\n}\n\n/**\n * Creates a new conversion context.\n *\n * @param target - The target JSON Schema version\n * @param rootSchema - The schema being converted at the document root, so a\n * cycle back to it can be spelled as the root pointer `#`\n * @param direction - The input or output side of transforming schemas\n */\nexport function createContext(\n target: JsonSchemaTarget,\n rootSchema?: unknown,\n direction: \"input\" | \"output\" = \"input\"\n): ConversionContext {\n return {\n definitions: {},\n referenceMap: new Map(),\n activeFrames: new Map(),\n rootSchema,\n refCount: 0,\n target,\n direction,\n };\n}\n","/**\n * Schema to JSON Schema converters.\n * Handles conversion of VibORM schemas to JSON Schema format.\n */\n\nimport { ValidationError } from \"@errors\";\nimport { BIGINT_TEXT_PATTERN } from \"../primitives/bigint\";\nimport type { DecimalSchema } from \"../primitives/decimal\";\nimport type { DecimalDescriptor } from \"../primitives/decimal-codec\";\nimport {\n GEO_BOUNDS_KEYS,\n GEO_LATITUDE_MAX,\n GEO_LATITUDE_MIN,\n GEO_LONGITUDE_MAX,\n GEO_LONGITUDE_MIN,\n GEO_POINT_KEYS,\n GEO_POLYGON_MIN_RING_POINTS,\n} from \"../primitives/geo-values\";\nimport { type IdDomain, idDomainPattern } from \"../primitives/id-codec\";\nimport type { ExactlyOneSchema } from \"../scalars/decimal\";\nimport type { VibSchema } from \"../types\";\nimport { isFunction, isRecord, isString } from \"../value-guards\";\nimport type {\n ConversionContext,\n ConversionFrame,\n JsonSchema,\n JsonSchemaTarget,\n} from \"./types\";\nimport { createContext, SUPPORTED_TARGETS } from \"./types\";\n\n// =============================================================================\n// Helper Functions\n// =============================================================================\n\n/**\n * Wrapper schema types that should be traversed to find inner schemas.\n */\nconst WRAPPER_TYPES = new Set([\"array\", \"nullable\", \"optional\", \"lazyRef\"]);\nconst DECIMAL_INPUT_PATTERN = \"^[+-]?(?:\\\\d+(?:\\\\.\\\\d*)?|\\\\.\\\\d+)$\";\nconst DECIMAL_OUTPUT_PATTERN =\n \"^(?:0|-?(?:[1-9]\\\\d*(?:\\\\.\\\\d*[1-9])?|0\\\\.\\\\d*[1-9]))$\";\n\n/**\n * The input literal grammar restricted to a declared domain: at most\n * `precision - scale` significant integer digits and at most `scale`\n * significant fractional digits, any leading and trailing zeros aside.\n */\nfunction decimalDomainPattern({ precision, scale }: DecimalDescriptor): string {\n const integer = precision - scale;\n const whole = integer === 0 ? \"0+\" : `(?:0+|0*[1-9]\\\\d{0,${integer - 1}})`;\n const fraction = `\\\\d{0,${scale}}0*`;\n const bareFraction = scale === 0 ? \"0+\" : `\\\\d{1,${scale}}0*`;\n return `^[+-]?(?:${whole}(?:\\\\.${fraction})?|\\\\.${bareFraction})$`;\n}\n\nfunction geoPointJsonSchema(): JsonSchema {\n return {\n type: \"object\",\n properties: {\n [GEO_POINT_KEYS[0]]: {\n type: \"number\",\n minimum: GEO_LONGITUDE_MIN,\n maximum: GEO_LONGITUDE_MAX,\n },\n [GEO_POINT_KEYS[1]]: {\n type: \"number\",\n minimum: GEO_LATITUDE_MIN,\n maximum: GEO_LATITUDE_MAX,\n },\n },\n required: [...GEO_POINT_KEYS],\n additionalProperties: false,\n };\n}\n\nfunction geoBoundsJsonSchema(): JsonSchema {\n const latitude = {\n type: \"number\" as const,\n minimum: GEO_LATITUDE_MIN,\n maximum: GEO_LATITUDE_MAX,\n };\n const longitude = {\n type: \"number\" as const,\n minimum: GEO_LONGITUDE_MIN,\n maximum: GEO_LONGITUDE_MAX,\n };\n return {\n type: \"object\",\n properties: {\n [GEO_BOUNDS_KEYS[0]]: latitude,\n [GEO_BOUNDS_KEYS[1]]: longitude,\n [GEO_BOUNDS_KEYS[2]]: latitude,\n [GEO_BOUNDS_KEYS[3]]: longitude,\n },\n required: [...GEO_BOUNDS_KEYS],\n additionalProperties: false,\n };\n}\n\ntype ConvertibleExactOneSchema = ExactlyOneSchema<\n Record<\n string,\n VibSchema<unknown, unknown> | (() => VibSchema<unknown, unknown>)\n >\n>;\n\ntype ConvertibleDecimalSchema = DecimalSchema<unknown, unknown> & {\n readonly options:\n | (NonNullable<DecimalSchema[\"options\"]> & {\n readonly array?: boolean | undefined;\n readonly nullable?: boolean | undefined;\n })\n | undefined;\n};\n\n/** Internal schema tags are the discriminants for their complete metadata. */\nfunction isDecimalSchema(\n schema: VibSchema<unknown, unknown>\n): schema is ConvertibleDecimalSchema {\n return schema.type === \"decimal\";\n}\n\nfunction isExactOneSchema(\n schema: VibSchema<unknown, unknown>\n): schema is ConvertibleExactOneSchema {\n return schema.type === \"exact_one\";\n}\n\n/**\n * Traverse through wrapper schemas to find the innermost schema.\n * Wrappers include: array, nullable, optional\n */\nfunction getInnerSchema(schema: any): any {\n let current = schema;\n while (current && WRAPPER_TYPES.has(current.type)) {\n // array uses 'item', others use 'wrapped'\n current = current.item ?? current.wrapped;\n }\n return current;\n}\n\n/**\n * The `$ref` value for an open frame something has just referred back to,\n * allocating it on first use.\n *\n * A cycle back to the document ROOT is the whole document, so it is spelled\n * `#` and hoists nothing. Anything else gets a `$defs` entry: a schema that\n * declares a name keeps it, an anonymous one — every recursive scalar filter,\n * whose `not` arm points back at the filter object itself — gets a generated\n * one. The key is reserved immediately so a second, concurrently-open frame\n * cannot claim it; the placeholder is overwritten with the real body when the\n * frame completes.\n */\nfunction framePointer(\n frame: ConversionFrame,\n context: ConversionContext\n): string {\n if (frame.pointer !== null) {\n return frame.pointer;\n }\n\n if (frame.schema === context.rootSchema) {\n frame.pointer = \"#\";\n return frame.pointer;\n }\n\n const declared = (frame.schema as { options?: { name?: string } }).options\n ?.name;\n let name = declared === \"\" ? undefined : declared;\n\n while (name === undefined || name in context.definitions) {\n context.refCount += 1;\n name = `Recursive${context.refCount}`;\n }\n\n frame.name = name;\n frame.pointer = `#/$defs/${name}`;\n // Reserve the key; the body lands here when the frame finishes converting.\n context.definitions[name] = {};\n return frame.pointer;\n}\n\n// =============================================================================\n// Main Converter\n// =============================================================================\n\n/**\n * Converts a VibORM schema to JSON Schema format.\n *\n * Cycle-aware: a schema graph may point back at itself (a scalar filter's\n * `not` arm is the filter itself, a model's `where` comes back round through\n * `AND`/`OR`/`NOT`). JSON Schema expresses that with `$ref`, so a schema\n * reached again while its own conversion is still open emits a reference —\n * `#` when it is the document root, otherwise a `$defs` entry holding its\n * body. A schema nothing points back at is unaffected: it is still inlined,\n * byte for byte as before.\n *\n * @param schema - The VibORM schema to convert\n * @param context - The conversion context for tracking references\n * @param skipRef - Whether to skip reference lookup (for inline conversion)\n * @returns The converted JSON Schema\n */\nexport function convertSchema(\n schema: VibSchema<unknown, unknown>,\n context: ConversionContext,\n skipRef = false\n): JsonSchema {\n if (!skipRef) {\n // Check for existing reference (circular schema support)\n const existingRef = context.referenceMap.get(schema);\n if (existingRef) {\n return { $ref: `#/$defs/${existingRef}` };\n }\n\n // Reached a schema that is still being converted further up the stack:\n // the graph is cyclic. Close it with a $ref rather than recursing forever.\n const openFrame = context.activeFrames.get(schema);\n if (openFrame) {\n return { $ref: framePointer(openFrame, context) };\n }\n }\n\n const shadowed = context.activeFrames.get(schema);\n const frame: ConversionFrame = { schema, pointer: null, name: null };\n context.activeFrames.set(schema, frame);\n\n let body: JsonSchema;\n try {\n body = convertSchemaBody(schema, context);\n if (\"options\" in schema && isRecord(schema.options)) {\n if (schema.options.array === true) body = { type: \"array\", items: body };\n if (schema.options.nullable === true)\n body =\n context.target === \"openapi-3.0\"\n ? { ...body, nullable: true }\n : { anyOf: [body, { type: \"null\" }] };\n }\n } finally {\n if (shadowed) {\n context.activeFrames.set(schema, shadowed);\n } else {\n context.activeFrames.delete(schema);\n }\n }\n\n if (frame.name === null) {\n // Either nothing pointed back at this schema, or it IS the document root\n // and the back-references already say `#`. Either way it stays inline.\n return body;\n }\n\n context.definitions[frame.name] = body;\n // Later occurrences of the same schema reuse the definition instead of\n // re-emitting the body.\n context.referenceMap.set(schema, frame.name);\n return { $ref: frame.pointer as string };\n}\n\n/**\n * The per-type conversion itself. Never call this directly — {@link convertSchema}\n * wraps it with the cycle bookkeeping every recursive schema depends on.\n */\nfunction convertSchemaBody(\n schema: VibSchema<unknown, unknown>,\n context: ConversionContext\n): JsonSchema {\n const jsonSchema: JsonSchema = {};\n\n if (isDecimalSchema(schema)) {\n // A decimal accepts a `Decimal` or a string, and validates to the\n // canonical string. A JSON number is a double and is refused, so it has\n // no arm. A `Decimal` object has no JSON Schema because a class instance\n // is not a JSON value; its own `toJSON()` produces the string.\n //\n // The DECLARED DOMAIN is part of the input pattern. Both bounds count\n // SIGNIFICANT digits, after canonicalization (`\"1.500\"` fits a scale-2\n // field because it names 1.5): at most `scale` fractional digits before\n // trailing zeros, and at most `precision - scale` integer digits after\n // leading zeros — `domainRefusal`'s rule, spelled as text.\n const options = schema.options;\n const domain = options?.decimal;\n if (domain) {\n jsonSchema.description = `Exact decimal with at most ${domain.precision} total digits and at most ${domain.scale} fractional digits`;\n }\n jsonSchema.type = \"string\";\n // Output is the codec's ONE canonical spelling, not the broader literal\n // grammar accepted on input: no leading plus/zero, dangling point,\n // trailing fractional zero, or signed zero survives validation.\n if (context.direction === \"output\") {\n jsonSchema.pattern = DECIMAL_OUTPUT_PATTERN;\n } else {\n jsonSchema.pattern = domain\n ? decimalDomainPattern(domain)\n : DECIMAL_INPUT_PATTERN;\n }\n\n return jsonSchema;\n }\n\n if (isExactOneSchema(schema)) {\n // Decimal updates own one runtime rule: exactly one declared operation.\n // Each JSON arm carries and requires only its selected property, so a\n // two-key bag cannot satisfy any arm.\n const arms: JsonSchema[] = [];\n for (const [key, entry] of Object.entries(schema.entries)) {\n const entrySchema = isFunction<() => VibSchema<unknown, unknown>>(entry)\n ? entry()\n : entry;\n // A refused entry exists only to give an untyped runtime caller a useful\n // explanation. It accepts no value and is not part of the JSON language.\n if (entrySchema.type === \"refused\") continue;\n arms.push({\n type: \"object\",\n properties: { [key]: convertSchema(entrySchema, context) },\n required: [key],\n additionalProperties: false,\n });\n }\n jsonSchema.oneOf = arms;\n return jsonSchema;\n }\n\n // Get schema type\n const schemaType = schema.type;\n\n // Convert based on schema type\n switch (schemaType) {\n // =========================================================================\n // Primitive Schemas\n // =========================================================================\n\n case \"string\": {\n jsonSchema.type = \"string\";\n const idDomain = (schema as { options?: { idDomain?: IdDomain } }).options\n ?.idDomain;\n if (idDomain) jsonSchema.pattern = idDomainPattern(idDomain);\n break;\n }\n\n case \"number\":\n case \"integer\":\n jsonSchema.type = schemaType === \"integer\" ? \"integer\" : \"number\";\n if (\"minimum\" in schema && typeof schema.minimum === \"number\")\n jsonSchema.minimum = schema.minimum;\n if (\"maximum\" in schema && typeof schema.maximum === \"number\")\n jsonSchema.maximum = schema.maximum;\n break;\n\n case \"boolean\":\n jsonSchema.type = \"boolean\";\n break;\n\n case \"bigint\":\n // A bigint crosses JSON as integer text: a JSON number past 2^53 has\n // already lost digits. The validator admits the same text.\n jsonSchema.type = \"string\";\n jsonSchema.pattern = BIGINT_TEXT_PATTERN;\n break;\n\n case \"literal\": {\n const value = (schema as any).value;\n if (context.target === \"openapi-3.0\") {\n // OpenAPI 3.0 doesn't support const, use enum\n jsonSchema.enum = [value];\n } else {\n jsonSchema.const = value;\n }\n break;\n }\n\n case \"enum\": {\n const values = (schema as any).values;\n jsonSchema.enum = values;\n break;\n }\n\n // =========================================================================\n // Wrapper Schemas\n // =========================================================================\n\n case \"nullable\": {\n const wrapped = (schema as any).wrapped as VibSchema<unknown, unknown>;\n const wrappedSchema = convertSchema(wrapped as any, context);\n\n if (context.target === \"openapi-3.0\") {\n // OpenAPI 3.0 uses nullable property\n Object.assign(jsonSchema, wrappedSchema);\n jsonSchema.nullable = true;\n } else {\n // Use anyOf with null\n jsonSchema.anyOf = [wrappedSchema, { type: \"null\" }];\n }\n break;\n }\n\n case \"optional\": {\n // Optional just passes through - optionality is handled at object level\n const wrapped = (schema as any).wrapped as VibSchema<unknown, unknown>;\n return convertSchema(wrapped as any, context);\n }\n\n case \"array\": {\n const item = (schema as any).item as VibSchema<unknown, unknown>;\n jsonSchema.type = \"array\";\n jsonSchema.items = convertSchema(item as any, context);\n break;\n }\n\n // =========================================================================\n // Composite Schemas\n // =========================================================================\n\n case \"object\": {\n const entries = (schema as any).entries as Record<string, unknown>;\n const options = (schema as any).options as\n | { partial?: boolean; strict?: boolean; atLeast?: readonly string[] }\n | undefined;\n const partial = options?.partial ?? true;\n const strict = options?.strict ?? true;\n\n jsonSchema.type = \"object\";\n jsonSchema.properties = {};\n jsonSchema.required = [];\n\n for (const key in entries) {\n const entry = entries[key];\n const isThunk = isFunction(entry);\n\n // Resolve thunks to get the actual schema\n const entrySchema = isThunk\n ? (entry as () => VibSchema<unknown, unknown>)()\n : (entry as VibSchema<unknown, unknown>);\n\n // Find the inner named object (if any) and pre-register it\n const innerSchema = getInnerSchema(entrySchema);\n const schemaName = innerSchema?.options?.name;\n\n if (\n schemaName &&\n isString(schemaName) &&\n !context.referenceMap.has(innerSchema)\n ) {\n // Pre-register the inner named object (not the wrapper)\n context.referenceMap.set(innerSchema, schemaName);\n // Convert the inner object and add to definitions\n context.definitions[schemaName] = convertSchema(\n innerSchema,\n context,\n true\n );\n }\n\n // Now convert the entry normally - if it hits a registered schema, it will emit $ref\n jsonSchema.properties[key] = convertSchema(entrySchema as any, context);\n\n // Determine if field is required\n const entryType = (entrySchema as any).type;\n const isOptionalWrapper =\n entryType === \"optional\" || entryType === \"nullish\";\n const acceptsUndefined =\n \"acceptsUndefined\" in entrySchema &&\n entrySchema.acceptsUndefined === true;\n const outputDefault =\n context.direction === \"output\" &&\n \"options\" in entrySchema &&\n isRecord(entrySchema.options) &&\n entrySchema.options.default !== undefined;\n\n if (\n (!partial || options?.atLeast?.includes(key)) &&\n (outputDefault || !(isOptionalWrapper || acceptsUndefined))\n ) {\n jsonSchema.required.push(key);\n }\n }\n\n // Handle strict mode\n if (strict) {\n jsonSchema.additionalProperties = false;\n }\n\n // Remove empty required array\n if (jsonSchema.required.length === 0) {\n jsonSchema.required = undefined;\n }\n\n break;\n }\n\n case \"record\": {\n const valueSchema = (schema as any).value as VibSchema<unknown, unknown>;\n jsonSchema.type = \"object\";\n jsonSchema.additionalProperties = convertSchema(\n valueSchema as any,\n context\n );\n break;\n }\n\n case \"union\": {\n const options = (schema as any).options as VibSchema<unknown, unknown>[];\n jsonSchema.anyOf = options.map((opt) =>\n convertSchema(opt as any, context)\n );\n break;\n }\n\n // =========================================================================\n // Date Schemas\n // =========================================================================\n\n case \"date\":\n jsonSchema.type = \"string\";\n jsonSchema.format = \"date-time\";\n break;\n\n case \"iso_timestamp\":\n jsonSchema.type = \"string\";\n jsonSchema.format = \"date-time\";\n break;\n\n case \"iso_date\":\n jsonSchema.type = \"string\";\n jsonSchema.format = \"date\";\n break;\n\n case \"iso_time\":\n jsonSchema.type = \"string\";\n jsonSchema.format = \"time\";\n break;\n\n // =========================================================================\n // Special Schemas\n // =========================================================================\n\n case \"json\":\n // JSON accepts any valid JSON value - empty schema accepts anything\n break;\n\n case \"refused\":\n // A key that exists only to explain why it is refused: it accepts\n // nothing, and `not: {}` is the JSON Schema that accepts nothing.\n jsonSchema.not = {};\n break;\n\n case \"blob\":\n jsonSchema.type = \"string\";\n jsonSchema.contentEncoding = \"base64\";\n break;\n\n case \"vector\": {\n const dimensions = (schema as any).dimensions as number | undefined;\n jsonSchema.type = \"array\";\n jsonSchema.items = { type: \"number\" };\n if (dimensions !== undefined) {\n jsonSchema.minItems = dimensions;\n jsonSchema.maxItems = dimensions;\n }\n break;\n }\n\n case \"point\":\n Object.assign(jsonSchema, geoPointJsonSchema());\n break;\n\n case \"geo_area\": {\n const ring: JsonSchema = {\n type: \"array\",\n items: geoPointJsonSchema(),\n minItems: GEO_POLYGON_MIN_RING_POINTS,\n };\n jsonSchema.oneOf = [\n {\n type: \"object\",\n properties: {\n bounds: {\n ...geoBoundsJsonSchema(),\n },\n },\n required: [\"bounds\"],\n additionalProperties: false,\n },\n {\n type: \"object\",\n properties: {\n polygon: {\n type: \"object\",\n properties: {\n outer: ring,\n holes: { type: \"array\", items: ring },\n },\n required: [\"outer\"],\n additionalProperties: false,\n },\n },\n required: [\"polygon\"],\n additionalProperties: false,\n },\n ];\n break;\n }\n\n case \"transform\": {\n // Transform wraps another schema - use the wrapped schema for JSON representation\n const wrapped = (schema as any).wrapped as VibSchema<unknown, unknown>;\n return convertSchema(wrapped as any, context);\n }\n\n case \"field_ref_or\":\n case \"comparison_operand\": {\n // A field reference, an SQL fragment, and the callback that returns one\n // are in-process values with no JSON representation: only the literal\n // operand they stand beside can cross a JSON boundary.\n const operand = (schema as any).wrapped as VibSchema<unknown, unknown>;\n return convertSchema(operand as any, context);\n }\n\n case \"lazyRef\": {\n // A deferred reference to a schema built elsewhere (args → core schemas,\n // and a scalar filter's `not` arm pointing back at the filter itself).\n // Resolving it here is what makes the reference transparent in JSON\n // Schema; the cycle bookkeeping in convertSchema is what keeps a\n // SELF-referential target from inlining forever.\n const target = (schema as any).wrapped as VibSchema<unknown, unknown>;\n return convertSchema(target as any, context);\n }\n\n case \"no_field_ref\": {\n // The mirror image: this wrapper only REMOVES in-process tokens, which\n // have no JSON representation to remove in the first place, so the JSON\n // shape is exactly the wrapped schema's.\n const inner = (schema as any).wrapped as VibSchema<unknown, unknown>;\n return convertSchema(inner as any, context);\n }\n\n case \"json_null_or\":\n case \"json_write\": {\n // The JSON null sentinels are in-process tokens (class instances), so\n // like a field reference they have no JSON representation: only the\n // document operand they wrap can cross a JSON boundary. `json_write`\n // additionally forbids a bare top-level null, which JSON Schema cannot\n // express here without contradicting the wrapped scalar's own nullable\n // shape — the runtime refusal is the enforcement, and this projection\n // stays the document language.\n const operand = (schema as any).wrapped as VibSchema<unknown, unknown>;\n return convertSchema(operand as any, context);\n }\n\n case \"polymorphic_only\": {\n // A variant allow-list: the membership list, each variant at most once.\n const { wrapped } = schema as VibSchema<unknown, unknown> & {\n wrapped: VibSchema<unknown, unknown>;\n };\n return { ...convertSchema(wrapped, context), uniqueItems: true };\n }\n\n case \"pipe\": {\n // Pipe contains a base schema and actions - use the base schema\n const baseSchema = (schema as any).schema as VibSchema<unknown, unknown>;\n return convertSchema(baseSchema as any, context);\n }\n\n default:\n throw new ValidationError({ kind: \"json-schema\", schemaType }, [\n {\n path: \"type\",\n message: `Cannot convert \"${schemaType}\" schema to JSON Schema: unsupported type`,\n },\n ]);\n }\n\n return jsonSchema;\n}\n\n// =============================================================================\n// Top-Level Conversion\n// =============================================================================\n\n/**\n * Converts a VibORM schema to a complete JSON Schema document.\n *\n * @param schema - The VibORM schema to convert\n * @param target - The target JSON Schema version\n * @returns Complete JSON Schema with $schema and $defs if needed\n */\nexport function toJsonSchema(\n schema: VibSchema<unknown, unknown>,\n target: JsonSchemaTarget = \"draft-07\"\n): JsonSchema {\n return toJsonSchemaForDirection(schema, target, \"input\");\n}\n\n/** Internal directional route used by the Standard Schema converter. */\nexport function toJsonSchemaForDirection(\n schema: VibSchema<unknown, unknown>,\n target: JsonSchemaTarget,\n direction: \"input\" | \"output\"\n): JsonSchema {\n if (!SUPPORTED_TARGETS.includes(target)) {\n throw new ValidationError({ kind: \"json-schema\", target }, [\n {\n path: \"target\",\n message: `Unsupported JSON Schema target: ${target}`,\n },\n ]);\n }\n\n const context = createContext(target, schema, direction);\n\n const jsonSchema = convertSchema(schema as any, context);\n\n // Add $schema URI based on target\n if (target === \"draft-2020-12\") {\n jsonSchema.$schema = \"https://json-schema.org/draft/2020-12/schema\";\n } else if (target === \"draft-07\") {\n jsonSchema.$schema = \"http://json-schema.org/draft-07/schema#\";\n }\n // OpenAPI 3.0 does not use $schema\n\n // Add definitions if any\n if (Object.keys(context.definitions).length > 0) {\n jsonSchema.$defs = context.definitions;\n }\n\n return jsonSchema;\n}\n","/**\n * Factory for creating JSON Schema converters.\n * Each schema gets its own jsonSchema property with input/output methods.\n */\n\nimport type { VibSchema } from \"../types\";\nimport { toJsonSchemaForDirection } from \"./converters\";\nimport type { JsonSchemaConverter, JsonSchemaOptions } from \"./types\";\n\n/**\n * Creates a JSON Schema converter for a VibORM schema.\n * The converter provides `input` and `output` methods that generate\n * JSON Schema representations of the schema's input and output types.\n *\n * @param schema - The VibORM schema to create a converter for\n * @returns A JsonSchemaConverter with input and output methods\n */\nexport function createJsonSchemaConverter(\n schema: VibSchema<unknown, unknown>\n): JsonSchemaConverter {\n return {\n input(options: JsonSchemaOptions): Record<string, unknown> {\n return toJsonSchemaForDirection(schema, options.target, \"input\");\n },\n\n output(options: JsonSchemaOptions): Record<string, unknown> {\n return toJsonSchemaForDirection(schema, options.target, \"output\");\n },\n };\n}\n","import { errorCause, isError } from \"../errors/diagnostic-safety\";\nimport { sanitizeErrorCause } from \"../errors/diagnostics\";\nimport type { ValidationFailure } from \"./types\";\n\nconst PARSE_FAILURE_CAUSE = Symbol(\"viborm.validation.parseFailureCause\");\n\n/** A refused async validator must not leak a later process-level rejection. */\nexport function discardAsyncValidationResult(result: unknown): void {\n Promise.resolve(result).catch(() => undefined);\n}\n\n/** Contain a thrown validator value while retaining sanitized cause evidence. */\nexport function validationFailureFromThrown(cause: unknown): ValidationFailure {\n const error = errorCause(cause);\n const failure: ValidationFailure = {\n issues: [{ message: \"Schema validation failed unexpectedly\" }],\n };\n Object.defineProperty(failure, PARSE_FAILURE_CAUSE, {\n value: sanitizeErrorCause(error),\n });\n return failure;\n}\n\n/**\n * Read the sanitized cause retained by the public parse boundary, if any.\n *\n * The argument is a parse result, and every one of them is built by\n * `parse` itself — the failure literals in `validation/index.ts` and the\n * failure this module defines the symbol on. Reading a symbol off an object\n * the library constructed cannot throw and cannot be handed a non-object, so\n * the type states the invariant and no guard restates it.\n */\nexport function readValidationFailureCause(value: object): Error | undefined {\n const cause = Reflect.get(value, PARSE_FAILURE_CAUSE);\n return isError(cause) ? cause : undefined;\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { createJsonSchemaConverter } from \"../json-schema/factory\";\nimport { discardAsyncValidationResult } from \"../parse-failure\";\nimport type {\n ComputeInput,\n ComputeOutput,\n ScalarOptions,\n ValidationFailure,\n ValidationIssue,\n ValidationResult,\n VibSchema,\n} from \"../types\";\nimport { isFunction } from \"../value-guards\";\nimport { canonicalizeId, describeIdDomain, type IdDomain } from \"./id-codec\";\n\n// =============================================================================\n// Core Validation Primitives\n// =============================================================================\n\n/**\n * Create a failure result with a single issue.\n */\nexport function fail(\n message: string,\n path?: PropertyKey[]\n): ValidationResult<never> {\n const issue: ValidationIssue =\n path && path.length > 0 ? { message, path } : { message };\n return { issues: [issue] };\n}\n\n/**\n * Whether the parse in progress reports EVERY issue instead of the first. Set\n * by {@link reportingAllIssues} for one synchronous parse and restored in its\n * `finally`, like `parseProviding`'s context. Read only on a failure path, so\n * a parse that succeeds never pays for the mode.\n */\nlet allIssues = false;\n\n/** Does the parse in progress collect every issue? */\nexport const collectingAllIssues = (): boolean => allIssues;\n\n/** Run `parse` with the all-issues mode set to `collect`, then restore it. */\nexport function reportingAllIssues<T>(collect: boolean, parse: () => T): T {\n const outer = allIssues;\n allIssues = collect;\n try {\n return parse();\n } finally {\n allIssues = outer;\n }\n}\n\n/** A member's issues, re-rooted under `key`: only the first unless collecting. */\nexport function issuesUnder(\n key: PropertyKey,\n issues: readonly ValidationIssue[]\n): ValidationIssue[] {\n const reported = allIssues ? issues : issues.slice(0, 1);\n return reported.map((issue) => ({\n message: issue.message,\n path: issue.path ? [key, ...issue.path] : [key],\n }));\n}\n\n/**\n * Create a success result.\n */\nexport function ok<T>(value: T): ValidationResult<T> {\n return { value };\n}\n\n/** Copy Standard Schema issues into VibORM's property-key path representation. */\nexport function standardSchemaFailure(\n issues: readonly StandardSchemaV1.Issue[]\n): ValidationFailure {\n return {\n issues: issues.map((issue) => {\n if (issue.path === undefined) return { message: issue.message };\n return {\n message: issue.message,\n path: issue.path.map((segment) =>\n typeof segment === \"object\" ? segment.key : segment\n ),\n };\n }),\n };\n}\n\n// =============================================================================\n// Set Theory Optimized Validators\n// =============================================================================\n\n// Pre-allocated error objects (avoid allocation in hot path)\nconst ARRAY_TYPE_ERROR = Object.freeze({\n issues: Object.freeze([Object.freeze({ message: \"Expected array\" })]),\n});\n\n// Pre-allocated null/undefined results for fast paths\nexport const OK_NULL = Object.freeze({ value: null });\nexport const OK_UNDEFINED = Object.freeze({ value: undefined });\n\n/**\n * Validate array items with the provided validator.\n * Shared by the array() wrapper, options.array and every other list walk.\n */\nexport function validateArray<T>(\n value: unknown,\n validate: (v: unknown) => StandardSchemaV1.Result<T>\n): ValidationResult<T[]> {\n try {\n if (!Array.isArray(value)) {\n return ARRAY_TYPE_ERROR;\n }\n } catch {\n return fail(\"Could not inspect array\");\n }\n\n let len: number;\n try {\n len = value.length;\n } catch {\n return fail(\"Could not read array length\");\n }\n if (!Number.isInteger(len) || len < 0) {\n return ARRAY_TYPE_ERROR;\n }\n if (len === 0) return ok([]);\n\n const results = new Array<T>(len);\n let issues: ValidationIssue[] | undefined;\n for (let i = 0; i < len; i++) {\n let member: unknown;\n try {\n member = value[i];\n } catch {\n return fail(\"Could not read array member\", [i]);\n }\n const r = validate(member);\n if (r.issues) {\n const rooted = issuesUnder(i, r.issues as readonly ValidationIssue[]);\n if (!allIssues) return { issues: rooted };\n (issues ??= []).push(...rooted);\n continue;\n }\n results[i] = (r as { value: T }).value;\n }\n return issues ? { issues } : ok(results);\n}\n\ntype ValidatorFn<T> = (value: unknown) => ValidationResult<T>;\n\n// =============================================================================\n// Factories with Default (for optional + default cases)\n// =============================================================================\n\n/**\n * Resolve a default when undefined, contain a throwing factory, and pass the\n * resolved value through the already-composed field validator.\n */\nfunction createOptionalWithDefault<T>(\n validate: ValidatorFn<T>,\n getDefault: () => unknown\n): ValidatorFn<T> {\n return (val) => {\n if (val !== undefined) return validate(val);\n let resolved: unknown;\n try {\n resolved = getDefault();\n } catch (error) {\n return fail(`Default failed: ${describeDefaultFailure(error)}`);\n }\n return validate(resolved);\n };\n}\n\n/** Render hostile thrown values without letting their coercion escape. */\nfunction describeDefaultFailure(error: unknown): string {\n try {\n return String(error instanceof Error ? error.message : error);\n } catch {\n return \"unrenderable thrown value\";\n }\n}\n\n// =============================================================================\n// Optimized Validator Builder (Set Theory + Composition)\n// =============================================================================\n\n/** `next` on the value `prev` admitted; `prev`'s issues otherwise. */\nfunction thenValidate(\n prev: ValidatorFn<unknown>,\n next: ValidatorFn<unknown>\n): ValidatorFn<unknown> {\n return (value) => {\n const result = prev(value);\n return result.issues ? result : next(result.value);\n };\n}\n\n/** The canonical member of `domain`, or its \"Expected <domain>\" refusal. */\nfunction idDomainAdmission(domain: IdDomain): ValidatorFn<string> {\n const expected = `Expected ${describeIdDomain(domain)}`;\n return (value) => {\n const canonical = canonicalizeId(value, domain);\n return canonical === undefined ? fail(expected) : ok(canonical);\n };\n}\n\n/**\n * Build an optimized validator at schema creation time.\n * Uses set theory approach for nullable/optional/array/default combinations.\n *\n * @param baseValidate - The base type validator\n * @param options - Schema options\n * @param typeName - The scalar representation that must survive transforms\n */\nexport function buildValidator<T, TOut, TSchemaOut = T>(\n baseValidate: ValidatorFn<T>,\n options: ScalarOptions<T, TOut, TSchemaOut> | undefined,\n typeName: string\n): ValidatorFn<TOut> {\n // Fast path: no options at all\n if (!options) {\n return baseValidate as unknown as ValidatorFn<TOut>;\n }\n\n const {\n nullable,\n optional,\n array,\n default: defaultVal,\n transform,\n schema,\n disallowZero,\n idDomain,\n } = options;\n\n // Check what we have\n const hasDefault = defaultVal !== undefined;\n const hasTransform = transform !== undefined;\n\n // Build the core validator (base + schema + transform chain)\n let validate: ValidatorFn<any> = baseValidate;\n\n if (disallowZero) validate = refusingZero(validate);\n\n // The identifier domain is the first AND the last word on the value.\n // First, before the custom schema and the transform: a `.schema()` a caller\n // attached to a `.uuid()` field reads the canonical spelling. Last, after\n // that schema: its output is the caller's code — a Standard Schema may\n // return any string — so it crosses the domain again, where an alias it\n // returns folds and a value outside the domain is refused with the same\n // \"Expected <domain>\" an input gets, at admission rather than at the\n // binding. Every identity-sensitive consumer downstream — cache key,\n // captured row key, `fkEquals` — reads the one spelling that leaves, and\n // `canonicalizeId` is the only place an alias is folded. A transform never\n // meets a domain: `scalars/string.ts` is the one caller that passes\n // `idDomain`, and a field state carries no transform.\n const admitIdDomain =\n idDomain === undefined ? undefined : idDomainAdmission(idDomain);\n if (admitIdDomain) validate = thenValidate(validate, admitIdDomain);\n\n // Chain custom schema validation (if any)\n\n if (schema !== undefined)\n validate = withCustomSchema(validate, schema, admitIdDomain);\n\n // Chain transform (if any)\n if (hasTransform) validate = withTransform(validate, transform!);\n // A custom JSON schema may transform its input, but the persisted result\n // must still be JSON. Validate the new representation before any write.\n if (typeName === \"json\" && (hasTransform || schema !== undefined))\n validate = thenValidate(validate, baseValidate);\n\n // Compose the complete field validator before the default trigger. A\n // resolved literal or factory value is an ordinary untrusted field value:\n // it crosses scalar/custom/transform, member-array, and nullability rules in\n // exactly the same order as an explicit input.\n\n if (array) {\n const itemValidator = validate;\n validate = (val) => validateArray(val, itemValidator);\n }\n\n if (nullable) {\n const nonNullValidate = validate;\n validate = (val) => (val === null ? OK_NULL : nonNullValidate(val));\n }\n\n if (hasDefault) {\n // Compute default getter once\n const getDefault = isFunction(defaultVal)\n ? (defaultVal as () => any)\n : () => defaultVal;\n\n return createOptionalWithDefault(validate, getDefault) as ValidatorFn<TOut>;\n }\n\n // Nullability is already part of the composed validator. Only optionality\n // remains when no default consumes undefined.\n if (optional) {\n const requiredValidate = validate;\n validate = (val) =>\n val === undefined ? OK_UNDEFINED : requiredValidate(val);\n }\n\n return validate as ValidatorFn<TOut>;\n}\n\n// The rarely declared field options, each composed by its own function so a\n// field without them never compiles their setup.\n\nfunction refusingZero(prev: ValidatorFn<any>): ValidatorFn<any> {\n return (value): ValidationResult<any> => {\n const result = prev(value);\n if (result.issues) return result;\n const validated = (result as { value: unknown }).value;\n if (validated === 0 || validated === 0n) {\n return fail(\"Explicit zero is not portable for an auto-increment field\");\n }\n return result;\n };\n}\n\nfunction withCustomSchema(\n prev: ValidatorFn<any>,\n schema: NonNullable<ScalarOptions<any, any>[\"schema\"]>,\n admitIdDomain: ValidatorFn<any> | undefined\n): ValidatorFn<any> {\n const schemaValidate = schema[\"~standard\"].validate;\n const validate: ValidatorFn<any> = (v): ValidationResult<any> => {\n const r = prev(v);\n if (r.issues) return r;\n const sr = schemaValidate(r.value);\n if (\"then\" in sr) {\n discardAsyncValidationResult(sr);\n return fail(\"Async schemas are not supported\");\n }\n if (sr.issues) return standardSchemaFailure(sr.issues);\n return ok(sr.value);\n };\n return admitIdDomain ? thenValidate(validate, admitIdDomain) : validate;\n}\n\nfunction withTransform(\n prev: ValidatorFn<any>,\n fn: (value: any) => any\n): ValidatorFn<any> {\n return (v) => {\n const r = prev(v);\n if (r.issues) return r;\n try {\n return ok(fn((r as { value: any }).value));\n } catch (error) {\n return fail(\n `Transform failed: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n };\n}\n\n// =============================================================================\n// Schema Builder (Returns complete schema object)\n// =============================================================================\n\n/**\n * Build a complete schema object with optimized validator.\n * This is the main entry point for creating scalar schemas.\n *\n * @param type - Schema type name\n * @param baseValidate - The base type validator\n * @param options - Schema options\n * @param extras - Additional properties to add to the schema (e.g., `value` for literal)\n */\nexport function buildSchema<\n T,\n const Opts extends ScalarOptions<T, any> | undefined,\n TExtras extends Record<string, unknown> = Record<never, never>,\n>(\n type: string,\n baseValidate: ValidatorFn<T>,\n options: Opts,\n extras?: TExtras\n): VibSchema<ComputeInput<T, Opts>, ComputeOutput<T, Opts>> &\n TExtras & { type: string; options: Opts; acceptsUndefined: boolean } {\n // Pre-compute whether this schema accepts undefined\n // True if: optional, or has a default value\n const acceptsUndefined =\n options?.optional === true || options?.default !== undefined;\n\n // `createSchema` owns the Standard Schema carrier and its lazy JSON Schema\n // converter; a scalar adds only its options and wrapper metadata.\n return Object.assign(\n createSchema<ComputeInput<T, Opts>, ComputeOutput<T, Opts>>(\n type,\n buildValidator(baseValidate, options, type)\n ),\n { options, acceptsUndefined, ...extras }\n ) as VibSchema<ComputeInput<T, Opts>, ComputeOutput<T, Opts>> &\n TExtras & { options: Opts; type: string; acceptsUndefined: boolean };\n}\n\n/**\n * Create a StandardSchema-compatible schema object.\n */\nexport function createSchema<TInput, TOutput>(\n type: string,\n validate: (value: unknown) => ValidationResult<TOutput>\n): VibSchema<TInput, TOutput> {\n const schema = {\n type,\n \"~standard\": {\n version: 1 as const,\n vendor: \"viborm\" as const,\n validate,\n // Lazy jsonSchema - converter is created when first accessed\n get jsonSchema() {\n const converter = createJsonSchemaConverter(\n schema as unknown as VibSchema<unknown, unknown>\n );\n // Replace getter with static value for subsequent access\n Object.defineProperty(this, \"jsonSchema\", {\n value: converter,\n writable: false,\n enumerable: true,\n });\n return converter;\n },\n },\n };\n\n // Add the inferred property for type branding\n Object.defineProperty(schema, \" vibInferred\", {\n value: undefined,\n enumerable: false,\n });\n\n return schema as VibSchema<TInput, TOutput>;\n}\n\n/**\n * Validate a value against a StandardSchema.\n */\nexport function validateSchema<const S extends StandardSchemaV1>(\n schema: S,\n value: unknown\n): ValidationResult<StandardSchemaV1.InferOutput<S>> {\n const result = schema[\"~standard\"].validate(value);\n if (\"then\" in result) {\n discardAsyncValidationResult(result);\n return fail(\"Async schemas are not supported\");\n }\n if (result.issues) {\n return standardSchemaFailure(result.issues);\n }\n return ok((result as { value: StandardSchemaV1.InferOutput<S> }).value);\n}\n","/**\n * The exact decimal VALUE type, its accepted spelling, and the text-level\n * arithmetic the field codec needs.\n *\n * A `Decimal` is an immutable signed `BigInt` coefficient and a non-negative\n * scale, `coefficient x 10^-scale`: no NaN, no infinity, no exponent, no\n * statics and no configuration. The constructor and every result strip\n * insignificant fraction zeros and zero is `(0n, 0)`, so `toString()` IS the\n * canonical private text every identity owner keys on.\n *\n * `admitDecimal` is the one admission rule (a string through the grammar,\n * anything else through the brand). The brand is the `#c` private field only\n * the constructor installs, so `canonicalDecimalText` answers `undefined` for\n * `Object.create(Decimal.prototype)`, a look-alike object or a `Proxy`, and no\n * boundary above has to snapshot a foreign representation.\n *\n * The published TYPE is an interface and the published VALUE a const holding\n * the class: result types map every leaf through `Prettify`, a mapped type\n * drops private fields, and a class type would stop being assignable to\n * `Decimal`. The const's declared type keeps the two in step.\n */\n\n/**\n * The accepted literal grammar: optional sign, decimal digits, at most one dot,\n * at least one digit overall. Deliberately NO exponent — `1e3` is a float\n * spelling, and admitting it would mean admitting `1e400` and the rounding\n * question that comes with it. Deliberately no whitespace, no `NaN`, no\n * `Infinity`: none of them name an exact decimal.\n */\nconst DECIMAL_LITERAL_REGEX = /^[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)$/;\n\nconst LEADING_ZEROS_REGEX = /^0+/;\nconst TRAILING_ZEROS_REGEX = /0+$/;\nconst LEADING_SIGN_REGEX = /^[+-]/;\n\n/**\n * Reduce a valid decimal literal to its ONE canonical spelling: no leading `+`,\n * no insignificant leading or trailing zeros, no bare `-0`, no dangling dot.\n *\n * Canonicalization is not cosmetic. It is the private logical representation\n * every identity owner keys on — cursors, row keys, cache keys, race pins, link\n * folds — so two Decimal instances naming the same number are the same key, and\n * `\"1.10\"` and `\"1.1\"` are the same value on every dialect.\n */\nfunction canonicalizeLiteral(literal: string): string {\n const negative = literal.startsWith(\"-\");\n const unsigned = literal.replace(LEADING_SIGN_REGEX, \"\");\n const [rawInteger = \"\", rawFraction = \"\"] = unsigned.split(\".\");\n const integer = rawInteger.replace(LEADING_ZEROS_REGEX, \"\");\n const fraction = rawFraction.replace(TRAILING_ZEROS_REGEX, \"\");\n const whole = integer === \"\" ? \"0\" : integer;\n // Zero has no sign: '-0.000' and '0' are the same number, so they get the\n // same spelling — otherwise text equality would split them apart.\n if (whole === \"0\" && fraction === \"\") return \"0\";\n const sign = negative ? \"-\" : \"\";\n return fraction === \"\" ? `${sign}${whole}` : `${sign}${whole}.${fraction}`;\n}\n\n/**\n * The canonical text of a `Decimal | string`, or `undefined` when the value\n * names no exact decimal: THE admission rule.\n *\n * The constructor reads a string through it, and the field (`v.decimal()`),\n * the engine binders and the cache encoder read every value through it, so\n * what `s.decimal()` accepts and what `new Decimal()` accepts cannot drift\n * apart. A `Decimal` answers through the brand, never through its shape.\n */\nexport function admitDecimal(value: unknown): string | undefined {\n if (typeof value !== \"string\") return canonicalDecimalText(value);\n return DECIMAL_LITERAL_REGEX.test(value)\n ? canonicalizeLiteral(value)\n : undefined;\n}\n\n/**\n * The two PRIMITIVE forms of an exact decimal a caller may hand the value type:\n * a spelling, or a whole coefficient. Both name an exact decimal; a JavaScript\n * number names a double, so it is not one of them.\n */\nexport type DecimalPrimitive = string | bigint;\n\n/**\n * How a quotient resolves a value exactly between two representable ones.\n *\n * Two modes, each with a caller: `\"half-up\"` is what an application reading a\n * money column expects and what every VibORM release so far has produced;\n * `\"half-even\"` is what the SQL engines do, so a caller reconciling against a\n * server-side division can ask for the server's answer. There is no third mode\n * because there is no third caller.\n */\nexport type DecimalRounding = \"half-up\" | \"half-even\";\n\nconst TEN = 10n;\n\n/** `10^power`, the scale shift both alignment and rounding are spelled with. */\nfunction shift(power: number): bigint {\n return TEN ** BigInt(power);\n}\n\n/**\n * Round `numerator / denominator` to an integer, both taken as non-negative.\n *\n * `\"half-up\"` sends a tie away from zero, which is the sign the caller's\n * coefficient carries separately; `\"half-even\"` sends it to the even neighbour.\n */\nfunction roundQuotient(\n numerator: bigint,\n denominator: bigint,\n rounding: DecimalRounding\n): bigint {\n const quotient = numerator / denominator;\n const doubled = (numerator % denominator) * 2n;\n if (doubled > denominator) return quotient + 1n;\n if (doubled < denominator) return quotient;\n return rounding === \"half-up\" || quotient % 2n !== 0n\n ? quotient + 1n\n : quotient;\n}\n\n/** The accepted spelling, named once for both refusal sentences below. */\nconst DECIMAL_SPELLING =\n \"a string like '-12.345' (sign, digits, at most one dot, no exponent); a JavaScript number is a double and is not accepted\";\n\n/**\n * The FIELD boundary's refusal: `v.decimal()` returns it as its issue message\n * wherever `admitDecimal` answers `undefined`.\n */\nexport const DECIMAL_INPUT_REFUSAL = `Expected an exact decimal: a Decimal or ${DECIMAL_SPELLING}`;\n\n/**\n * The constructor's refusal. It names one more member than the field's,\n * because the value type also takes a whole `bigint` coefficient, and it shares\n * the grammar and the spelling clause with it.\n */\nexport const DECIMAL_CONSTRUCTOR_REFUSAL = `Expected an exact decimal: a Decimal, a bigint, or ${DECIMAL_SPELLING}`;\n\n/**\n * Write one normalized coefficient and scale as canonical text: the integer\n * digits, a point only when there are fraction digits, and a sign only on a\n * value below zero. The one canonical rendering — `toString` and the seam the\n * codec reads both come here, so no caller can be shown a second spelling;\n * `toFixed` shares its point placement.\n */\nfunction renderParts(coefficient: bigint, scale: number): string {\n const negative = coefficient < 0n;\n return placePoint(\n negative,\n (negative ? -coefficient : coefficient).toString(),\n scale\n );\n}\n\n/** Unsigned digits with the point `fractionDigits` from the right, and a sign. */\nfunction placePoint(\n negative: boolean,\n digits: string,\n fractionDigits: number\n): string {\n const sign = negative ? \"-\" : \"\";\n if (fractionDigits === 0) return `${sign}${digits}`;\n const padded = digits.padStart(fractionDigits + 1, \"0\");\n const point = padded.length - fractionDigits;\n return `${sign}${padded.slice(0, point)}.${padded.slice(point)}`;\n}\n\n/**\n * Write a coefficient and scale with exactly `fractionDigits` fraction digits,\n * rounding half away from zero: `toFixed`.\n */\nfunction renderFixed(\n coefficient: bigint,\n scale: number,\n fractionDigits: number\n): string {\n const negative = coefficient < 0n;\n const rounded = roundQuotient(\n (negative ? -coefficient : coefficient) * shift(fractionDigits),\n shift(scale),\n \"half-up\"\n ).toString();\n // A negative value keeps its sign even when every digit it rounded to is a\n // zero: `-0.004` to two places is `-0.00`, which says the value was below\n // zero and too small to show. Zero itself is never negative, so there is no\n // second rule to apply.\n return placePoint(negative, rounded, fractionDigits);\n}\n\n/**\n * Read already-canonical text straight into a coefficient and a scale.\n *\n * Canonical text carries no `+`, no insignificant zero and no bare `-0`, so\n * what comes out needs no normalization — which is what lets the codec hand\n * over a spelling it has already validated without paying for the grammar a\n * second time.\n */\nfunction partsOfCanonical(canonical: string): [bigint, number] {\n const point = canonical.indexOf(\".\");\n if (point === -1) return [BigInt(canonical), 0];\n const scale = canonical.length - point - 1;\n return [\n BigInt(canonical.slice(0, point) + canonical.slice(point + 1)),\n scale,\n ];\n}\n\n/**\n * The exact decimal VALUE.\n *\n * Immutable: every operation returns a new instance and none of them mutates\n * the receiver. Every binary operation accepts the same\n * `Decimal | DecimalPrimitive` the constructor does, so there is one admission\n * grammar for the whole type.\n *\n * This is an INTERFACE, and {@link Decimal} below is the const that holds the\n * class implementing it. They carry the same name on purpose — a caller writes\n * `Decimal` for both — and the const's declared type is what keeps them in\n * step: a method added to one side and not the other stops compiling.\n *\n * @example\n * new Decimal(\"19.99\").times(\"3\").toString(); // \"59.97\"\n * new Decimal(\"1\").div(\"3\", 5).toString(); // \"0.33333\"\n */\nexport interface Decimal {\n /** Immutable canonical text retained by deep equality and structured cloning. */\n readonly value: string;\n /** This value plus `other`, exactly. */\n plus(other: Decimal | DecimalPrimitive): Decimal;\n /** This value minus `other`, exactly. */\n minus(other: Decimal | DecimalPrimitive): Decimal;\n /** This value times `other`, exactly: coefficients multiply, scales add. */\n times(other: Decimal | DecimalPrimitive): Decimal;\n /**\n * This value divided by `other`, to `fractionDigits` fraction digits.\n *\n * A quotient is the one operation with no exact answer, so it is the one that\n * asks: how many digits, and what happens to a tie.\n *\n * @throws {RangeError} when `other` is zero.\n */\n div(\n other: Decimal | DecimalPrimitive,\n fractionDigits?: number,\n rounding?: DecimalRounding\n ): Decimal;\n /** `-1`, `0` or `1` as this value is below, equal to, or above `other`. */\n cmp(other: Decimal | DecimalPrimitive): -1 | 0 | 1;\n /** Whether this value and `other` are the same number. */\n eq(other: Decimal | DecimalPrimitive): boolean;\n /** Whether this value is below `other`. */\n lt(other: Decimal | DecimalPrimitive): boolean;\n /** Whether this value is below `other` or the same number. */\n lte(other: Decimal | DecimalPrimitive): boolean;\n /** Whether this value is above `other`. */\n gt(other: Decimal | DecimalPrimitive): boolean;\n /** Whether this value is above `other` or the same number. */\n gte(other: Decimal | DecimalPrimitive): boolean;\n /** This value without its sign. */\n abs(): Decimal;\n /** This value with its sign flipped. Zero has no sign to flip. */\n neg(): Decimal;\n /**\n * The canonical text of this value: no exponent, ever, and no insignificant\n * zero, so two instances naming the same number spell it the same way.\n */\n toString(): string;\n /**\n * This value with exactly `fractionDigits` fraction digits, rounding half\n * away from zero. With no argument it is {@link Decimal.toString}: the whole\n * value, in normal notation, rounded nowhere.\n */\n toFixed(fractionDigits?: number): string;\n /**\n * This value as a JavaScript number, which is a double: the conversion is\n * exact only for values a double can hold, and is the caller's decision.\n */\n toNumber(): number;\n /** The canonical text, so `` `${value}` `` and `+value` read the number. */\n valueOf(): string;\n /** The canonical text, so `JSON.stringify` writes the number, not `{}`. */\n toJSON(): string;\n}\n\n/**\n * The two module-private readers of a Decimal's private fields, captured from\n * inside the class body.\n *\n * Captured rather than declared `static` so the published constructor carries\n * no static property at all: `Object.getOwnPropertyNames(Decimal)` is\n * `length`, `name`, `prototype` and nothing else, which is the \"no\n * configuration, in either direction\" promise made literal.\n */\nlet owns: (value: unknown) => value is ExactDecimal;\nlet textOf: (value: ExactDecimal) => string;\n\n/**\n * The class, and the only place a `#c` is installed.\n *\n * Named for what it is rather than `Decimal`, which the interface above already\n * takes: it is not a wrapper AROUND a decimal, it IS the exact decimal, and a\n * class named `DecimalValue`/`DecimalWrapper` beside a `Decimal` is exactly the\n * second-owner shape the language census refuses.\n *\n * Module-private: what the package exports is {@link Decimal} below, whose\n * declared type carries ONE construct signature — the public grammar. The\n * two-argument form here is the internal seam a coefficient at a non-zero\n * scale arrives through; TypeScript outside this module cannot spell it, but\n * untyped JavaScript reaches it (`new Decimal(123n, 2)` is 1.23) and the\n * scale is not checked there.\n */\nclass ExactDecimal implements Decimal {\n readonly #c: bigint;\n readonly #scale: number;\n readonly value: string;\n\n constructor(value: Decimal | DecimalPrimitive, scale?: number) {\n // A `bigint` is a coefficient: a public one is a whole number (scale 0),\n // and the internal seam passes its scale. Normalized here so every result\n // in this file is normalized in one place.\n if (typeof value === \"bigint\") {\n let coefficient = value;\n let places = scale ?? 0;\n while (places > 0 && coefficient % TEN === 0n) {\n coefficient /= TEN;\n places--;\n }\n this.#c = coefficient;\n this.#scale = coefficient === 0n ? 0 : places;\n } else if (owns(value)) {\n // The BRAND, not `instanceof`: a prototype is forgeable and a private field\n // is not, so a value that only wears the prototype falls through to the\n // refusal below instead of failing on a field it does not have.\n this.#c = value.#c;\n this.#scale = value.#scale;\n } else {\n const canonical = admitDecimal(value);\n if (canonical === undefined) {\n throw new TypeError(DECIMAL_CONSTRUCTOR_REFUSAL);\n }\n const [coefficient, places] = partsOfCanonical(canonical);\n this.#c = coefficient;\n this.#scale = places;\n }\n this.value = renderParts(this.#c, this.#scale);\n Object.defineProperty(this, \"value\", {\n writable: false,\n configurable: false,\n });\n }\n\n static {\n owns = (value: unknown): value is ExactDecimal =>\n typeof value === \"object\" && value !== null && #c in value;\n textOf = (value) => renderParts(value.#c, value.#scale);\n }\n\n /** The coefficient this value would carry at `scale`, which is never less. */\n #at(scale: number): bigint {\n return this.#c * shift(scale - this.#scale);\n }\n\n plus(other: Decimal | DecimalPrimitive): Decimal {\n const addend = new ExactDecimal(other);\n const scale = Math.max(this.#scale, addend.#scale);\n return new ExactDecimal(this.#at(scale) + addend.#at(scale), scale);\n }\n\n minus(other: Decimal | DecimalPrimitive): Decimal {\n const subtrahend = new ExactDecimal(other);\n const scale = Math.max(this.#scale, subtrahend.#scale);\n return new ExactDecimal(this.#at(scale) - subtrahend.#at(scale), scale);\n }\n\n times(other: Decimal | DecimalPrimitive): Decimal {\n const factor = new ExactDecimal(other);\n return new ExactDecimal(this.#c * factor.#c, this.#scale + factor.#scale);\n }\n\n div(\n other: Decimal | DecimalPrimitive,\n fractionDigits = 20,\n rounding: DecimalRounding = \"half-up\"\n ): Decimal {\n const divisor = new ExactDecimal(other);\n if (divisor.#c === 0n) throw new RangeError(\"Division by zero\");\n const numerator = this.#c * shift(divisor.#scale + fractionDigits);\n const denominator = divisor.#c * shift(this.#scale);\n const negative = numerator < 0n !== denominator < 0n;\n const magnitude = roundQuotient(\n numerator < 0n ? -numerator : numerator,\n denominator < 0n ? -denominator : denominator,\n rounding\n );\n return new ExactDecimal(negative ? -magnitude : magnitude, fractionDigits);\n }\n\n cmp(other: Decimal | DecimalPrimitive): -1 | 0 | 1 {\n const against = new ExactDecimal(other);\n const scale = Math.max(this.#scale, against.#scale);\n const left = this.#at(scale);\n const right = against.#at(scale);\n if (left < right) return -1;\n return left > right ? 1 : 0;\n }\n\n eq(other: Decimal | DecimalPrimitive): boolean {\n return this.cmp(other) === 0;\n }\n\n lt(other: Decimal | DecimalPrimitive): boolean {\n return this.cmp(other) === -1;\n }\n\n lte(other: Decimal | DecimalPrimitive): boolean {\n return this.cmp(other) !== 1;\n }\n\n gt(other: Decimal | DecimalPrimitive): boolean {\n return this.cmp(other) === 1;\n }\n\n gte(other: Decimal | DecimalPrimitive): boolean {\n return this.cmp(other) !== -1;\n }\n\n abs(): Decimal {\n return new ExactDecimal(this.#c < 0n ? -this.#c : this.#c, this.#scale);\n }\n\n neg(): Decimal {\n return new ExactDecimal(-this.#c, this.#scale);\n }\n\n toString(): string {\n return renderParts(this.#c, this.#scale);\n }\n\n toFixed(fractionDigits?: number): string {\n return fractionDigits === undefined\n ? this.toString()\n : renderFixed(this.#c, this.#scale, fractionDigits);\n }\n\n toNumber(): number {\n return Number(this.toString());\n }\n\n valueOf(): string {\n return this.toString();\n }\n\n toJSON(): string {\n return this.toString();\n }\n\n [Symbol.for(\"nodejs.util.inspect.custom\")](): string {\n return `Decimal(\"${this.value}\")`;\n }\n}\n\n/**\n * The public constructor, carrying the one grammar a caller may spell.\n *\n * The same object as the class, so `instanceof` and `Object.create(\n * Decimal.prototype)` behave exactly as they would for a plain class\n * declaration — only the internal two-argument construction is hidden, and the\n * instance TYPE stays free of private fields so a mapped result type keeps it.\n */\nexport const Decimal: {\n /**\n * @param value a `Decimal` to copy, an exact decimal string, or a whole\n * `bigint`.\n * @throws {TypeError} for every other value, including every JavaScript\n * number, a string outside the accepted grammar, and a value of any other\n * type.\n */\n new (value: Decimal | DecimalPrimitive): Decimal;\n readonly prototype: Decimal;\n} = ExactDecimal;\n\n/**\n * Construct one Decimal from text this module's own grammar already admitted.\n *\n * The decode half of every result, cache and default boundary. The codec has\n * established the spelling before calling, so re-testing it here would make the\n * grammar two owners deep; a caller that has NOT established it uses the\n * ordinary constructor, which is the only other way in.\n */\nexport function fromCanonical(canonical: string): Decimal {\n const [coefficient, scale] = partsOfCanonical(canonical);\n return new ExactDecimal(coefficient, scale);\n}\n\n/**\n * The canonical text of a value that IS one of ours, or `undefined`.\n *\n * The whole value boundary, in one function: the private field is installed by\n * the constructor and by nothing else, so answering at all is a witness of\n * CONSTRUCTION rather than a reading of a shape — `undefined` for\n * `Object.create(Decimal.prototype)`, for a plain object carrying the same\n * keys, for a `Proxy` around a real one, and for every other value there is.\n *\n * The text is read from the fields, deliberately NOT through `value.toString()`:\n * the prototype is an object an application can write to, and a codec that\n * rendered through it would be rendering whatever the application put there.\n * The fields are reachable from inside the class body and from nowhere else, so\n * this is the only rendering no caller can move — and it shares `renderParts`\n * with the prototype method, so there is still one spelling.\n */\nexport function canonicalDecimalText(value: unknown): string | undefined {\n return owns(value) ? textOf(value) : undefined;\n}\n\n/**\n * The Decimal `coefficient x 10^-scale`: the decode seam for an unscaled\n * integer a provider stored, normalized by the constructor like every result.\n */\nexport function fromCoefficient(coefficient: bigint, scale: number): Decimal {\n return new ExactDecimal(coefficient, scale);\n}\n\n/**\n * The unscaled integer coefficient of canonical text at `scale`, which is never\n * less than the text's own: `logical x 10^scale`, exact because it is the\n * value's own `BigInt` shifted, never a JavaScript multiplication.\n */\nexport function toCoefficient(canonical: string, scale: number): string {\n const [coefficient, own] = partsOfCanonical(canonical);\n return (coefficient * shift(scale - own)).toString();\n}\n\n/**\n * Why canonical text is outside the domain `{ precision, scale }`, or\n * `undefined` when it fits: the one owner of both refusal sentences.\n *\n * Fitting is a DOMAIN question, not a spelling one: `\"1.2\"` at scale 5 fits and\n * stays `\"1.2\"`. Only digits past `scale`, or an unscaled coefficient wider\n * than `precision`, are outside, and both are refused rather than rounded.\n *\n * Read from the TEXT, in one pass and with no allocation: a declared scale may\n * be as large as `Number.MAX_SAFE_INTEGER` before a provider bounds it, and a\n * field refuses an over-long literal before any `BigInt` is built.\n */\nexport function domainRefusal(\n canonical: string,\n precision: number,\n scale: number\n): string | undefined {\n const point = canonical.indexOf(\".\");\n const fractionDigits = point === -1 ? 0 : canonical.length - point - 1;\n if (fractionDigits > scale) {\n return `Expected at most ${scale} fractional digit${scale === 1 ? \"\" : \"s\"}, but '${canonical}' has ${fractionDigits}`;\n }\n const start = canonical.startsWith(\"-\") ? 1 : 0;\n let digits: number;\n if (canonical[start] !== \"0\") {\n // Canonical text has no leading zero, so every integer digit counts.\n digits = (point === -1 ? canonical.length : point) - start + scale;\n } else {\n // A zero integer part: the coefficient starts at the first non-zero\n // fraction digit, and zero itself has none.\n let first = point + 1;\n while (canonical[first] === \"0\") first++;\n digits = point === -1 ? 0 : scale - (first - point - 1);\n }\n if (digits > precision) {\n return `Expected an unscaled coefficient of at most ${precision} digits, but '${canonical}' needs ${digits}`;\n }\n return undefined;\n}\n","/**\n * The field-aware decimal codec: the descriptor type, the two physical\n * vocabularies a column crosses through, the provider decode grammars and\n * their domain limits, the two DDL renderings, the widened-sum decode and the\n * JSON list container. The value and its arithmetic are `decimal-value.ts`'s;\n * a value whose `canonicalDecimalText` answers was built by its constructor,\n * so there is nothing here to snapshot or defend against.\n */\n\nimport { isString } from \"../value-guards\";\nimport {\n admitDecimal,\n canonicalDecimalText,\n type Decimal,\n fromCanonical,\n fromCoefficient,\n toCoefficient,\n} from \"./decimal-value\";\n\n// =============================================================================\n// THE DOMAIN\n// =============================================================================\n\n/**\n * The fixed-decimal domain: multiples of `10^-scale` whose unscaled coefficient\n * has at most `precision` digits. Frozen once by `s.decimal` and carried by\n * reference through every modifier.\n */\nexport interface DecimalDescriptor {\n readonly precision: number;\n readonly scale: number;\n}\n\n/** Whether two optional descriptor references declare the same value domain. */\nexport function sameDecimalDescriptor(\n left: DecimalDescriptor | undefined,\n right: DecimalDescriptor | undefined\n): boolean {\n if (left === undefined || right === undefined) return left === right;\n return left.precision === right.precision && left.scale === right.scale;\n}\n\n/**\n * The two exact physical vocabularies a decimal field can cross through.\n *\n * The active adapter selects one; this codec alone interprets it. The value\n * cannot select its own vocabulary because `\"120\"` is logical 120 as native\n * decimal text and logical 1.2 as a scale-2 coefficient.\n */\nexport type DecimalPhysicalRepresentation = \"text\" | \"coefficient\";\n\n/**\n * The codec's names for four value-module seams: the admission rule\n * (`admitDecimal`), the brand reader (`canonicalDecimalText`), the\n * grammar-skipping decode seam (`fromCanonical`) and the coefficient at a\n * scale (`toCoefficient`). Each is the same function, not a wrapper around it.\n * They are the names every other module reaches: the language census lets only\n * this codec and the root entry import a construction seam from the value\n * module at runtime, so `primitives/decimal.ts`, the engine's binders, result\n * parser and cache, and the migration readers build and admit through here.\n */\nexport const canonicalizeDecimal = admitDecimal;\nexport const canonicalizeMaterializedDecimal = canonicalDecimalText;\nexport const toDecimal = fromCanonical;\nexport const logicalToCoefficient = toCoefficient;\n\n// =============================================================================\n// THE COEFFICIENT VOCABULARY\n// =============================================================================\n\n/**\n * The one physical coefficient spelling: `0`, or an optional minus and digits\n * with no leading zero. `BigInt` alone would also read `\" 1 \"`, `\"0x10\"` and\n * `\"\"`, so a provider value crosses this before it becomes a number.\n */\nconst COEFFICIENT_REGEX = /^(?:0|-?[1-9]\\d*)$/;\n\n/**\n * Decode one untrusted unscaled coefficient at `scale`, or `undefined` when it\n * is outside the vocabulary or wider than `precision` digits. The length is\n * bounded before the `BigInt` is built.\n */\nfunction decodeCoefficient(\n value: unknown,\n scale: number,\n precision?: number\n): Decimal | undefined {\n if (!(isString(value) && COEFFICIENT_REGEX.test(value))) return undefined;\n const digits = value.startsWith(\"-\") ? value.length - 1 : value.length;\n if (precision !== undefined && digits > precision) return undefined;\n return fromCoefficient(BigInt(value), scale);\n}\n\n/** The canonical text of a decoded coefficient, or `undefined`. */\nfunction decodeCoefficientText(\n value: unknown,\n scale: number,\n precision?: number\n): string | undefined {\n const decoded = decodeCoefficient(value, scale, precision);\n return decoded === undefined ? undefined : canonicalDecimalText(decoded);\n}\n\n// =============================================================================\n// PROVIDER TEXT DECODE\n// =============================================================================\n\n/** Whether one UTF-16 code unit is an ASCII decimal digit. */\nfunction isDecimalDigit(code: number): boolean {\n return code >= 48 && code <= 57;\n}\n\n/**\n * Validate and locate canonical physical decimal TEXT in one scan: an optional\n * minus, an integer part with no leading zero, and a fraction padded to the\n * column's scale — the spelling an adapter emits for `NUMERIC(p,s)` /\n * `DECIMAL(p,s)`. Narrower than the application grammar on purpose: a\n * spelling no adapter emits is a malformed row, not a number to guess at.\n *\n * Returns the canonical end offset (zero for normalized zero). The scan owns\n * scale and optional precision admission, so the field and SUM decoders never\n * reinterpret the spelling afterward.\n */\nfunction scanProviderText(\n value: string,\n scale: number,\n precision?: number\n): number | undefined {\n const length = value.length;\n if (length === 0) return undefined;\n\n const negative = value.charCodeAt(0) === 45;\n const integerStart = negative ? 1 : 0;\n if (integerStart === length) return undefined;\n\n let index = integerStart;\n const first = value.charCodeAt(index);\n const integerIsZero = first === 48;\n if (integerIsZero) {\n index++;\n if (index < length && isDecimalDigit(value.charCodeAt(index))) {\n return undefined;\n }\n } else {\n if (first < 49 || first > 57) return undefined;\n index++;\n while (index < length && isDecimalDigit(value.charCodeAt(index))) index++;\n }\n const integerEnd = index;\n\n let fractionStart = length;\n let firstNonZeroFraction = -1;\n let lastNonZeroFractionEnd = -1;\n if (index < length) {\n if (value.charCodeAt(index) !== 46) return undefined;\n fractionStart = ++index;\n if (index === length) return undefined;\n for (; index < length; index++) {\n const code = value.charCodeAt(index);\n if (!isDecimalDigit(code)) return undefined;\n if (code !== 48) {\n if (firstNonZeroFraction < 0) {\n firstNonZeroFraction = index - fractionStart;\n }\n lastNonZeroFractionEnd = index + 1;\n }\n }\n }\n\n const isZero = integerIsZero && firstNonZeroFraction < 0;\n const fractionalDigits =\n lastNonZeroFractionEnd < 0 ? 0 : lastNonZeroFractionEnd - fractionStart;\n const coefficientDigits = integerIsZero\n ? firstNonZeroFraction < 0\n ? 0\n : scale - firstNonZeroFraction\n : integerEnd - integerStart + scale;\n if (\n fractionalDigits > scale ||\n (precision !== undefined && coefficientDigits > precision)\n ) {\n return undefined;\n }\n if (isZero) return 0;\n return fractionalDigits === 0 ? integerEnd : lastNonZeroFractionEnd;\n}\n\n/** Render one validated provider TEXT value as canonical private text. */\nfunction renderProviderText(text: string, end: number): string {\n if (end === 0) return \"0\";\n return end === text.length ? text : text.slice(0, end);\n}\n\n/**\n * Decode one scalar field value read back as native decimal text, or\n * `undefined` when the provider returned something outside the field's declared\n * domain or outside the physical vocabulary the adapter promised.\n *\n * The PostgreSQL/MySQL scalar-read half of the codec: a column declared\n * `NUMERIC(p,s)` cannot answer with more than `s` fractional digits or more\n * than `p` coefficient digits, so a value that does is a column the schema no\n * longer describes rather than a number to widen the field for.\n */\nexport function decodeFieldScalar(\n text: unknown,\n descriptor: DecimalDescriptor\n): string | undefined {\n if (!isString(text)) return undefined;\n const canonicalEnd = scanProviderText(\n text,\n descriptor.scale,\n descriptor.precision\n );\n return canonicalEnd === undefined\n ? undefined\n : renderProviderText(text, canonicalEnd);\n}\n\n/**\n * Decode an aggregate SUM, which keeps the field's SCALE but is deliberately\n * NOT held to its precision: adding a million `precision: 10` rows produces a\n * legitimate answer wider than any single column. `undefined` means the\n * provider returned something that is not an exact decimal at this scale.\n */\nexport function decodeWidenedSum(\n value: unknown,\n scale: number\n): string | undefined {\n if (!isString(value)) return undefined;\n const canonicalEnd = scanProviderText(value, scale);\n return canonicalEnd === undefined\n ? undefined\n : renderProviderText(value, canonicalEnd);\n}\n\n// =============================================================================\n// PROVIDER PHYSICAL REPRESENTATION\n// =============================================================================\n\nfunction encodePhysicalDecimalAtScale(\n canonical: string,\n scale: number,\n representation: DecimalPhysicalRepresentation\n): string {\n return representation === \"coefficient\"\n ? toCoefficient(canonical, scale)\n : canonical;\n}\n\n/**\n * Encode one trusted canonical logical value in the vocabulary selected by the\n * active adapter. SQL construction remains with that adapter.\n */\nexport function encodePhysicalDecimal(\n canonical: string,\n descriptor: DecimalDescriptor,\n representation: DecimalPhysicalRepresentation\n): string {\n return encodePhysicalDecimalAtScale(\n canonical,\n descriptor.scale,\n representation\n );\n}\n\n/** Construct one provider TEXT value after the shared grammar and domain scan. */\nfunction materializeProviderText(\n value: unknown,\n scale: number,\n precision?: number\n): Decimal | undefined {\n if (!isString(value)) return undefined;\n const canonicalEnd = scanProviderText(value, scale, precision);\n if (canonicalEnd === undefined) return undefined;\n return fromCanonical(renderProviderText(value, canonicalEnd));\n}\n\n/**\n * Decode one untrusted provider scalar into canonical private logical text.\n */\nexport function decodePhysicalDecimal(\n value: unknown,\n descriptor: DecimalDescriptor,\n representation: DecimalPhysicalRepresentation\n): string | undefined {\n return representation === \"text\"\n ? decodeFieldScalar(value, descriptor)\n : decodeCoefficientText(value, descriptor.scale, descriptor.precision);\n}\n\n/**\n * Decode one ordinary scalar directly into its one fresh public Decimal: a\n * native decimal spelling through `renderProviderText` and the text seam, an\n * unscaled integer through the coefficient seam. Neither builds an\n * intermediate Decimal.\n */\nexport function materializePhysicalDecimal(\n value: unknown,\n descriptor: DecimalDescriptor,\n representation: DecimalPhysicalRepresentation\n): Decimal | undefined {\n return representation === \"text\"\n ? materializeProviderText(value, descriptor.scale, descriptor.precision)\n : decodeCoefficient(value, descriptor.scale, descriptor.precision);\n}\n\n/**\n * Encode the ordered input members that the adapter will place in its native\n * array or JSON-backed coefficient container. Canonicalization stays inside\n * the codec so the caller does not need a second list pass or conversion owner.\n */\nexport function encodePhysicalDecimalListMembers(\n values: readonly unknown[],\n descriptor: DecimalDescriptor,\n representation: DecimalPhysicalRepresentation\n): string[] | undefined {\n const members = new Array<string>(values.length);\n for (const [index, value] of values.entries()) {\n const canonical = admitDecimal(value);\n if (canonical === undefined) return undefined;\n members[index] = encodePhysicalDecimalAtScale(\n canonical,\n descriptor.scale,\n representation\n );\n }\n return members;\n}\n\n/**\n * Decode one provider list into canonical private logical members. Text means\n * a native array of exact decimal strings; coefficient means one JSON text\n * container of coefficient strings.\n */\nexport function decodePhysicalDecimalList(\n value: unknown,\n descriptor: DecimalDescriptor,\n representation: DecimalPhysicalRepresentation\n): string[] | undefined {\n let members: string[];\n if (representation === \"coefficient\") {\n const decoded = decodeDecimalListContainer(\n value,\n descriptor.scale,\n descriptor.precision\n );\n if (decoded === undefined) return undefined;\n members = decoded;\n } else {\n // A supplied driver or result middleware can return a proxy rather than a\n // provider's ordinary native array. Reflection over that value is the\n // untrusted provider boundary: a revoked proxy, a hostile length getter, or\n // an indexed trap is a malformed list, never an exception that escapes the\n // result parser without its typed operation context.\n try {\n if (!Array.isArray(value)) return undefined;\n const length = value.length;\n if (!Number.isSafeInteger(length) || length < 0) return undefined;\n members = new Array<string>(length);\n for (let index = 0; index < length; index++) {\n if (!Object.hasOwn(value, index)) return undefined;\n const canonical = decodeFieldScalar(value[index], descriptor);\n if (canonical === undefined) return undefined;\n members[index] = canonical;\n }\n } catch {\n return undefined;\n }\n return members;\n }\n\n return members;\n}\n\n/**\n * Decode an exact SUM while retaining only the declared scale. The field\n * precision is deliberately not applied because sums widen.\n */\nexport function decodePhysicalWidenedSum(\n value: unknown,\n descriptor: DecimalDescriptor,\n representation: DecimalPhysicalRepresentation\n): string | undefined {\n return representation === \"text\"\n ? decodeWidenedSum(value, descriptor.scale)\n : decodeCoefficientText(value, descriptor.scale);\n}\n\n/** Decode one widened SUM directly into its one fresh public Decimal. */\nexport function materializePhysicalWidenedSum(\n value: unknown,\n descriptor: DecimalDescriptor,\n representation: DecimalPhysicalRepresentation\n): Decimal | undefined {\n return representation === \"text\"\n ? materializeProviderText(value, descriptor.scale)\n : decodeCoefficient(value, descriptor.scale);\n}\n\n// =============================================================================\n// THE TWO DDL RENDERINGS\n// =============================================================================\n\n/** The dialects that spell a fixed decimal, in `NativeType[\"db\"]` vocabulary. */\nexport type DecimalDialect = \"pg\" | \"mysql\" | \"sqlite\";\n\n// =============================================================================\n// PROVIDER PHYSICAL LIMITS\n// =============================================================================\n\n/**\n * What each provider can physically store, as one table (plan 3.1).\n *\n * PostgreSQL's `NUMERIC(p,s)` tops out at 1000 digits. MySQL's `DECIMAL(p,s)`\n * tops out at 65 digits with at most 30 after the point, and exact coefficient\n * arithmetic additionally needs `precision + scale <= 65`. SQLite's bound is not\n * a storage limit at all — it stores the unscaled coefficient in an int64 — but\n * the requirement of the one-statement multiply/divide: `precision + scale <=\n * 18` is what makes every in-range rounded result computable without\n * overflowing the intermediate, and 18 digits is also the widest literal\n * SQLite's own parser reads as an integer rather than as a REAL, which is what\n * the descriptor's range CHECK is written in.\n *\n * A descriptor is syntactically valid at model construction regardless: a\n * schema valid for PostgreSQL stays a valid model graph, and only BINDING it to\n * a provider that cannot store it fails.\n */\nconst PROVIDER_LIMITS: Record<\n DecimalDialect,\n { readonly precision: number; readonly scale: number; readonly sum?: number }\n> = {\n pg: { precision: 1000, scale: 1000 },\n mysql: { precision: 65, scale: 30, sum: 65 },\n sqlite: { precision: 18, scale: 18, sum: 18 },\n};\n\n/**\n * Why this provider cannot store this descriptor, or `undefined` when it can:\n * one sentence per failing bound, naming the descriptor, the provider and the\n * limit — the caller adds the field. Read by the schema bind boundary\n * (`provider-limits.ts`) before any provider I/O, and by the migration layer.\n */\nexport function describeProviderLimitRefusal(\n dialect: DecimalDialect,\n descriptor: DecimalDescriptor\n): string | undefined {\n const limit = PROVIDER_LIMITS[dialect];\n const { precision, scale } = descriptor;\n const named = `precision ${precision}, scale ${scale}`;\n if (precision > limit.precision) {\n return `${named} exceeds this provider's maximum precision of ${limit.precision}`;\n }\n if (scale > limit.scale) {\n return `${named} exceeds this provider's maximum scale of ${limit.scale}`;\n }\n if (limit.sum !== undefined && precision + scale > limit.sum) {\n return `${named} needs precision + scale <= ${limit.sum} on this provider, which is what makes its one-statement exact multiply and divide representable`;\n }\n return undefined;\n}\n\n/**\n * The physical column type for this descriptor.\n *\n * SQLite has no exact decimal type — `DECIMAL(10,5)` is only a NUMERIC-affinity\n * spelling whose numbers it ignores — so it stores the signed integer\n * coefficient and the migration driver adds the range check that makes the\n * declared precision real.\n *\n * No space after the comma, on every dialect: the emitted text is compared by\n * the differ, so one descriptor has one spelling.\n */\nexport function decimalColumnType(\n dialect: DecimalDialect,\n descriptor: DecimalDescriptor\n): string {\n const { precision, scale } = descriptor;\n if (dialect === \"pg\") return `NUMERIC(${precision},${scale})`;\n if (dialect === \"mysql\") return `DECIMAL(${precision},${scale})`;\n return \"INTEGER\";\n}\n\n/**\n * The DDL literal for a default. PostgreSQL and MySQL take the value padded to\n * `scale` fraction digits, because that is what MySQL reads back from\n * `information_schema`: canonical `1.2` on a scale-5 column would read back as\n * `1.20000` and the differ would see a change on every push. SQLite takes the\n * coefficient, the same integer the column stores.\n *\n * The text is padded, never rounded: PostgreSQL introspection hands back\n * catalog text the column's scale never touched (`DEFAULT 1.005` on\n * `NUMERIC(10,2)` stays `1.005`), and the differ compares what the DDL\n * declared. A scale-0 column keeps the integer part.\n */\nexport function decimalDefaultText(\n dialect: DecimalDialect,\n canonical: string,\n descriptor: DecimalDescriptor\n): string {\n const { scale } = descriptor;\n if (dialect === \"sqlite\") return toCoefficient(canonical, scale);\n const point = canonical.indexOf(\".\");\n if (scale === 0) return point === -1 ? canonical : canonical.slice(0, point);\n if (point === -1) return `${canonical}.${\"0\".repeat(scale)}`;\n return canonical.padEnd(point + 1 + scale, \"0\");\n}\n\n/**\n * The physical value of one trusted literal decimal-list default.\n *\n * PostgreSQL owns a native numeric array, so every logical member is padded to\n * the declared scale just like a scalar DDL default. MySQL and the SQLite\n * family own coefficient-string JSON containers, exactly like their runtime\n * list writes. This codec renders the VALUE only; migration drivers still own\n * string quoting and provider expression syntax.\n */\nexport function decimalListDefaultText(\n dialect: DecimalDialect,\n canonicals: readonly string[],\n descriptor: DecimalDescriptor\n): string {\n if (dialect !== \"pg\") {\n return encodeDecimalListContainer(canonicals, descriptor.scale);\n }\n const members = new Array<string>(canonicals.length);\n for (const [index, canonical] of canonicals.entries()) {\n members[index] = decimalDefaultText(\"pg\", canonical, descriptor);\n }\n return `{${members.join(\",\")}}`;\n}\n\n// =============================================================================\n// THE JSON LIST CONTAINER\n// =============================================================================\n\n/**\n * The physical container for a decimal list on the JSON-backed providers:\n * a JSON array of unscaled coefficient STRINGS.\n *\n * Strings, never JSON numeric tokens — JavaScript and D1 both round integers\n * above 2^53, so a numeric token is a silently wrong member rather than a\n * bigger one.\n */\nexport function encodeDecimalListContainer(\n canonicals: readonly string[],\n scale: number\n): string {\n const members = new Array<string>(canonicals.length);\n for (const [index, canonical] of canonicals.entries()) {\n members[index] = encodePhysicalDecimalAtScale(\n canonical,\n scale,\n \"coefficient\"\n );\n }\n return JSON.stringify(members);\n}\n\n/**\n * The canonical logical members of a physical list container, or `undefined`\n * when the container is not one this codec wrote: malformed JSON, a non-array\n * top level, a numeric token, `null`, or a member outside the coefficient\n * grammar. Order and multiplicity are preserved exactly.\n */\nexport function decodeDecimalListContainer(\n container: unknown,\n scale: number,\n precision?: number\n): string[] | undefined {\n if (!isString(container)) return undefined;\n let parsed: unknown;\n try {\n parsed = JSON.parse(container);\n } catch {\n return undefined;\n }\n if (!Array.isArray(parsed)) return undefined;\n const members = new Array<string>(parsed.length);\n for (const [index, member] of parsed.entries()) {\n const canonical = decodeCoefficientText(member, scale, precision);\n if (canonical === undefined) return undefined;\n members[index] = canonical;\n }\n return members;\n}\n\n/** Domain diagnostics and catalog admission share the value descriptor owner. */\nexport function describeDecimalDomain(descriptor: DecimalDescriptor): string {\n return `precision ${descriptor.precision}, scale ${descriptor.scale}`;\n}\n\nconst STORED_DECIMAL_INTEGER = /^-?\\d+$/;\nexport function readStoredDecimalDescriptor(\n precisionValue: unknown,\n scaleValue: unknown,\n dialect: DecimalDialect\n): DecimalDescriptor | undefined {\n const precision = readStoredDecimalInteger(precisionValue);\n const scale = readStoredDecimalInteger(scaleValue);\n if (\n precision === undefined ||\n scale === undefined ||\n precision <= 0 ||\n scale < 0 ||\n scale > precision\n ) {\n return undefined;\n }\n const descriptor = { precision, scale };\n return describeProviderLimitRefusal(dialect, descriptor) === undefined\n ? descriptor\n : undefined;\n}\n\nfunction readStoredDecimalInteger(value: unknown): number | undefined {\n if (typeof value === \"number\") {\n return Number.isSafeInteger(value) ? value : undefined;\n }\n if (typeof value !== \"string\" || !STORED_DECIMAL_INTEGER.test(value)) {\n return undefined;\n }\n const parsed = Number(value);\n return Number.isSafeInteger(parsed) ? parsed : undefined;\n}\n","import { createJsonSchemaConverter } from \"../json-schema/factory\";\nimport type {\n InferInputShape,\n InferOutputShape,\n ThunkCast,\n ValidationIssue,\n ValidationResult,\n VibSchema,\n} from \"../types\";\nimport { isFunction, isRecord } from \"../value-guards\";\nimport {\n collectingAllIssues,\n fail,\n issuesUnder,\n OK_NULL,\n OK_UNDEFINED,\n ok,\n validateArray,\n} from \"./helpers\";\n\n// =============================================================================\n// Object Schema Types\n// =============================================================================\n\n/**\n * Object entries - a record of field names to schemas or thunks.\n */\nexport type ObjectEntries = Record<\n string,\n VibSchema<any, any> | ThunkCast<any, any>\n>;\n\n/**\n * Options for object schemas.\n */\nexport interface ObjectOptions<T = unknown, TKeys extends string = string> {\n /** Make all fields optional (default: true) */\n partial?: boolean;\n /** Reject unknown keys (default: true) */\n strict?: boolean;\n /** Make the object itself optional (undefined allowed) */\n optional?: boolean;\n /** Make the object itself nullable (null allowed) */\n nullable?: boolean;\n /** Validate as array of objects */\n array?: boolean;\n /** Default value when undefined/null */\n default?: T | (() => T);\n /** Transform output */\n transform?: (value: T) => T;\n /** Object name for circular references in json schema*/\n name?: string;\n /** Object description for json schema*/\n description?: string;\n /** Require at least these specific keys (works with partial: true) */\n atLeast?: TKeys[];\n /** Require at least one key from each group to be present */\n requiresOneOf?: readonly (readonly TKeys[])[];\n /** Require one key set from each group; all keys in the chosen set must be present */\n requiresOneOfKeySets?: readonly (readonly (readonly TKeys[])[])[];\n /** Omit these keys entirely from the type and validation */\n omit?: TKeys[];\n /** Require at least one key to be present (object cannot be empty) */\n nonEmpty?: boolean;\n /**\n * The WHOLE-OBJECT refusal this object owns, with its own sentence.\n *\n * `atLeast`, `requiresOneOf` and `nonEmpty` each answer one shape of \"which\n * keys must be here\", and each answers it with the primitive's own generic\n * message. A completeness rule that reads more than key presence — \"this\n * filter states no OPERATION\" (`path`/`mode` are modifiers, not operations),\n * \"this `mode` governs nothing here\", \"this `by` names the same column\n * twice\" — has no key-level spelling, and the ones that do still have a\n * REGISTERED sentence the generic message cannot spell.\n *\n * So one hook: it runs after every member validated, over the validated\n * output (a key spelled `undefined` is already absent there, which is the\n * `{ f: undefined }` ≡ `{}` rule the whole surface follows), and returns the\n * refusal sentence, an issue carrying the path of the key that is wrong, or\n * `undefined`. It is deliberately NOT part of the\n * inferred input type: these are runtime completeness facts about a\n * recursive filter surface, and distributing them into the type would turn\n * every filter object into a union of one variant per operator.\n */\n refuse?: (\n value: Record<string, unknown>\n ) => string | ValidationIssue | undefined;\n}\n\n/**\n * The options the validator reads besides the public ones. `provides` is the\n * name this object's fields are provided under: inside {@link parseProviding},\n * a required field the caller's context provides under it may be absent (the\n * required-field check and the `requiresOneOfKeySets` check count it as\n * given); outside, it changes nothing. A model's create schemas pass it with\n * their other options; it is not public, so it shapes no input type.\n */\ninterface ValidatorOptions extends ObjectOptions {\n provides?: string;\n}\n\n/** Which fields, of the object a `provides` name names, the caller's context provides. */\ntype ProvidedFields = (name: string, field: string) => boolean;\n\n/**\n * The provided fields of the parse in progress. Set by\n * {@link parseProviding} for one synchronous parse and restored, to the\n * enclosing parse's value or to `undefined`, in its `finally`: no field is\n * provided outside it, after it throws, or to another call.\n */\nlet provided: ProvidedFields | undefined;\n\n/** Does the parse in progress provide `field` of the object named `name`? */\nconst isProvided = (name: string | undefined, field: string): boolean =>\n name !== undefined && provided?.(name, field) === true;\n\n/**\n * Run `parse` where `fields` are provided by the caller's context: an object\n * whose `provides` name they list takes such a required field as absent, not\n * missing, so the caller may leave it out (someone else writes it after the\n * parse). `parse` must be synchronous: the context lives until it returns or\n * throws and is then restored, so a nested call sees its own fields and its\n * caller's come back after it.\n */\nexport function parseProviding<T>(fields: ProvidedFields, parse: () => T): T {\n const outer = provided;\n provided = fields;\n try {\n return parse();\n } finally {\n provided = outer;\n }\n}\n\n/**\n * Omit specific keys from a type entirely.\n * Preserves optionality of remaining keys.\n */\ntype VOmit<T, K extends string> = {\n [P in keyof T as P extends K ? never : P]: T[P];\n};\n\ntype OmittedKeyUnion<TKeys> = TKeys extends readonly PropertyKey[]\n ? Extract<TKeys[number], string>\n : never;\n\ntype KeepRequirementGroup<\n Group,\n OmittedKeys extends string,\n> = Group extends readonly string[]\n ? [Extract<Group[number], OmittedKeys>] extends [never]\n ? Group\n : never\n : never;\n\ntype KeepRequirementKeySetGroup<\n Group,\n OmittedKeys extends string,\n> = Group extends readonly (readonly string[])[]\n ? [Extract<Group[number][number], OmittedKeys>] extends [never]\n ? Group\n : never\n : never;\n\ntype ActiveRequirementGroups<\n Groups,\n OmittedKeys extends string,\n> = Groups extends readonly [\n infer Group extends readonly string[],\n ...infer Rest extends readonly (readonly string[])[],\n]\n ? KeepRequirementGroup<Group, OmittedKeys> extends never\n ? ActiveRequirementGroups<Rest, OmittedKeys>\n : readonly [\n KeepRequirementGroup<Group, OmittedKeys>,\n ...ActiveRequirementGroups<Rest, OmittedKeys>,\n ]\n : Groups extends readonly (infer Group extends readonly string[])[]\n ? readonly Exclude<KeepRequirementGroup<Group, OmittedKeys>, never>[]\n : readonly [];\n\ntype ActiveRequirementKeySetGroups<\n Groups,\n OmittedKeys extends string,\n> = Groups extends readonly [\n infer Group extends readonly (readonly string[])[],\n ...infer Rest extends readonly (readonly (readonly string[])[])[],\n]\n ? KeepRequirementKeySetGroup<Group, OmittedKeys> extends never\n ? ActiveRequirementKeySetGroups<Rest, OmittedKeys>\n : readonly [\n KeepRequirementKeySetGroup<Group, OmittedKeys>,\n ...ActiveRequirementKeySetGroups<Rest, OmittedKeys>,\n ]\n : Groups extends readonly (infer Group extends\n readonly (readonly string[])[])[]\n ? readonly Exclude<KeepRequirementKeySetGroup<Group, OmittedKeys>, never>[]\n : readonly [];\n\ntype ActiveOmitRequirements<TOpts, OmittedKeys extends string> = Omit<\n TOpts,\n \"requiresOneOf\" | \"requiresOneOfKeySets\"\n> &\n (TOpts extends {\n requiresOneOf: infer Groups extends readonly (readonly string[])[];\n }\n ? {\n requiresOneOf: ActiveRequirementGroups<Groups, OmittedKeys>;\n }\n : unknown) &\n (TOpts extends {\n requiresOneOfKeySets: infer Groups extends\n readonly (readonly (readonly string[])[])[];\n }\n ? {\n requiresOneOfKeySets: ActiveRequirementKeySetGroups<\n Groups,\n OmittedKeys\n >;\n }\n : unknown);\n\n/**\n * Compute input type based on partial option.\n * Default is partial: true, so only non-partial when explicitly { partial: false }\n * If atLeast is specified, those keys are required even when partial: true\n * If omit is specified, those keys are removed from the type entirely\n */\ntype ComputeObjectInput<TEntries, TOpts> = TOpts extends {\n omit: infer OmitKeys extends readonly string[];\n}\n ? TOpts extends { partial: false }\n ? ApplyRequiresOneOf<\n VOmit<InferInputShape<TEntries>, OmitKeys[number]>,\n ActiveOmitRequirements<TOpts, OmitKeys[number]>\n >\n : TOpts extends { atLeast: infer Keys extends readonly string[] }\n ? ApplyRequiresOneOf<\n VOmit<\n RequireKeys<Partial<InferInputShape<TEntries>>, Keys[number]>,\n OmitKeys[number]\n >,\n ActiveOmitRequirements<TOpts, OmitKeys[number]>\n >\n : ApplyRequiresOneOf<\n VOmit<Partial<InferInputShape<TEntries>>, OmitKeys[number]>,\n ActiveOmitRequirements<TOpts, OmitKeys[number]>\n >\n : TOpts extends { partial: false }\n ? ApplyRequiresOneOf<InferInputShape<TEntries>, TOpts>\n : TOpts extends { atLeast: infer Keys extends readonly string[] }\n ? ApplyRequiresOneOf<\n RequireKeys<Partial<InferInputShape<TEntries>>, Keys[number]>,\n TOpts\n >\n : ApplyRequiresOneOf<Partial<InferInputShape<TEntries>>, TOpts>;\n\n/**\n * Compute output type based on entries.\n * Unlike input, output doesn't use Partial - each field's schema determines\n * whether its output includes undefined (based on whether it has a default).\n */\ntype ComputeObjectOutput<TEntries, _TOpts> = InferOutputShape<TEntries>;\n\n/**\n * Make specific keys required in an otherwise partial object.\n * Uses a mapped type instead of Omit & Required<Pick> to reduce type depth.\n */\ntype RequireKeys<T, K extends string> = {\n [P in keyof T as P extends K ? never : P]?: T[P];\n} & {\n [P in keyof T as P extends K ? P : never]-?: T[P];\n};\n\ntype RequireOneKey<T, K extends PropertyKey> = T extends unknown\n ? K extends keyof T\n ? RequireKeys<T, Extract<K, string>>\n : never\n : never;\n\ntype ApplyRequiresOneOf<T, TOpts> = TOpts extends {\n requiresOneOf: infer Groups extends readonly (readonly string[])[];\n}\n ? ApplyRequiresOneOfKeySets<ApplyRequiresOneOfGroups<T, Groups>, TOpts>\n : ApplyRequiresOneOfKeySets<T, TOpts>;\n\ntype ApplyRequiresOneOfGroups<T, Groups> = Groups extends readonly [\n infer Group extends readonly string[],\n ...infer Rest extends readonly (readonly string[])[],\n]\n ? ApplyRequiresOneOfGroups<RequireOneKey<T, Group[number]>, Rest>\n : Groups extends readonly (infer Group extends readonly string[])[]\n ? [Group[number]] extends [never]\n ? T\n : RequireOneKey<T, Group[number]>\n : T;\n\ntype ApplyRequiresOneOfKeySets<TCurrent, TOpts> = TOpts extends {\n requiresOneOfKeySets: infer Groups extends\n readonly (readonly (readonly string[])[])[];\n}\n ? ApplyRequiresOneOfKeySetGroups<TCurrent, Groups>\n : TCurrent;\n\ntype RequireKeySet<T, K extends PropertyKey> = T extends unknown\n ? RequireKeys<T, Extract<K, string>>\n : never;\n\ntype RequireOneKeySet<T, Alternatives> = [Alternatives] extends [never]\n ? T\n : Alternatives extends readonly []\n ? never\n : Alternatives extends readonly [\n infer KeySet extends readonly string[],\n ...infer Rest extends readonly (readonly string[])[],\n ]\n ? RequireKeySet<T, KeySet[number]> | RequireOneKeySet<T, Rest>\n : Alternatives extends readonly (infer KeySet extends readonly string[])[]\n ? [KeySet[number]] extends [never]\n ? T\n : RequireKeySet<T, KeySet[number]>\n : T;\n\ntype UnionToIntersection<T> = (\n T extends unknown\n ? (value: T) => void\n : never\n) extends (value: infer I) => void\n ? I\n : never;\n\ntype RequireEveryKeySetGroup<T, Group> =\n UnionToIntersection<\n Group extends unknown ? { value: RequireOneKeySet<T, Group> } : never\n > extends { value: infer I }\n ? I & T\n : T;\n\ntype ApplyRequiresOneOfKeySetGroups<T, Groups> = Groups extends readonly [\n infer Group extends readonly (readonly string[])[],\n ...infer Rest extends readonly (readonly (readonly string[])[])[],\n]\n ? ApplyRequiresOneOfKeySetGroups<RequireOneKeySet<T, Group>, Rest>\n : Groups extends readonly (infer Group extends\n readonly (readonly string[])[])[]\n ? [Group] extends [never]\n ? T\n : RequireEveryKeySetGroup<T, Group>\n : T;\n\n/**\n * Apply wrapper options (optional, nullable, array) to input type.\n * Input accepts undefined when optional (even with default).\n */\ntype ApplyObjectOptionsInput<TBase, TOpts> = TOpts extends { array: true }\n ? TOpts extends { optional: true }\n ? TOpts extends { nullable: true }\n ? TBase[] | undefined | null\n : TBase[] | undefined\n : TOpts extends { nullable: true }\n ? TBase[] | null\n : TBase[]\n : TOpts extends { optional: true }\n ? TOpts extends { nullable: true }\n ? TBase | undefined | null\n : TBase | undefined\n : TOpts extends { nullable: true }\n ? TBase | null\n : TBase;\n\n/**\n * Apply wrapper options (optional, nullable, array) to output type.\n * When a default is provided, undefined is not included in output\n * (the default will always be applied).\n */\ntype ApplyObjectOptionsOutput<TBase, TOpts> = TOpts extends { array: true }\n ? TOpts extends { optional: true }\n ? TOpts extends { default: any }\n ? TOpts extends { nullable: true }\n ? TBase[] | null\n : TBase[]\n : TOpts extends { nullable: true }\n ? TBase[] | undefined | null\n : TBase[] | undefined\n : TOpts extends { nullable: true }\n ? TBase[] | null\n : TBase[]\n : TOpts extends { optional: true }\n ? TOpts extends { default: any }\n ? TOpts extends { nullable: true }\n ? TBase | null\n : TBase\n : TOpts extends { nullable: true }\n ? TBase | undefined | null\n : TBase | undefined\n : TOpts extends { nullable: true }\n ? TBase | null\n : TBase;\n\n/**\n * Object schema interface.\n */\nexport interface ObjectSchema<\n TEntries,\n TOpts extends ObjectOptions | undefined = undefined,\n TInput = ApplyObjectOptionsInput<ComputeObjectInput<TEntries, TOpts>, TOpts>,\n TOutput = ApplyObjectOptionsOutput<\n ComputeObjectOutput<TEntries, TOpts>,\n TOpts\n >,\n> extends VibSchema<TInput, TOutput> {\n readonly type: \"object\";\n readonly entries: TEntries;\n readonly options: TOpts;\n readonly parse: VibSchema<TInput, TOutput>[\"~standard\"][\"validate\"];\n /** Extend this schema with additional entries */\n extend<\n TNewEntries extends ObjectEntries,\n TNewTOpts extends ObjectOptions | undefined = undefined,\n >(\n newEntries: TNewEntries,\n options?: TNewTOpts\n ): ObjectSchema<TEntries & TNewEntries, TOpts & TNewTOpts>;\n}\n\n/** An object schema whose parser omits keys from both its input and output. */\nexport type OmittedObjectSchema<\n TEntries,\n TOpts extends ObjectOptions | undefined,\n TKeys extends readonly PropertyKey[] | undefined,\n> = ObjectSchema<\n TEntries,\n TOpts,\n ApplyObjectOptionsInput<ComputeObjectInput<TEntries, TOpts>, TOpts>,\n ApplyObjectOptionsOutput<\n VOmit<InferOutputShape<TEntries>, OmittedKeyUnion<TKeys>>,\n TOpts\n >\n>;\n\n// =============================================================================\n// Object Schema Implementation\n// =============================================================================\n\n// Pre-computed error for fast path (frozen — shared across all callers)\nconst OBJECT_TYPE_ERROR = Object.freeze({\n issues: Object.freeze([Object.freeze({ message: \"Expected object\" })]),\n});\n\nconst EMPTY_METADATA_ARRAY: readonly never[] = Object.freeze([]);\nconst EMPTY_KEY_INDEX: ReadonlyMap<string, number> = Object.freeze(new Map());\nconst INPUT_VALUE_UNREAD = Symbol(\"inputValueUnread\");\n\nfunction readObjectInputValue(\n input: Record<string, unknown>,\n key: string,\n inputValueScratch: unknown[] | undefined,\n inputValueScratchIndexByName: ReadonlyMap<string, number> | undefined\n): unknown {\n if (\n inputValueScratch === undefined ||\n inputValueScratchIndexByName === undefined\n ) {\n return input[key];\n }\n const scratchIndex = inputValueScratchIndexByName.get(key);\n if (scratchIndex === undefined) return input[key];\n const settledInputValue = inputValueScratch[scratchIndex];\n if (settledInputValue !== INPUT_VALUE_UNREAD) return settledInputValue;\n const inputValue = input[key];\n inputValueScratch[scratchIndex] = inputValue;\n return inputValue;\n}\n\n/**\n * Create an optimized validator for an object schema.\n * Minimal overhead, Valibot-style simplicity.\n */\nfunction createObjectValidator(\n entries: ObjectEntries,\n options: ValidatorOptions = {}\n): (value: unknown) => ValidationResult<Record<string, unknown>> {\n const {\n partial = true,\n strict = true,\n atLeast,\n requiresOneOf,\n requiresOneOfKeySets,\n omit,\n nonEmpty,\n refuse,\n provides,\n } = options;\n let keys: readonly string[] = EMPTY_METADATA_ARRAY;\n let keyIndex = EMPTY_KEY_INDEX;\n let validates: readonly ((value: unknown) => any)[] = EMPTY_METADATA_ARRAY;\n let activeRequiresOneOf: ObjectOptions[\"requiresOneOf\"];\n let activeRequiresOneOfKeySets: ObjectOptions[\"requiresOneOfKeySets\"];\n let runOnMissingIdx: readonly number[] = EMPTY_METADATA_ARRAY;\n let acceptsUndefined: readonly boolean[] = EMPTY_METADATA_ARRAY;\n let requiredByAtLeast: readonly boolean[] | null = null;\n let inputValueScratchTemplate: readonly unknown[] | undefined;\n let inputValueScratchIndexByName: ReadonlyMap<string, number> | undefined;\n\n // Compile only when a record first reaches this validator. Registry schemas\n // that are never used retain their public entries, but no lookup structures.\n let resolve: (() => void) | undefined;\n resolve = () => {\n // Release this resolver before resolving thunks. The state arrays are\n // published below, so a circular thunk observes initialized storage.\n resolve = undefined;\n\n const omitSet = omit ? new Set(omit) : null;\n const resolvedKeys = Object.keys(entries).filter(\n (key) => !omitSet?.has(key)\n );\n const atLeastSet = atLeast ? new Set(atLeast) : null;\n const resolvedKeyIndex = new Map<string, number>();\n const resolvedValidates: ((value: unknown) => any)[] = new Array(\n resolvedKeys.length\n );\n const resolvedIsFullyPartial = partial && !atLeastSet;\n const resolvedActiveRequiresOneOf = requiresOneOf?.filter(\n (group) => !group.some((key) => omitSet?.has(key))\n );\n const resolvedActiveRequiresOneOfKeySets = requiresOneOfKeySets?.filter(\n (group) =>\n !group.some((keySet) => keySet.some((key) => omitSet?.has(key)))\n );\n let mutableRunOnMissingIdx: number[] | undefined;\n let mutableAcceptsUndefined: boolean[] | undefined;\n\n keys = resolvedKeys;\n keyIndex = resolvedKeyIndex;\n validates = resolvedValidates;\n activeRequiresOneOf = resolvedActiveRequiresOneOf;\n activeRequiresOneOfKeySets = resolvedActiveRequiresOneOfKeySets;\n\n if (resolvedIsFullyPartial) {\n mutableRunOnMissingIdx = [];\n runOnMissingIdx = mutableRunOnMissingIdx;\n acceptsUndefined = EMPTY_METADATA_ARRAY;\n requiredByAtLeast = null;\n } else {\n mutableAcceptsUndefined = new Array(resolvedKeys.length);\n runOnMissingIdx = EMPTY_METADATA_ARRAY;\n acceptsUndefined = mutableAcceptsUndefined;\n // Sparse atLeast schemas cache required flags. Fully-required schemas\n // derive the answer from partial=false without retaining another array.\n requiredByAtLeast =\n partial && atLeastSet\n ? resolvedKeys.map((key) => atLeastSet.has(key))\n : null;\n }\n\n // Publish the arrays before resolving thunks to preserve circular references.\n for (let i = 0; i < resolvedKeys.length; i++) {\n const key = resolvedKeys[i]!;\n resolvedKeyIndex.set(key, i);\n const entry = entries[key]!;\n const schema = isFunction(entry)\n ? (entry as () => VibSchema<any, any>)()\n : entry;\n\n resolvedValidates[i] = schema[\"~standard\"].validate;\n const doesAcceptUndefined =\n (schema as { acceptsUndefined?: boolean }).acceptsUndefined === true;\n\n if (mutableRunOnMissingIdx) {\n if (doesAcceptUndefined) mutableRunOnMissingIdx.push(i);\n } else if (mutableAcceptsUndefined) {\n mutableAcceptsUndefined[i] = doesAcceptUndefined;\n }\n }\n\n const resolvedInputValueScratchIndexByName = new Map<string, number>();\n const registerInputValueScratchIndex = (key: string): void => {\n if (resolvedInputValueScratchIndexByName.has(key)) return;\n resolvedInputValueScratchIndexByName.set(\n key,\n resolvedInputValueScratchIndexByName.size\n );\n };\n for (const group of resolvedActiveRequiresOneOf ?? EMPTY_METADATA_ARRAY) {\n for (const key of group) registerInputValueScratchIndex(key);\n }\n for (const group of resolvedActiveRequiresOneOfKeySets ??\n EMPTY_METADATA_ARRAY) {\n for (const keySet of group) {\n for (const key of keySet) registerInputValueScratchIndex(key);\n }\n }\n for (const i of runOnMissingIdx) {\n registerInputValueScratchIndex(resolvedKeys[i]!);\n }\n if (resolvedInputValueScratchIndexByName.size > 0) {\n inputValueScratchTemplate = Array.from(\n { length: resolvedInputValueScratchIndexByName.size },\n () => INPUT_VALUE_UNREAD\n );\n inputValueScratchIndexByName = resolvedInputValueScratchIndexByName;\n }\n };\n\n type Result = ValidationResult<Record<string, unknown>>;\n\n // `nonEmpty` and the one-of requirements, apart: most objects declare none,\n // and a validator whose shape has none never compiles them.\n const checkRequirements =\n nonEmpty === true || requiresOneOf || requiresOneOfKeySets\n ? (\n input: Record<string, unknown>,\n inputValueScratch: unknown[] | undefined\n ): ValidationIssue[] | undefined => {\n if (nonEmpty === true) {\n // Check if object has any keys at all (including unknown keys when strict: false)\n let hasAnyKey = false;\n for (const _key in input) {\n hasAnyKey = true;\n break;\n }\n if (!hasAnyKey) return [{ message: \"Object cannot be empty\" }];\n }\n\n if (activeRequiresOneOf) {\n for (const group of activeRequiresOneOf) {\n const hasOne = group.some(\n (key) =>\n readObjectInputValue(\n input,\n key,\n inputValueScratch,\n inputValueScratchIndexByName\n ) !== undefined\n );\n if (!hasOne) {\n return [\n {\n message: `Missing required field: one of ${group.join(\", \")}`,\n },\n ];\n }\n }\n }\n\n if (activeRequiresOneOfKeySets) {\n for (const group of activeRequiresOneOfKeySets) {\n const hasAlternative = group.some((keySet) =>\n keySet.every(\n (key) =>\n readObjectInputValue(\n input,\n key,\n inputValueScratch,\n inputValueScratchIndexByName\n ) !== undefined || isProvided(provides, key)\n )\n );\n if (!hasAlternative) {\n const alternatives = group\n .map((keySet) => keySet.join(\", \"))\n .join(\" or \");\n return [\n {\n message: `Missing required fields: one of ${alternatives}`,\n },\n ];\n }\n }\n }\n return undefined;\n }\n : undefined;\n\n /**\n * Both parsers' prologue — strict keys, then requirements: the first issue,\n * or every one when collecting.\n */\n const precheck = (\n input: Record<string, unknown>,\n inputValueScratch: unknown[] | undefined\n ): ValidationIssue[] | undefined => {\n const issues = strict ? unknownKeyIssues(input, keyIndex) : undefined;\n if (issues && !collectingAllIssues()) return issues;\n const unmet = checkRequirements?.(input, inputValueScratch);\n return unmet ? gathered(issues, unmet) : issues;\n };\n\n // Fast path for fully-partial objects (where/select/orderBy args):\n // iterate input keys instead of all schema keys, and don't materialize\n // undefined entries for absent keys — output stays input-sized.\n const parsePartial = (value: unknown): Result => {\n if (!isRecord(value)) {\n return OBJECT_TYPE_ERROR as Result;\n }\n const input = value as Record<string, unknown>;\n if (resolve) resolve();\n const inputValueScratch = inputValueScratchTemplate?.slice();\n let issues = precheck(input, inputValueScratch);\n if (issues && !collectingAllIssues()) return { issues };\n const output: Record<string, unknown> = {};\n for (const key in input) {\n const i = keyIndex.get(key);\n if (i === undefined) {\n // unknown key with strict: false — dropped, as before\n continue;\n }\n\n // Explicit undefined is treated as absent (Prisma parity): it is\n // neither validated nor materialized. Downstream consumers use key\n // presence (\"where\" in config, hasRecordKeys) as meaningful, so\n // { f: undefined } must behave exactly like {}. Defaults for such\n // keys still fire via the absent-keys loop below.\n const inputValue = readObjectInputValue(\n input,\n key,\n inputValueScratch,\n inputValueScratchIndexByName\n );\n if (inputValue === undefined) {\n continue;\n }\n\n const result = validates[i]!(inputValue);\n if (result.issues) {\n issues = gathered(issues, issuesUnder(key, result.issues));\n if (!collectingAllIssues()) return { issues };\n continue;\n }\n if (result.value !== undefined) {\n output[key] = result.value;\n }\n }\n\n // Keys that are absent (or explicitly undefined) only matter when their\n // schema can apply a default\n for (const i of runOnMissingIdx) {\n const key = keys[i]!;\n if (\n readObjectInputValue(\n input,\n key,\n inputValueScratch,\n inputValueScratchIndexByName\n ) !== undefined\n ) {\n continue;\n }\n const result = validates[i]!(undefined);\n if (result.issues) {\n issues = gathered(issues, issuesUnder(key, result.issues));\n if (!collectingAllIssues()) return { issues };\n continue;\n }\n if (result.value !== undefined) {\n output[key] = result.value;\n }\n }\n\n if (issues) return { issues };\n const refusal = refuse?.(output);\n if (!refusal) return { value: output };\n return {\n issues: [typeof refusal === \"string\" ? { message: refusal } : refusal],\n };\n };\n\n // Slow path (partial: false or atLeast): output is intentionally DENSE —\n // every schema key is materialized, including undefined. Create/update\n // data schemas rely on this to surface defaults; required keys are always\n // present in valid input anyway, so sparse vs dense doesn't diverge there.\n const parseDense = (value: unknown): Result => {\n if (!isRecord(value)) {\n return OBJECT_TYPE_ERROR as Result;\n }\n const input = value as Record<string, unknown>;\n if (resolve) resolve();\n const inputValueScratch = inputValueScratchTemplate?.slice();\n let issues = precheck(input, inputValueScratch);\n if (issues && !collectingAllIssues()) return { issues };\n const output: Record<string, unknown> = {};\n // Validate each field - direct array access, no object property lookup\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]!;\n\n // Handle an ABSENT key — which, per Prisma parity, includes a key that is\n // present with an explicit `undefined`. This is the same rule the\n // fully-partial fast path above applies, the same rule `requiresOneOf`\n // already applies here (`input[key] !== undefined`), and the same rule the\n // whole client surface is documented to follow: `{ f: undefined }` must\n // behave exactly like `{}`, so the spread-an-optional idiom\n // (`{ ...(sel && { select: sel }) }` collapsed to `{ select: sel }`) works.\n // Testing `key in input` instead made an optional key spelled `undefined`\n // validate `undefined` against a schema that does not accept it —\n // `createMany({ data, select: undefined })` failed with \"Expected object\"\n // while the identical `deleteMany` call (fully partial, fast path)\n // returned `{ count }`.\n const inputValue = readObjectInputValue(\n input,\n key,\n inputValueScratch,\n inputValueScratchIndexByName\n );\n if (inputValue === undefined) {\n // Key is required (partial: false OR in atLeast) and schema doesn't accept undefined\n if (\n (!partial || requiredByAtLeast?.[i] === true) &&\n !acceptsUndefined[i] &&\n !isProvided(provides, key)\n ) {\n issues = gathered(issues, [\n { message: `Missing required field: ${key}`, path: [key] },\n ]);\n if (!collectingAllIssues()) return { issues };\n continue;\n }\n\n // If schema accepts undefined, run validator to apply defaults\n if (acceptsUndefined[i]) {\n const result = validates[i]!(undefined);\n if (result.issues) {\n issues = gathered(issues, issuesUnder(key, result.issues));\n if (!collectingAllIssues()) return { issues };\n continue;\n }\n output[key] = result.value;\n } else {\n // Scalar is optional (partial: true, not in atLeast) but schema doesn't have defaults\n // Just set to undefined without running validator\n output[key] = undefined;\n }\n continue;\n }\n\n // Validate field - direct function call\n const result = validates[i]!(inputValue);\n\n // Handle validation error (most common unhappy path)\n if (result.issues) {\n issues = gathered(issues, issuesUnder(key, result.issues));\n if (!collectingAllIssues()) return { issues };\n continue;\n }\n\n output[key] = result.value;\n }\n\n if (issues) return { issues };\n const refusal = refuse?.(output);\n if (!refusal) return { value: output };\n return {\n issues: [typeof refusal === \"string\" ? { message: refusal } : refusal],\n };\n };\n\n return partial && !atLeast ? parsePartial : parseDense;\n}\n\n/** `found` after the issues a parse has already gathered, if any. */\nfunction gathered(\n issues: ValidationIssue[] | undefined,\n found: ValidationIssue[]\n): ValidationIssue[] {\n if (!issues) return found;\n issues.push(...found);\n return issues;\n}\n\n/** The unknown keys of a strict object: the first, or every one when collecting. */\nfunction unknownKeyIssues(\n input: Record<string, unknown>,\n keyIndex: ReadonlyMap<string, number>\n): ValidationIssue[] | undefined {\n let issues: ValidationIssue[] | undefined;\n for (const key in input) {\n if (keyIndex.has(key)) continue;\n (issues ??= []).push({ message: `Unknown key: ${key}`, path: [key] });\n if (!collectingAllIssues()) break;\n }\n return issues;\n}\n\n/**\n * Create an object schema.\n *\n * IMPORTANT: No constraint on TEntries to allow circular reference resolution.\n * The identity conditional (R extends infer _ ? _ : never) defers type evaluation.\n *\n * @param entries - Object schema entries\n * @param options - Schema options\n * - `strict` (default: true) - Reject unknown keys\n * - `partial` (default: true) - Make all fields optional\n * - `optional` - Allow undefined\n * - `nullable` - Allow null\n * - `array` - Validate as array of objects\n * - `default` - Default value\n * - `transform` - Transform output\n *\n * @example\n * // Basic object (strict by default)\n * const user = v.object({\n * name: v.string(),\n * age: v.number(),\n * });\n *\n * // Circular references\n * const node = v.object({\n * value: v.string(),\n * child: () => node, // Thunk\n * });\n */\nexport function object<TEntries>(\n entries: TEntries\n): ObjectSchema<TEntries, undefined>;\nexport function object<TEntries, const TOpts extends ObjectOptions | undefined>(\n entries: TEntries,\n options?: TOpts\n): ObjectSchema<TEntries, TOpts>;\nexport function object<\n TEntries, // NO constraint - critical for circular references\n const TOpts extends ObjectOptions | undefined,\n R = ObjectSchema<TEntries, TOpts>,\n>(entries: TEntries, options?: TOpts): R extends infer _ ? _ : never {\n type BaseOutput = ComputeObjectOutput<TEntries, TOpts>;\n\n // Pre-create the optimized object validator (caches keys and schemas)\n const validateObj = createObjectValidator(entries as ObjectEntries, options);\n\n // Check if we have wrapper options (optional/nullable/array)\n const hasOptional = options?.optional === true;\n const hasNullable = options?.nullable === true;\n const hasArray = options?.array === true;\n const hasTransform = options?.transform !== undefined;\n const hasDefault = options?.default !== undefined;\n\n // Fast path: no wrapper options (most common case)\n const needsWrapper =\n hasOptional || hasNullable || hasArray || hasTransform || hasDefault;\n\n let validate: (value: unknown) => any;\n\n if (needsWrapper) {\n // Pre-compute default getter once (avoid repeated typeof checks)\n const getDefault = hasDefault\n ? isFunction(options!.default)\n ? (options!.default as () => BaseOutput)\n : () => options!.default as BaseOutput\n : null;\n\n // Create the base validator (with optional transform)\n const validateItem = hasTransform\n ? (value: unknown): ValidationResult<any> => {\n const result = validateObj(value);\n if (result.issues) return result;\n try {\n return ok(options!.transform!((result as { value: any }).value));\n } catch (error) {\n return fail(\n `Transform failed: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n }\n : validateObj;\n\n // Build wrapper based on options\n if (hasArray) {\n // Array mode: use shared validateArray utility\n const arrayValidate = (value: unknown) =>\n validateArray(value, validateItem);\n\n if (hasOptional && hasNullable) {\n validate = (value: unknown) => {\n if (value === undefined)\n return getDefault ? ok(getDefault()) : OK_UNDEFINED;\n if (value === null) return OK_NULL;\n return arrayValidate(value);\n };\n } else if (hasOptional) {\n validate = (value: unknown) => {\n if (value === undefined)\n return getDefault ? ok(getDefault()) : OK_UNDEFINED;\n return arrayValidate(value);\n };\n } else if (hasNullable) {\n validate = (value: unknown) => {\n if (value === null) return OK_NULL;\n return arrayValidate(value);\n };\n } else {\n validate = arrayValidate;\n }\n } else if (hasOptional && hasNullable) {\n // Single object mode\n validate = (value: unknown) => {\n if (value === undefined)\n return getDefault ? ok(getDefault()) : OK_UNDEFINED;\n if (value === null) return OK_NULL;\n return validateItem(value);\n };\n } else if (hasOptional) {\n validate = (value: unknown) => {\n if (value === undefined)\n return getDefault ? ok(getDefault()) : OK_UNDEFINED;\n return validateItem(value);\n };\n } else if (hasNullable) {\n validate = (value: unknown) => {\n if (value === null) return OK_NULL;\n return validateItem(value);\n };\n } else {\n // Only transform, no optional/nullable\n validate = validateItem;\n }\n } else {\n // Fast path: direct object validation\n validate = validateObj;\n }\n\n const schema = {\n type: \"object\" as const,\n entries,\n options,\n acceptsUndefined: hasOptional || hasDefault,\n \"~standard\": {\n version: 1 as const,\n vendor: \"viborm\" as const,\n validate,\n // Lazy jsonSchema - converter is created when first accessed\n get jsonSchema() {\n const converter = createJsonSchemaConverter(\n schema as unknown as VibSchema<unknown, unknown>\n );\n // Replace getter with static value for subsequent access\n Object.defineProperty(this, \"jsonSchema\", {\n value: converter,\n writable: false,\n enumerable: true,\n });\n return converter;\n },\n },\n extend: (newEntries: ObjectEntries) =>\n object({ ...entries, ...newEntries } as any, options),\n };\n\n return schema as R extends infer _ ? _ : never;\n}\n","/**\n * The one logical instant domain of a VibORM DateTime value.\n *\n * Four-digit ISO years are not only an input spelling. They bound every\n * public DateTime instant, including a `Date` input and a provider value read\n * back through a numeric physical representation.\n */\n\nexport const MIN_DATETIME_EPOCH_MILLISECONDS = -62_167_219_200_000;\nexport const MAX_DATETIME_EPOCH_MILLISECONDS = 253_402_300_799_999;\n\n/** Whether one number names a whole millisecond in the public DateTime domain. */\nexport function isDateTimeInstant(epochMilliseconds: number): boolean {\n return (\n Number.isInteger(epochMilliseconds) &&\n epochMilliseconds >= MIN_DATETIME_EPOCH_MILLISECONDS &&\n epochMilliseconds <= MAX_DATETIME_EPOCH_MILLISECONDS\n );\n}\n\n/** Whether three numeric components name one real proleptic-Gregorian date. */\nexport function isGregorianCalendarDate(\n year: number,\n month: number,\n day: number\n): boolean {\n const hasIntegerComponents =\n Number.isInteger(year) && Number.isInteger(month) && Number.isInteger(day);\n if (!hasIntegerComponents || month < 1 || month > 12 || day < 1) {\n return false;\n }\n let daysInMonth = 31;\n if (month === 2) {\n daysInMonth = isLeapYear(year) ? 29 : 28;\n } else if (month === 4 || month === 6 || month === 9 || month === 11) {\n daysInMonth = 30;\n }\n return day <= daysInMonth;\n}\n\n/** Whether three numeric components name one clock time without leap seconds. */\nexport function isDateTimeClock(\n hour: number,\n minute: number,\n second: number\n): boolean {\n return (\n Number.isInteger(hour) &&\n Number.isInteger(minute) &&\n Number.isInteger(second) &&\n hour >= 0 &&\n hour <= 23 &&\n minute >= 0 &&\n minute <= 59 &&\n second >= 0 &&\n second <= 59\n );\n}\n\nfunction isLeapYear(year: number): boolean {\n return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);\n}\n","import type {\n ComputeInput,\n ComputeOutput,\n ScalarOptions,\n VibSchema,\n} from \"../types\";\nimport { isNumber } from \"../value-guards\";\nimport { buildSchema, ok } from \"./helpers\";\n\n// =============================================================================\n// Number Schema\n// =============================================================================\n\nexport interface BaseNumberSchema<\n Opts extends ScalarOptions<number, any> | undefined = undefined,\n> extends VibSchema<ComputeInput<number, Opts>, ComputeOutput<number, Opts>> {}\n\nexport interface NumberSchema<TInput = number, TOutput = number>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"number\";\n}\n\n// Pre-computed error for fast path\nconst NUMBER_ERROR = Object.freeze({\n issues: Object.freeze([Object.freeze({ message: \"Expected finite number\" })]),\n});\n\n/**\n * Validate that a value is a finite number (rejects NaN and Infinity).\n */\nfunction validateNumber(value: unknown) {\n return isNumber(value) && Number.isFinite(value) ? ok(value) : NUMBER_ERROR;\n}\n\n/**\n * Create a number schema.\n *\n * @example\n * const age = v.number();\n * const optionalAge = v.number({ optional: true });\n * const scores = v.number({ array: true });\n */\nexport function number(): NumberSchema<number, number>;\nexport function number<const Opts extends ScalarOptions<number, any>>(\n options: Opts\n): NumberSchema<ComputeInput<number, Opts>, ComputeOutput<number, Opts>>;\nexport function number<\n const Opts extends ScalarOptions<number, any> | undefined,\n>(\n options?: Opts\n): NumberSchema<ComputeInput<number, Opts>, ComputeOutput<number, Opts>> {\n return buildSchema(\"number\", validateNumber, options) as NumberSchema<\n ComputeInput<number, Opts>,\n ComputeOutput<number, Opts>\n >;\n}\n\n// =============================================================================\n// Integer Schema (number with integer constraint)\n// =============================================================================\n\nexport interface BaseIntegerSchema<\n Opts extends ScalarOptions<number, any> | undefined = undefined,\n> extends VibSchema<ComputeInput<number, Opts>, ComputeOutput<number, Opts>> {}\n\nexport interface IntegerSchema<TInput = number, TOutput = number>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"integer\";\n}\n\n// Pre-computed error for fast path\nconst INTEGER_ERROR = Object.freeze({\n issues: Object.freeze([Object.freeze({ message: \"Expected integer\" })]),\n});\nconst UNSAFE_INTEGER_ERROR = Object.freeze({\n issues: Object.freeze([Object.freeze({ message: \"Expected safe integer\" })]),\n});\n\n/**\n * Validate that a value is an integer.\n */\nfunction validateInteger(value: unknown) {\n if (!(isNumber(value) && Number.isInteger(value))) return INTEGER_ERROR;\n return Number.isSafeInteger(value) ? ok(value) : UNSAFE_INTEGER_ERROR;\n}\n\n/**\n * Create an integer schema.\n *\n * @example\n * const count = v.integer();\n */\nexport function integer(): IntegerSchema<number, number>;\nexport function integer<const Opts extends ScalarOptions<number, any>>(\n options: Opts\n): IntegerSchema<ComputeInput<number, Opts>, ComputeOutput<number, Opts>>;\nexport function integer<\n const Opts extends ScalarOptions<number, any> | undefined,\n>(\n options?: Opts\n): IntegerSchema<ComputeInput<number, Opts>, ComputeOutput<number, Opts>> {\n return buildSchema(\"integer\", validateInteger, options) as IntegerSchema<\n ComputeInput<number, Opts>,\n ComputeOutput<number, Opts>\n >;\n}\n\n// Export validate functions for reuse\nexport { validateNumber, validateInteger };\n","import type {\n Cast,\n InferInput,\n InferOutput,\n ThunkCast,\n ValidationResult,\n VibSchema,\n} from \"../types\";\nimport { isFunction } from \"../value-guards\";\nimport { createSchema, ok } from \"./helpers\";\n\n// =============================================================================\n// Optional Schema\n// =============================================================================\n\n/**\n * Schema or thunk that can be wrapped with optional.\n */\nexport type WrappableSchema =\n | VibSchema<any, any>\n | ThunkCast<any, any>\n | (() => Cast<any, any>);\n\n/**\n * Unwrap a schema or thunk to get the underlying schema type.\n */\ntype UnwrapSchema<T> =\n T extends VibSchema<any, any>\n ? T\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\nexport interface OptionalSchema<\n TWrapped extends WrappableSchema,\n TDefault = undefined,\n TInput = InferInput<UnwrapSchema<TWrapped>> | undefined,\n TOutput = TDefault extends undefined\n ? InferOutput<UnwrapSchema<TWrapped>> | undefined\n : InferOutput<UnwrapSchema<TWrapped>>,\n> extends VibSchema<TInput, TOutput> {\n readonly type: \"optional\";\n readonly wrapped: TWrapped;\n readonly default: TDefault;\n readonly acceptsUndefined: true;\n}\n\n// Compute output type based on default\ntype OptionalOutput<\n TWrapped extends WrappableSchema,\n TDefault,\n> = TDefault extends undefined\n ? InferOutput<UnwrapSchema<TWrapped>> | undefined\n : InferOutput<UnwrapSchema<TWrapped>>;\n\n/**\n * Create an optional schema that allows undefined values.\n * Supports both direct schemas and thunks (for circular references).\n * Optionally provide a default value for when undefined is received.\n *\n * @example\n * const optionalName = v.optional(v.string());\n * const nameWithDefault = v.optional(v.string(), \"Unknown\");\n *\n * // With thunks (circular references)\n * const node = v.object({ child: v.optional(() => node) });\n */\nexport function optional<\n TWrapped extends WrappableSchema,\n TDefault extends\n | InferOutput<UnwrapSchema<TWrapped>>\n | (() => InferOutput<UnwrapSchema<TWrapped>>)\n | undefined = undefined,\n>(\n wrapped: TWrapped,\n defaultValue?: TDefault\n): OptionalSchema<TWrapped, TDefault> {\n // Check if wrapped is a thunk (function) or direct schema\n const isThunk = isFunction(wrapped) && !(\"~standard\" in wrapped);\n\n // Lazy resolution for thunks\n let cachedValidate: ((value: unknown) => any) | null = isThunk\n ? null\n : (wrapped as VibSchema<any, any>)[\"~standard\"].validate;\n\n const getValidate = () => {\n if (cachedValidate) return cachedValidate;\n\n const resolvedSchema = (wrapped as () => VibSchema<any, any>)();\n cachedValidate = resolvedSchema[\"~standard\"].validate;\n\n return cachedValidate;\n };\n\n const schema = createSchema(\n \"optional\",\n (value): ValidationResult<OptionalOutput<TWrapped, TDefault>> => {\n // Handle undefined - fast path\n if (value === undefined) {\n if (defaultValue !== undefined) {\n const resolved = isFunction(defaultValue)\n ? (defaultValue as () => InferOutput<UnwrapSchema<TWrapped>>)()\n : defaultValue;\n return ok(resolved) as ValidationResult<\n OptionalOutput<TWrapped, TDefault>\n >;\n }\n return ok(undefined) as ValidationResult<\n OptionalOutput<TWrapped, TDefault>\n >;\n }\n\n // Delegate to wrapped schema (resolve thunk if needed)\n const validate = getValidate();\n return validate(value) as ValidationResult<\n OptionalOutput<TWrapped, TDefault>\n >;\n }\n ) as OptionalSchema<TWrapped, TDefault>;\n\n // Add references\n (schema as any).wrapped = wrapped;\n (schema as any).default = defaultValue;\n // Optional schema always accepts undefined\n (schema as any).acceptsUndefined = true;\n\n return schema;\n}\n","import type { ValidationResult } from \"../types\";\nimport {\n GEO_LATITUDE_MAX,\n GEO_LATITUDE_MIN,\n GEO_LONGITUDE_MAX,\n GEO_LONGITUDE_MIN,\n GEO_POINT_KEYS,\n type GeoPoint,\n} from \"./geo-values\";\nimport { createSchema, fail, ok, validateSchema } from \"./helpers\";\nimport { validateNumber } from \"./number\";\nimport { object } from \"./object\";\n\nexport type { GeoPoint } from \"./geo-values\";\n\n/**\n * One finite coordinate inside its inclusive range, with -0 read as 0: the\n * type VibORM returns has no -0, and points decode provider rows and cache\n * snapshots through this same schema.\n */\nfunction geoCoordinate(label: string, low: number, high: number) {\n return createSchema<number, number>(\"number\", (value) => {\n const coordinate = validateNumber(value);\n if (coordinate.issues) return coordinate;\n if (coordinate.value < low || coordinate.value > high) {\n return fail(`${label} must be between ${low} and ${high}`);\n }\n return ok(Object.is(coordinate.value, -0) ? 0 : coordinate.value);\n });\n}\n\nexport const geoLongitude = geoCoordinate(\n \"Longitude\",\n GEO_LONGITUDE_MIN,\n GEO_LONGITUDE_MAX\n);\nexport const geoLatitude = geoCoordinate(\n \"Latitude\",\n GEO_LATITUDE_MIN,\n GEO_LATITUDE_MAX\n);\n\nconst pointRecord = object(\n { [GEO_POINT_KEYS[0]]: geoLongitude, [GEO_POINT_KEYS[1]]: geoLatitude },\n { partial: false }\n);\n\n/** Validate the one public GeoPoint representation into a fresh record. */\nexport function validateGeoPoint(value: unknown): ValidationResult<GeoPoint> {\n const point = validateSchema(pointRecord, value);\n if (point.issues) return point;\n const { longitude, latitude } = point.value;\n // -180 and +180 are one meridian. The SQLite CHECK\n // (adapters/databases/sqlite/storage/geo-point.ts) refuses -180, and the coordinate\n // predicates in adapters/shared/geo-point.ts assume the +180 spelling.\n return ok({\n longitude: longitude === GEO_LONGITUDE_MIN ? GEO_LONGITUDE_MAX : longitude,\n latitude,\n });\n}\n"],"mappings":"yNAuBA,MAAM,EAAe,OAAO,OAAO,CACjC,OAAQ,OAAO,OAAO,CACpB,OAAO,OAAO,CAAE,QAAS,uCAAwC,CAAC,CACnE,CAAC,CACH,CAAC,CAOW,EAAsB,cAC7B,EAAc,IAAI,OAAO,EAAoB,CAKnD,SAAS,eAAe,EAAgB,CAEtC,OADI,EAAS,EAAM,CAAS,GAAG,EAAM,CAC9B,OAAO,GAAU,UAAY,EAAY,KAAK,EAAM,CACvD,GAAG,OAAO,EAAM,CAAC,CACjB,EAcN,SAAgB,OAGd,EACuE,CACvE,OAAO,YAAY,SAAU,eAAgB,EAAQ,CC1DvD,MAAa,EAAiB,CAAC,YAAa,WAAW,CAC1C,EAAoB,KACpB,EAAoB,IACpB,EAAmB,IACnB,EAAmB,GACnB,EAAkB,CAAC,QAAS,OAAQ,QAAS,OAAO,CACpD,EAA8B,ECOrC,EAAY,wBACZ,EACJ,mEACI,EAAkB,wBAaxB,SAAS,SAAS,EAA0B,CAC1C,GAAI,CAAC,EAAU,KAAK,EAAI,CAAE,MAAO,CAAE,YAAa,aAAc,CAC9D,IAAM,EAAM,IAAI,WAAW,EAAI,OAAS,EAAE,CAC1C,IAAK,IAAI,EAAQ,EAAG,EAAQ,EAAI,OAAQ,IACtC,EAAI,GAAS,OAAO,SAAS,EAAI,MAAM,EAAQ,EAAG,EAAQ,EAAI,EAAE,CAAE,GAAG,CAEvE,MAAO,CAAE,MAAO,EAAK,CAGvB,SAAS,YAAY,EAA6B,CAChD,GAAI,CAAC,EAAO,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EAAS,aACb,WACC,GAEK,IAAU,IAAA,GASL,GARH,IAAiB,IAAA,GAQX,IAAA,GAPS,EAAW,EAAa,CACpC,GAA4D,CAC7D,EACe,CAUN,aAAa,CACd,EAAM,CAIzB,CAQD,MALC,GAAe,QAAU,EACzB,EAAe,QAAU,EAEzB,EAAe,iBAAmB,GAE5B,EC5GT,SAAS,cAAc,EAAe,EAAa,EAAc,CAC/D,OAAO,aAA6B,SAAW,GAAU,CACvD,IAAM,EAAa,eAAe,EAAM,CAKxC,OAJI,EAAW,OAAe,EAC1B,EAAW,MAAQ,GAAO,EAAW,MAAQ,EACxC,KAAK,GAAG,EAAM,mBAAmB,EAAI,OAAO,IAAO,CAErD,GAAG,OAAO,GAAG,EAAW,MAAO,GAAG,CAAG,EAAI,EAAW,MAAM,EACjE,CAGJ,MAAa,GAAe,cAC1B,YACA,EACA,IACD,CACY,EAAc,cACzB,WACA,IACA,GACD,CAEK,GAAc,OAClB,EAAG,EAAe,IAAK,IAAe,EAAe,IAAK,EAAa,CACvE,CAAE,QAAS,GAAO,CACnB,CAGD,SAAgB,iBAAiB,EAA4C,CAC3E,IAAM,EAAQ,eAAe,GAAa,EAAM,CAChD,GAAI,EAAM,OAAQ,OAAO,EACzB,GAAM,CAAE,YAAW,YAAa,EAAM,MAItC,OAAO,GAAG,CACR,UAAW,IAAc,EAAoB,IAAoB,EACjE,WACD,CAAC"}
@@ -1,2 +0,0 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{t}from"./identifier-hQCs8M1n.mjs";import{f as n,t as r}from"./registration-preflight-DEjv050M.mjs";function hydrateSchemaNames(e,t=!1){let i=Object.entries(e);if(t){for(let[e,t]of i)bindModelNames(e,t);return}let a=r(i);if(a)throw new n([a]);for(let[e,t]of i)preflightModelIdentifiers(e,t);for(let[e,t]of i)bindModelNames(e,t)}function preflightModelIdentifiers(e,t){let n=t[`~`].state;assertValidIdentifier(`Model`,e),n.tableName!==void 0&&assertValidIdentifier(`Mapped table`,n.tableName,e);for(let t of Object.keys(n.shape))assertValidIdentifier(`Field`,t,e);for(let t of Object.values(n.scalars))t[`~`].state.columnName!==void 0&&assertValidIdentifier(`Mapped column`,t[`~`].state.columnName,e)}function bindModelNames(e,t){let n=t[`~`].names,r=t[`~`].state,i=t[`~`].nameRegistry;n.ts=e,n.sql=r.tableName??e;for(let[e,t]of Object.entries(r.scalars)){let n={ts:e,sql:t[`~`].state.columnName??e};i.fields.set(e,n)}}function assertValidIdentifier(e,n,r){if(t(n))return;let i=r?` in '${r}'`:``,a=String(n);throw Error(`${e} '${a}'${i} is invalid identifier; identifiers must be ASCII, at most 63 bytes, and must not collide with Object.prototype properties`)}export{hydrateSchemaNames as t};
2
- //# sourceMappingURL=hydration-CAxOL4aI.mjs.map
@@ -1,2 +0,0 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-AdXAoy6l.mjs";import{t as n}from"./migrations-DTObIjAm.mjs";import{o as r}from"./sql-Bp7jicEX.mjs";import{d as i,n as a,p as o,s}from"./validator-X9-bwtRo.mjs";import{_ as c,g as l}from"./registration-preflight-DEjv050M.mjs";import{it as u,st as d}from"./geo-point-codec-lhxH42SK.mjs";import{t as f}from"./hydration-CAxOL4aI.mjs";import{M as p}from"./standard-sql-Bk4RZPqJ.mjs";function mapReferentialAction(e){switch(e.toUpperCase()){case`CASCADE`:return`cascade`;case`SET NULL`:return`setNull`;case`RESTRICT`:return`restrict`;case`SET DEFAULT`:return`setDefault`;default:return`noAction`}}function groupBy(e,t){let n=new Map;for(let r of e){let e=t(r),i=n.get(e);i?i.push(r):n.set(e,[r])}return n}function groupByNested(e,t,n){let r=new Map;for(let i of e){let e=t(i),a=n(i),o=r.get(e);o||(o=new Map,r.set(e,o));let s=o.get(a);s?s.push(i):o.set(a,[i])}return r}const m=`[0-9a-fA-F]`,h=`[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]`,g=`[0-9A-Za-z]`,_={uuid:{length:36,regex:`^${m}{8}-${m}{4}-${m}{4}-${m}{4}-${m}{12}$`,glob:`${m.repeat(8)}-${m.repeat(4)}-${m.repeat(4)}-${m.repeat(4)}-${m.repeat(12)}`,fold:`lower`,max:void 0},ulid:{length:26,regex:`^[0-7]${h}{25}$`,glob:`[0-7]${h.repeat(25)}`,fold:`upper`,max:void 0},ksuid:{length:27,regex:`^${g}{27}$`,glob:g.repeat(27),fold:void 0,max:d}};function patternOf(e){return e.format===`ulid`?_.ulid:e.format===`ksuid`?_.ksuid:_.uuid}const int=e=>r.raw(String(e));function fromSql(e,t,n,i){let a=p(t===`mysql`?"`":`"`),o=t===`postgresql`&&n?`${a(n)}.`:``;return r.raw(`${o+a(c(e))} AS ${i}`)}function columnSql(e,t,n,i){let a=p(n===`mysql`?"`":`"`);return r.raw(`${i}.${a(l(e,t))}`)}function payloadSql(e,t){let n=t.prefix;return n?r`substr(${e}, ${int(n.length+2)})`:e}function bytesSql(e,t){return t===`mysql`?r`CAST(${e} AS BINARY)`:e}function orderedSql(e,t){return t===`postgresql`?r`CAST(${e} AS text) COLLATE "C"`:bytesSql(e,t)}function admitsSql(e,t,n){let i=patternOf(t),a=payloadSql(e,t),o=n===`postgresql`?r`${a} ~ ${i.regex}`:n===`mysql`?r`${a} REGEXP ${i.regex}`:r`${a} GLOB ${i.glob}`,s=r`${r.raw(n===`mysql`?`CHAR_LENGTH`:`length`)}(${a}) = ${int(i.length)} AND ${o}`,c=i.max===void 0?s:r`${s} AND ${orderedSql(a,n)} <= ${i.max}`,l=t.prefix;return l?r`${bytesSql(r`substr(${e}, 1, ${int(l.length+1)})`,n)} = ${`${l}-`} AND ${c}`:c}function foldSql(e,t,n){let i=patternOf(t).fold,a=payloadSql(e,t);return bytesSql(i===void 0?a:r`${r.raw(i)}(${a})`,n)}function foldCollisionCheck(e,t,n,i){return{kind:`trusted-read`,query:r`SELECT COUNT(${t}) = COUNT(DISTINCT ${foldSql(t,n,i)}) AS ok FROM ${e}`,equals:!0}}function isSingleColumnKey(e,t){return o(e).referenceableKeys.some(e=>e.length===1&&e[0]===t)}const noRowWhere=(e,t)=>({kind:`trusted-read`,query:r`SELECT NOT EXISTS (SELECT 1 FROM ${e} WHERE ${t}) AS ok`,equals:!0});function referencingColumns(e,t){let n=[];for(let r of i(t))if(r.kind===`foreignKey`&&(r.endpoints[0]===r.owner?r.endpoints[1]:r.endpoints[0]).source===e.model)for(let t of r.reference.members)t.referencedField===e.field&&n.push({model:r.owner.source,field:t.foreignField});return n}function identifierConversionChecks(e){let{model:i,field:o,dialect:d,namespace:p}=e;f(e.schema);let m=a(e.schema),h=s(i,o,m);if(h===void 0||!u(h.format))throw new n(`'${c(i)}.${l(i,o)}' has no compactly stored identifier domain, so it has no text conversion to check: only uuid, uuidv7, ulid and ksuid change storage.`,t.INVALID_INPUT);let g=fromSql(i,d,p,`p`),_=columnSql(i,o,d,`p`),v=[noRowWhere(g,r`${_} IS NOT NULL AND NOT (${admitsSql(_,h,d)})`)],y=patternOf(h).fold!==void 0;y&&v.push(foldCollisionCheck(g,_,h,d));for(let t of referencingColumns(e,m)){let e=fromSql(t.model,d,p,`c`),n=columnSql(t.model,t.field,d,`c`);v.push(noRowWhere(e,r`${n} IS NOT NULL AND NOT (${admitsSql(n,h,d)})`)),y&&isSingleColumnKey(t.model,t.field)&&v.push(foldCollisionCheck(e,n,h,d)),v.push(noRowWhere(e,r`${n} IS NOT NULL AND NOT EXISTS (SELECT 1 FROM ${g} WHERE ${foldSql(_,h,d)} = ${foldSql(n,h,d)})`))}return v}const v=/^(?:text|citext|varchar\(\d+\)|character varying.*)$/i,literal=e=>`'${e.replaceAll(`'`,`''`)}'`;function postgresTextToUuidGuard(e,t){let n=`${e}.${t}`;return`DO \$viborm\$ DECLARE invalid bigint; BEGIN SELECT count(*) INTO invalid FROM ${e} WHERE ${t} IS NOT NULL AND ${t} !~ ${literal(_.uuid.regex)}; IF invalid > 0 THEN RAISE EXCEPTION ${literal(`VibORM: % row(s) of ${n} are not canonical uuid text, so this conversion would abort on them. A prefixed identifier is one of the shapes that fails here: only the payload is stored, and no generated statement strips a prefix. Convert the rows yourself — add the uuid column, write the payloads into it, drop the old column and rename — or keep the column as it is with a text-family native type, which validates the domain without changing storage.`)}, invalid; END IF; END \$viborm\$`}function isPostgresTextToUuid(e,t){return t.toLowerCase()===`uuid`&&v.test(e.trim())}export{groupByNested as a,groupBy as i,isPostgresTextToUuid as n,mapReferentialAction as o,postgresTextToUuidGuard as r,identifierConversionChecks as t};
2
- //# sourceMappingURL=identifier-conversion-GgbwHc2G.mjs.map
@@ -1,2 +0,0 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{r as t}from"./validation-Dk9Q_-C7.mjs";const n=/^[a-zA-Z_][a-zA-Z0-9_]*$/,r=new Set(Object.getOwnPropertyNames(Object.prototype));function isValidSchemaIdentifier(e){return typeof e==`string`&&e.length<=63&&n.test(e)&&!r.has(e)}const i={postgresql:63,mysql:64},a={postgresql:`PostgreSQL`,mysql:`MySQL`},o=new Set([`information_schema`,`mysql`,`performance_schema`,`sys`,`ndbinfo`]);function refuseNamespace(e,n){throw new t(`The "namespace" option ${n} (${a[e]}).`)}function normalizeNamespace(e,t){typeof e!=`string`&&refuseNamespace(t,`must be a string; received type "${typeof e}"`);let a=i[t];return e.length>a&&refuseNamespace(t,`must be at most ${a} characters; received ${e.length}`),n.test(e)||refuseNamespace(t,`must match [A-Za-z_][A-Za-z0-9_]*; received ${JSON.stringify(e)}`),r.has(e)&&refuseNamespace(t,`must not be an Object.prototype property name; received ${JSON.stringify(e)}`),t===`postgresql`?((e===`information_schema`||e.startsWith(`pg_`))&&refuseNamespace(t,`must not be a system schema; "information_schema" and the "pg_" prefix are reserved`),e):(o.has(e.toLowerCase())&&refuseNamespace(t,`must not be a system database; received ${JSON.stringify(e)}`),e)}export{normalizeNamespace as n,isValidSchemaIdentifier as t};
2
- //# sourceMappingURL=identifier-hQCs8M1n.mjs.map