viborm 1.14.2 → 1.15.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 (272) hide show
  1. package/dist/{adapter-namespace-DaRiTIIf.mjs → adapter-namespace-DD-BQ2Wk.mjs} +2 -2
  2. package/dist/{adapter-namespace-DaRiTIIf.mjs.map → adapter-namespace-DD-BQ2Wk.mjs.map} +1 -1
  3. package/dist/adapters.d.mts +15 -3
  4. package/dist/adapters.mjs +1 -1
  5. package/dist/{args-764KdWMr.mjs → args-BvA37zBZ.mjs} +2 -2
  6. package/dist/{args-764KdWMr.mjs.map → args-BvA37zBZ.mjs.map} +1 -1
  7. package/dist/{batch-refs-C-gx7A4-.mjs → batch-refs-BmEpMmjI.mjs} +2 -2
  8. package/dist/{batch-refs-C-gx7A4-.mjs.map → batch-refs-BmEpMmjI.mjs.map} +1 -1
  9. package/dist/bun-sql.d.mts +1 -1
  10. package/dist/bun-sql.mjs +1 -1
  11. package/dist/bun-sqlite.d.mts +1 -1
  12. package/dist/bun-sqlite.mjs +1 -1
  13. package/dist/cache/cloudflare-kv.d.mts +1 -1
  14. package/dist/cache/cloudflare-kv.mjs +1 -1
  15. package/dist/cache/memory.d.mts +1 -1
  16. package/dist/cache/memory.mjs +1 -1
  17. package/dist/cache.d.mts +2 -2
  18. package/dist/cache.mjs +1 -1
  19. package/dist/{call-Cz8XUmrl.mjs → call-BWFI7-vU.mjs} +2 -2
  20. package/dist/{call-Cz8XUmrl.mjs.map → call-BWFI7-vU.mjs.map} +1 -1
  21. package/dist/cli.mjs +2 -2
  22. package/dist/cli.mjs.map +1 -1
  23. package/dist/client-CVCC-D1j.mjs +2 -0
  24. package/dist/client-CVCC-D1j.mjs.map +1 -0
  25. package/dist/{client-CRxfhw2y.d.mts → client-DZ39sYy2.d.mts} +2 -2
  26. package/dist/{client-y7TV0PRZ.mjs → client-DtPTegtA.mjs} +2 -2
  27. package/dist/{client-y7TV0PRZ.mjs.map → client-DtPTegtA.mjs.map} +1 -1
  28. package/dist/client.d.mts +3 -3
  29. package/dist/client.mjs +1 -1
  30. package/dist/config.d.mts +1 -1
  31. package/dist/config.mjs +1 -1
  32. package/dist/{confine-DqFBTUw6.mjs → confine-BGGv2du0.mjs} +2 -2
  33. package/dist/{confine-DqFBTUw6.mjs.map → confine-BGGv2du0.mjs.map} +1 -1
  34. package/dist/{coordination-6qZHx_kl.mjs → coordination-BY6Np3xV.mjs} +2 -2
  35. package/dist/{coordination-6qZHx_kl.mjs.map → coordination-BY6Np3xV.mjs.map} +1 -1
  36. package/dist/d1.d.mts +1 -1
  37. package/dist/d1.mjs +1 -1
  38. package/dist/{database-adapter-BGqvjeEy.d.mts → database-adapter-D62c-uC6.d.mts} +604 -473
  39. package/dist/{datetime-physical-codec-Dj-APo9f.mjs → datetime-physical-codec-BS2T81sD.mjs} +2 -2
  40. package/dist/{datetime-physical-codec-Dj-APo9f.mjs.map → datetime-physical-codec-BS2T81sD.mjs.map} +1 -1
  41. package/dist/{defaults-DwOHWI_M.mjs → defaults-CrtGVdEC.mjs} +2 -2
  42. package/dist/{defaults-DwOHWI_M.mjs.map → defaults-CrtGVdEC.mjs.map} +1 -1
  43. package/dist/{document-BVTQ-cF-.d.mts → document-o5Bd5ZoJ.d.mts} +1 -1
  44. package/dist/{driver-BBEmaJZy.d.mts → driver-0cdCF_KD.d.mts} +1 -1
  45. package/dist/{driver-BGVcgnIX.mjs → driver-D1grnHEr.mjs} +2 -2
  46. package/dist/{driver-BGVcgnIX.mjs.map → driver-D1grnHEr.mjs.map} +1 -1
  47. package/dist/{driver-BIXhOH2_.mjs → driver-Df88hu4U.mjs} +2 -2
  48. package/dist/{driver-BIXhOH2_.mjs.map → driver-Df88hu4U.mjs.map} +1 -1
  49. package/dist/driver.d.mts +1 -1
  50. package/dist/driver.mjs +1 -1
  51. package/dist/durable-object.d.mts +1 -1
  52. package/dist/durable-object.mjs +1 -1
  53. package/dist/error-mapping-DIRlrmDK.mjs +2 -0
  54. package/dist/error-mapping-DIRlrmDK.mjs.map +1 -0
  55. package/dist/every-BHEmfLOW.mjs +2 -0
  56. package/dist/{every-tOgQmaIE.mjs.map → every-BHEmfLOW.mjs.map} +1 -1
  57. package/dist/execution-context-VMQm-9CH.mjs +2 -0
  58. package/dist/execution-context-VMQm-9CH.mjs.map +1 -0
  59. package/dist/{exports-COCJ8f2f.d.mts → exports-Bzvtum3F.d.mts} +1 -1
  60. package/dist/geo-area-codec-BDvW7IH-.mjs +2 -0
  61. package/dist/{geo-area-codec-mHrM3b9A.mjs.map → geo-area-codec-BDvW7IH-.mjs.map} +1 -1
  62. package/dist/{hydration-A3zffFWP.mjs → hydration-D7U8HACL.mjs} +2 -2
  63. package/dist/{hydration-A3zffFWP.mjs.map → hydration-D7U8HACL.mjs.map} +1 -1
  64. package/dist/{identifier-conversion-DHYPTgzr.mjs → identifier-conversion-Ci_iaJ0b.mjs} +2 -2
  65. package/dist/{identifier-conversion-DHYPTgzr.mjs.map → identifier-conversion-Ci_iaJ0b.mjs.map} +1 -1
  66. package/dist/identifiers-BTCfD5ic.mjs +2 -0
  67. package/dist/identifiers-BTCfD5ic.mjs.map +1 -0
  68. package/dist/index.d.mts +2 -2
  69. package/dist/index.mjs +1 -1
  70. package/dist/instrumentation.d.mts +1 -1
  71. package/dist/instrumentation.mjs +1 -1
  72. package/dist/{introspect-Bm6xnXcG.mjs → introspect-C4T5gt9O.mjs} +2 -2
  73. package/dist/{introspect-Bm6xnXcG.mjs.map → introspect-C4T5gt9O.mjs.map} +1 -1
  74. package/dist/{json-DgMc8-GU.mjs → json-CHdgejCt.mjs} +2 -2
  75. package/dist/{json-DgMc8-GU.mjs.map → json-CHdgejCt.mjs.map} +1 -1
  76. package/dist/judge-words-DpwxOfre.mjs +2 -0
  77. package/dist/judge-words-DpwxOfre.mjs.map +1 -0
  78. package/dist/{key-hxFFCKed.mjs → key-B3xgpu0M.mjs} +2 -2
  79. package/dist/{key-hxFFCKed.mjs.map → key-B3xgpu0M.mjs.map} +1 -1
  80. package/dist/{keys-BQxM4c_a.mjs → keys-1Z6WKrnE.mjs} +1 -1
  81. package/dist/{keys-BQxM4c_a.mjs.map → keys-1Z6WKrnE.mjs.map} +1 -1
  82. package/dist/{libsql-DuGR904j.mjs → libsql-DJRsCDT_.mjs} +2 -2
  83. package/dist/{libsql-DuGR904j.mjs.map → libsql-DJRsCDT_.mjs.map} +1 -1
  84. package/dist/libsql.d.mts +1 -1
  85. package/dist/libsql.mjs +1 -1
  86. package/dist/{memory-G4cSuc6A.mjs → memory-gjKMy3Ql.mjs} +2 -2
  87. package/dist/{memory-G4cSuc6A.mjs.map → memory-gjKMy3Ql.mjs.map} +1 -1
  88. package/dist/methods-part-DoTrY6b9.mjs +2 -0
  89. package/dist/methods-part-DoTrY6b9.mjs.map +1 -0
  90. package/dist/migrations/mysql.d.mts +4 -4
  91. package/dist/migrations/mysql.mjs +1 -1
  92. package/dist/migrations/postgres.d.mts +4 -4
  93. package/dist/migrations/postgres.mjs +1 -1
  94. package/dist/migrations/snowflake.d.mts +4 -4
  95. package/dist/migrations/snowflake.mjs +1 -1
  96. package/dist/migrations/sqlite.d.mts +4 -4
  97. package/dist/migrations/sqlite.mjs +1 -1
  98. package/dist/migrations/storage/durable-object.mjs +1 -1
  99. package/dist/migrations/storage/r2.mjs +1 -1
  100. package/dist/migrations/surrealdb.d.mts +4 -4
  101. package/dist/migrations/surrealdb.mjs +1 -1
  102. package/dist/migrations/tenant.d.mts +2 -2
  103. package/dist/migrations/tenant.mjs +1 -1
  104. package/dist/migrations.d.mts +4 -4
  105. package/dist/migrations.mjs +1 -1
  106. package/dist/{mysql-BNXWfTOo.mjs → mysql-BH0Z3PlH.mjs} +2 -2
  107. package/dist/{mysql-BNXWfTOo.mjs.map → mysql-BH0Z3PlH.mjs.map} +1 -1
  108. package/dist/mysql-adapter-B06Ve3ds.mjs +2 -0
  109. package/dist/mysql-adapter-B06Ve3ds.mjs.map +1 -0
  110. package/dist/mysql2.d.mts +1 -1
  111. package/dist/mysql2.mjs +1 -1
  112. package/dist/named-statements-Bdz2GD5R.d.mts +13 -0
  113. package/dist/named-statements-CMj1QEyw.mjs +2 -0
  114. package/dist/named-statements-CMj1QEyw.mjs.map +1 -0
  115. package/dist/{native-types-DgjMUikz.mjs → native-types-DspZ0Z5E.mjs} +2 -2
  116. package/dist/{native-types-DgjMUikz.mjs.map → native-types-DspZ0Z5E.mjs.map} +1 -1
  117. package/dist/neon-http.d.mts +1 -1
  118. package/dist/neon-http.mjs +1 -1
  119. package/dist/{object-store-B_YMoW8u.d.mts → object-store-D5x-Yf7w.d.mts} +3 -3
  120. package/dist/{object-store-DS0F0yZX.mjs → object-store-WIE0DGGG.mjs} +1 -1
  121. package/dist/{object-store-DS0F0yZX.mjs.map → object-store-WIE0DGGG.mjs.map} +1 -1
  122. package/dist/{on-ylYaKuRu.mjs → on-DvrfHGje.mjs} +2 -2
  123. package/dist/{on-ylYaKuRu.mjs.map → on-DvrfHGje.mjs.map} +1 -1
  124. package/dist/on.d.mts +1 -1
  125. package/dist/on.mjs +1 -1
  126. package/dist/ordering/keys.mjs +1 -1
  127. package/dist/ordering.d.mts +1 -1
  128. package/dist/ordering.mjs +1 -1
  129. package/dist/pending-operation-Dq4rv-Ml.mjs +2 -0
  130. package/dist/pending-operation-Dq4rv-Ml.mjs.map +1 -0
  131. package/dist/permissions.d.mts +1 -1
  132. package/dist/permissions.mjs +1 -1
  133. package/dist/pg.d.mts +27 -1
  134. package/dist/pg.mjs +1 -1
  135. package/dist/pg.mjs.map +1 -1
  136. package/dist/pglite.d.mts +1 -1
  137. package/dist/pglite.mjs +1 -1
  138. package/dist/{physical-CeE2nYmI.mjs → physical-wboFLAg9.mjs} +2 -2
  139. package/dist/{physical-CeE2nYmI.mjs.map → physical-wboFLAg9.mjs.map} +1 -1
  140. package/dist/planetscale.d.mts +1 -1
  141. package/dist/planetscale.mjs +1 -1
  142. package/dist/{planner-DHjdvjwk.d.mts → planner-Ckoxeruk.d.mts} +1 -1
  143. package/dist/{postgres-CDdh5dSP.mjs → postgres-DQ_pO0hi.mjs} +2 -2
  144. package/dist/{postgres-CDdh5dSP.mjs.map → postgres-DQ_pO0hi.mjs.map} +1 -1
  145. package/dist/{postgres-adapter-axapXX8d.mjs → postgres-adapter-Byp7Zpop.mjs} +2 -2
  146. package/dist/{postgres-adapter-axapXX8d.mjs.map → postgres-adapter-Byp7Zpop.mjs.map} +1 -1
  147. package/dist/postgres-adapter-Ia4u0-Ht.mjs +2 -0
  148. package/dist/postgres-adapter-Ia4u0-Ht.mjs.map +1 -0
  149. package/dist/postgres-result-CiS5OWp1.mjs +2 -0
  150. package/dist/postgres-result-CiS5OWp1.mjs.map +1 -0
  151. package/dist/postgres.d.mts +17 -1
  152. package/dist/postgres.mjs +1 -1
  153. package/dist/postgres.mjs.map +1 -1
  154. package/dist/{provider-limits-Ccsb8PTb.mjs → provider-limits-CCOa4d1E.mjs} +2 -2
  155. package/dist/{provider-limits-Ccsb8PTb.mjs.map → provider-limits-CCOa4d1E.mjs.map} +1 -1
  156. package/dist/{provider-parameter-snapshot-BikrgKqI.mjs → provider-parameter-snapshot-C0ehKSAA.mjs} +2 -2
  157. package/dist/{provider-parameter-snapshot-BikrgKqI.mjs.map → provider-parameter-snapshot-C0ehKSAA.mjs.map} +1 -1
  158. package/dist/query-Cdy8E2jM.mjs +2 -0
  159. package/dist/query-Cdy8E2jM.mjs.map +1 -0
  160. package/dist/{query-inspection-BoG-yAln.mjs → query-inspection-C-T2ttRx.mjs} +2 -2
  161. package/dist/{query-inspection-BoG-yAln.mjs.map → query-inspection-C-T2ttRx.mjs.map} +1 -1
  162. package/dist/{raw-Dyq6Y6UX.mjs → raw-uaVIxHcE.mjs} +2 -2
  163. package/dist/{raw-Dyq6Y6UX.mjs.map → raw-uaVIxHcE.mjs.map} +1 -1
  164. package/dist/{relation-bound-ku_cMdye.mjs → relation-bound-BaU-LuuI.mjs} +1 -1
  165. package/dist/{relation-bound-ku_cMdye.mjs.map → relation-bound-BaU-LuuI.mjs.map} +1 -1
  166. package/dist/{rule-words-ZIGm7cDm.mjs → rule-words-C4lXzgW2.mjs} +2 -2
  167. package/dist/{rule-words-ZIGm7cDm.mjs.map → rule-words-C4lXzgW2.mjs.map} +1 -1
  168. package/dist/scalar-B9WizsvR.mjs +4 -0
  169. package/dist/scalar-B9WizsvR.mjs.map +1 -0
  170. package/dist/schema/introspect.d.mts +2 -2
  171. package/dist/schema/introspect.mjs +1 -1
  172. package/dist/schema/json.d.mts +2 -2
  173. package/dist/schema/json.mjs +1 -1
  174. package/dist/{schema-BYA-_bpk.mjs → schema-MB-pPNTO.mjs} +2 -2
  175. package/dist/schema-MB-pPNTO.mjs.map +1 -0
  176. package/dist/{schema-CFIaebgi.mjs → schema-TthAXPVP.mjs} +2 -2
  177. package/dist/{schema-CFIaebgi.mjs.map → schema-TthAXPVP.mjs.map} +1 -1
  178. package/dist/schema-introspection-wMVZowIF.mjs +6 -0
  179. package/dist/schema-introspection-wMVZowIF.mjs.map +1 -0
  180. package/dist/schema.d.mts +1 -1
  181. package/dist/schema.mjs +1 -1
  182. package/dist/select-assembly-SuVxJjps.mjs +2 -0
  183. package/dist/select-assembly-SuVxJjps.mjs.map +1 -0
  184. package/dist/{serializer-rBq3v1xr.mjs → serializer-B2kk7NAR.mjs} +5 -5
  185. package/dist/{serializer-rBq3v1xr.mjs.map → serializer-B2kk7NAR.mjs.map} +1 -1
  186. package/dist/{settled-BjyuA76m.mjs → settled-Dkk5w1vE.mjs} +2 -2
  187. package/dist/{settled-BjyuA76m.mjs.map → settled-Dkk5w1vE.mjs.map} +1 -1
  188. package/dist/{snowflake-UOCC820W.mjs → snowflake-6sBLJi34.mjs} +2 -2
  189. package/dist/{snowflake-UOCC820W.mjs.map → snowflake-6sBLJi34.mjs.map} +1 -1
  190. package/dist/snowflake.d.mts +2 -2
  191. package/dist/snowflake.mjs +1 -1
  192. package/dist/snowflake.mjs.map +1 -1
  193. package/dist/soft-delete.d.mts +1 -1
  194. package/dist/soft-delete.mjs +1 -1
  195. package/dist/{spans-XDUFeTzC.mjs → spans-BE-EjlZK.mjs} +1 -1
  196. package/dist/{spans-XDUFeTzC.mjs.map → spans-BE-EjlZK.mjs.map} +1 -1
  197. package/dist/sql-BGjAsoBE.mjs +2 -0
  198. package/dist/sql-BGjAsoBE.mjs.map +1 -0
  199. package/dist/{sql-Dl6nykFV.mjs → sql-CFxGrk3K.mjs} +2 -2
  200. package/dist/{sql-Dl6nykFV.mjs.map → sql-CFxGrk3K.mjs.map} +1 -1
  201. package/dist/{sql-BVZ8QefY.d.mts → sql-CXtSIPzy.d.mts} +11 -5
  202. package/dist/sql.d.mts +1 -1
  203. package/dist/sql.mjs +1 -1
  204. package/dist/{sqlite-adapter-Ad0d-m2t.mjs → sqlite-adapter-fIbNDvwO.mjs} +2 -2
  205. package/dist/{sqlite-adapter-Ad0d-m2t.mjs.map → sqlite-adapter-fIbNDvwO.mjs.map} +1 -1
  206. package/dist/{sqlite-utils-BRvbmlQ1.mjs → sqlite-utils-DcQct689.mjs} +2 -2
  207. package/dist/{sqlite-utils-BRvbmlQ1.mjs.map → sqlite-utils-DcQct689.mjs.map} +1 -1
  208. package/dist/sqlite3.d.mts +1 -1
  209. package/dist/sqlite3.mjs +1 -1
  210. package/dist/{standard-sql-qLcQyCtK.mjs → standard-sql-Bsf5nrla.mjs} +3 -3
  211. package/dist/standard-sql-Bsf5nrla.mjs.map +1 -0
  212. package/dist/surrealdb.d.mts +2 -2
  213. package/dist/surrealdb.mjs +1 -1
  214. package/dist/surrealdb.mjs.map +1 -1
  215. package/dist/{surrealql-C1dp1sWw.mjs → surrealql-DY7sgVnJ.mjs} +2 -2
  216. package/dist/{surrealql-C1dp1sWw.mjs.map → surrealql-DY7sgVnJ.mjs.map} +1 -1
  217. package/dist/{to-many-BybuKQM1.mjs → to-many-DiP6cOSQ.mjs} +2 -2
  218. package/dist/{to-many-BybuKQM1.mjs.map → to-many-DiP6cOSQ.mjs.map} +1 -1
  219. package/dist/{unit-BhHbZyuJ.mjs → unit-CSaAB0su.mjs} +2 -2
  220. package/dist/{unit-BhHbZyuJ.mjs.map → unit-CSaAB0su.mjs.map} +1 -1
  221. package/dist/{unit-words-CT0yeqfZ.mjs → unit-words-BGMVZ1MX.mjs} +2 -2
  222. package/dist/{unit-words-CT0yeqfZ.mjs.map → unit-words-BGMVZ1MX.mjs.map} +1 -1
  223. package/dist/{utils-CpAojrCj.mjs → utils-BLlgSQIo.mjs} +2 -2
  224. package/dist/{utils-CpAojrCj.mjs.map → utils-BLlgSQIo.mjs.map} +1 -1
  225. package/dist/validation-D0LG854o.mjs +2 -0
  226. package/dist/validation-D0LG854o.mjs.map +1 -0
  227. package/dist/validation.d.mts +1 -1
  228. package/dist/validation.mjs +1 -1
  229. package/dist/{validator-CZLW7aR3.mjs → validator-CDYlO9HV.mjs} +2 -2
  230. package/dist/{validator-CZLW7aR3.mjs.map → validator-CDYlO9HV.mjs.map} +1 -1
  231. package/dist/{values-B4aj1i1f.mjs → values-Byqn5wAh.mjs} +2 -2
  232. package/dist/{values-B4aj1i1f.mjs.map → values-Byqn5wAh.mjs.map} +1 -1
  233. package/dist/version-B_ZLWzLW.mjs +2 -0
  234. package/dist/{version-CXGIA82S.mjs.map → version-B_ZLWzLW.mjs.map} +1 -1
  235. package/package.json +35 -35
  236. package/dist/client-DRpX3-vw.mjs +0 -2
  237. package/dist/client-DRpX3-vw.mjs.map +0 -1
  238. package/dist/error-mapping-B1-IWkCQ.mjs +0 -2
  239. package/dist/error-mapping-B1-IWkCQ.mjs.map +0 -1
  240. package/dist/every-tOgQmaIE.mjs +0 -2
  241. package/dist/execution-context-BXpcbyPe.mjs +0 -2
  242. package/dist/execution-context-BXpcbyPe.mjs.map +0 -1
  243. package/dist/geo-area-codec-mHrM3b9A.mjs +0 -2
  244. package/dist/identifiers-s00pGES8.mjs +0 -2
  245. package/dist/identifiers-s00pGES8.mjs.map +0 -1
  246. package/dist/judge-words-CzUyXtJ6.mjs +0 -2
  247. package/dist/judge-words-CzUyXtJ6.mjs.map +0 -1
  248. package/dist/methods-part-ZY0f2AV_.mjs +0 -2
  249. package/dist/methods-part-ZY0f2AV_.mjs.map +0 -1
  250. package/dist/mysql-adapter-C69j1sKh.mjs +0 -2
  251. package/dist/mysql-adapter-C69j1sKh.mjs.map +0 -1
  252. package/dist/pending-operation-C_eOFOBE.mjs +0 -2
  253. package/dist/pending-operation-C_eOFOBE.mjs.map +0 -1
  254. package/dist/postgres-adapter-Dlr3ZWd7.mjs +0 -2
  255. package/dist/postgres-adapter-Dlr3ZWd7.mjs.map +0 -1
  256. package/dist/postgres-result-DF6DmW3r.mjs +0 -2
  257. package/dist/postgres-result-DF6DmW3r.mjs.map +0 -1
  258. package/dist/query-BZVHfA0s.mjs +0 -2
  259. package/dist/query-BZVHfA0s.mjs.map +0 -1
  260. package/dist/scalar-BHCh7aUz.mjs +0 -4
  261. package/dist/scalar-BHCh7aUz.mjs.map +0 -1
  262. package/dist/schema-BYA-_bpk.mjs.map +0 -1
  263. package/dist/schema-introspection-D0f8cti4.mjs +0 -6
  264. package/dist/schema-introspection-D0f8cti4.mjs.map +0 -1
  265. package/dist/select-assembly-DVI7d3tf.mjs +0 -2
  266. package/dist/select-assembly-DVI7d3tf.mjs.map +0 -1
  267. package/dist/sql-3o4DOKm9.mjs +0 -2
  268. package/dist/sql-3o4DOKm9.mjs.map +0 -1
  269. package/dist/standard-sql-qLcQyCtK.mjs.map +0 -1
  270. package/dist/validation-CYaJ8ndO.mjs +0 -2
  271. package/dist/validation-CYaJ8ndO.mjs.map +0 -1
  272. package/dist/version-CXGIA82S.mjs +0 -2
@@ -1 +1 @@
1
- {"version":3,"file":"geo-area-codec-mHrM3b9A.mjs","names":["latitude","last","north"],"sources":["../src/validation/primitives/geo-area-codec.ts"],"sourcesContent":["import type { ValidationResult, VibSchema } from \"../types\";\nimport { geoLatitude, geoLongitude, validateGeoPoint } from \"./geo-point-codec\";\nimport {\n GEO_BOUNDS_KEYS,\n GEO_POLYGON_MIN_RING_POINTS,\n type GeoArea,\n type GeoBounds,\n type GeoPoint,\n type GeoPolygon,\n} from \"./geo-values\";\nimport {\n createSchema,\n fail,\n ok,\n validateArray,\n validateSchema,\n} from \"./helpers\";\nimport { object } from \"./object\";\nimport { optional } from \"./optional\";\n\nexport type { GeoArea, GeoBounds, GeoPolygon } from \"./geo-values\";\n\nconst OUTWARD_BOUND_DEGREES = 1e-10;\n\n/** The fixed spherical Earth model shared by portable GeoPoint distance SQL. */\nexport const GEO_POINT_EARTH_RADIUS_METERS = 6_371_008.8;\n\n/**\n * Construct the smallest conservative latitude/longitude rectangle around a\n * trusted spherical distance cap. The exact distance predicate remains the\n * membership owner; this rectangle is only an index-friendly superset.\n */\nexport function geoBoundsForDistance(\n point: GeoPoint,\n meters: number\n): GeoBounds {\n if (meters <= 0) {\n return {\n south: point.latitude,\n west: point.longitude,\n north: point.latitude,\n east: point.longitude,\n };\n }\n\n const angularRadius = meters / GEO_POINT_EARTH_RADIUS_METERS;\n if (angularRadius >= Math.PI) {\n return { south: -90, west: -180, north: 90, east: 180 };\n }\n\n const latitudeRadians = (point.latitude * Math.PI) / 180;\n const latitudeDelta = (angularRadius * 180) / Math.PI;\n const south = Math.max(\n -90,\n point.latitude - latitudeDelta - OUTWARD_BOUND_DEGREES\n );\n const north = Math.min(\n 90,\n point.latitude + latitudeDelta + OUTWARD_BOUND_DEGREES\n );\n if (south === -90 || north === 90) {\n return { south, west: -180, north, east: 180 };\n }\n\n const longitudeDelta =\n (Math.asin(\n Math.min(1, Math.sin(angularRadius) / Math.cos(latitudeRadians))\n ) *\n 180) /\n Math.PI +\n OUTWARD_BOUND_DEGREES;\n return {\n south,\n west: normalizeLongitude(point.longitude - longitudeDelta),\n north,\n east: normalizeLongitude(point.longitude + longitudeDelta),\n };\n}\n\nfunction normalizeLongitude(longitude: number): number {\n return ((((longitude + 180) % 360) + 360) % 360) - 180;\n}\n\nconst boundsRecord = object(\n {\n [GEO_BOUNDS_KEYS[0]]: geoLatitude,\n [GEO_BOUNDS_KEYS[1]]: geoLongitude,\n [GEO_BOUNDS_KEYS[2]]: geoLatitude,\n [GEO_BOUNDS_KEYS[3]]: geoLongitude,\n },\n { partial: false }\n);\n\nexport function validateGeoBounds(value: unknown): ValidationResult<GeoBounds> {\n const bounds = validateSchema(boundsRecord, value);\n if (bounds.issues) return bounds;\n // An inverted rectangle is no database error: the latitude arm of\n // withinBounds (adapters/shared/geo-point.ts) would silently match nothing.\n if (bounds.value.south > bounds.value.north) {\n return fail(\"GeoBounds south must be less than or equal to north\", [\n \"south\",\n ]);\n }\n return bounds;\n}\n\n/**\n * A ring is its vertices in input order, at least GEO_POLYGON_MIN_RING_POINTS\n * of them: the JSON Schema states that minimum, and closedRing\n * (adapters/shared/geo-point.ts) reads the first vertex of every ring. The\n * count is judged before any vertex, so a short ring reports its length.\n */\nfunction validateRing(value: unknown): ValidationResult<GeoPoint[]> {\n const members = validateArray(value, ok);\n if (members.issues) return members;\n if (members.value.length < GEO_POLYGON_MIN_RING_POINTS) {\n return fail(\n `A GeoPolygon ring needs at least ${GEO_POLYGON_MIN_RING_POINTS} vertices`\n );\n }\n return validateArray(members.value, validateGeoPoint);\n}\n\nconst polygonRecord = object(\n {\n outer: createSchema(\"array\", validateRing),\n holes: optional(\n createSchema(\"array\", (value) => validateArray(value, validateRing))\n ),\n },\n { partial: false }\n);\n\n/*\n * Polygon geometry, judged after the record walker admitted the shape.\n * VibORM reads an edge as the great-circle arc between its vertices, so\n * crossings, touches and containment are judged on the unit sphere, never on\n * straight longitude/latitude lines, and the polygon is the side of its outer\n * ring away from both poles.\n *\n * Refused as having no single meaning on that reading: a ring crossing,\n * touching or retracing itself, a ring of zero area, a hole not strictly\n * inside its outer ring, holes touching or overlapping.\n *\n * DOMAIN CHOICES, each made for the reason given, not a property every valid\n * polygon lacks. A new refusal needs a reason of this kind; \"invalid\n * geometry\" is not one.\n * - Resolution, TOLERANCE (1e-9 degrees): exact tests on float64 vectors need\n * a margin for rounding, one for every ring size. Within it a point is on\n * what it touches: rings closer than it touch and are refused, and an edge\n * shorter than it is a repeated vertex.\n * - Near-antipodal edges, NEAREST_ANTIPODE (0.01 degrees): nearer to\n * antipodal, one float64 step of a written coordinate turns the edge's\n * great circle by more than a third of TOLERANCE, so the coordinates do not\n * fix the edge; it is refused.\n * - Poles: a vertex within TOLERANCE of a pole has no longitude, and a ring\n * winding around a pole or running over both has no side away from both;\n * both are refused. An edge whose longitudes differ by exactly 180 degrees\n * runs over the pole on its vertices' side, and is admitted.\n *\n * A valid polygon is not refused because a database reads it differently:\n * MySQL draws edges on the ellipsoid, PostGIS misreads some rings reaching\n * across all three coordinate planes (docs/content/docs/schema/scalars/\n * point.mdx, \"How each database reads a polygon\", gives the measured\n * differences).\n */\n\ntype Vector = readonly [x: number, y: number, z: number];\n\n/** One ring vertex, its longitude unwrapped past ±180 along the ring. */\ninterface UnwrappedPoint {\n /**\n * The longitude unwrapped: it records how the ring travels (the edges'\n * directions, the area's lunes), never where the vertex lies.\n */\n readonly longitude: number;\n readonly latitude: number;\n /** The longitude as written, where `sweep` places it. */\n readonly written: number;\n /** The vertex on the unit sphere, from its written coordinates. */\n readonly vector: Vector;\n}\n\n/** One ring edge: the great-circle arc from `from` to `to`. */\ninterface Arc {\n readonly from: UnwrappedPoint;\n readonly to: UnwrappedPoint;\n readonly start: Vector;\n readonly end: Vector;\n /** The unit normal of the arc's great circle, start × end. */\n readonly normal: Vector;\n /**\n * The pole the arc runs over, when its longitudes differ by exactly 180\n * degrees: it rises along one meridian and falls along the other.\n */\n readonly pole: Vector | undefined;\n}\n\n/** A ring's arcs; a ring is refused before it could have fewer than two. */\ntype Ring = readonly [Arc, ...Arc[]];\n\nconst RADIANS = Math.PI / 180;\n/**\n * An angle of 1e-9 degrees, about 0.1 mm: a point this near an arc is on it,\n * and an edge this short is a repeated vertex. It is VibORM's resolution, a\n * domain choice (above), at every ring size: a smaller feature reads as a\n * touch or a repeated vertex, so a ring needs no size bound of its own, and a\n * vertex needs no pole clearance. How exactly rings are judged above it is\n * measured in the guard-ownership ledger's D2 addendum.\n */\nconst TOLERANCE = 1e-9 * RADIANS;\n/**\n * The chord between an edge's end and the antipode of its start below which\n * the edge is refused: 0.01 degrees, a domain choice (above). Two antipodal\n * points lie on every great circle through them, and near the antipode the\n * circle an edge takes turns by up to about 3e-12 / d degrees when a written\n * coordinate moves by one float64 step, d degrees from antipodal (measured in\n * the ledger's D2 addendum, \"Near-antipodal edge\"). From 0.01 degrees out the\n * edge's path is fixed to a third of TOLERANCE; nearer, the written\n * coordinates do not decide on which side of it a point lies.\n */\nconst NEAREST_ANTIPODE = 2 * Math.sin(0.005 * RADIANS);\n\nfunction toVector(longitude: number, latitude: number): Vector {\n const cosine = Math.cos(latitude * RADIANS);\n return [\n cosine * Math.cos(longitude * RADIANS),\n cosine * Math.sin(longitude * RADIANS),\n Math.sin(latitude * RADIANS),\n ];\n}\n\nfunction dot(first: Vector, second: Vector): number {\n return first[0] * second[0] + first[1] * second[1] + first[2] * second[2];\n}\n\n/**\n * first × second, taken as (first − second) × (first + second) / 2: the same\n * vector, but the difference of two nearby points is exact, so the normal of\n * a short arc keeps its direction; taken plainly it loses it at 1e-7 degrees\n * (the ledger's D2 addendum, \"Cross products from vertex differences\").\n */\nfunction cross(first: Vector, second: Vector): Vector {\n const dx = first[0] - second[0];\n const dy = first[1] - second[1];\n const dz = first[2] - second[2];\n const sx = first[0] + second[0];\n const sy = first[1] + second[1];\n const sz = first[2] + second[2];\n return [\n (dy * sz - dz * sy) / 2,\n (dz * sx - dx * sz) / 2,\n (dx * sy - dy * sx) / 2,\n ];\n}\n\nfunction unit(vector: Vector): Vector {\n const length = Math.hypot(...vector);\n return [vector[0] / length, vector[1] / length, vector[2] / length];\n}\n\nfunction chord(first: Vector, second: Vector): number {\n return Math.hypot(\n first[0] - second[0],\n first[1] - second[1],\n first[2] - second[2]\n );\n}\n\nfunction antipode(vector: Vector): Vector {\n return [-vector[0], -vector[1], -vector[2]];\n}\n\n/** What an edge adds to its end's longitude to take the short way round. */\nfunction shortWay(delta: number): number {\n if (delta > 180) return -360;\n if (delta < -180) return 360;\n return 0;\n}\n\n/** One distinct ring vertex, at its index in the ring. */\ninterface Distinct {\n readonly vertex: GeoPoint;\n readonly index: number;\n readonly vector: Vector;\n}\n\n/**\n * The ring's distinct vertices, closed on the first. A vertex within TOLERANCE\n * of a pole is refused: on the pole it has no longitude, and so no meridian\n * for its edges. A repeated consecutive vertex, the caller's closing vertex\n * included, is admitted as the zero-length edge both databases ignore, and\n * dropped here.\n */\nfunction distinctVertices(\n ring: readonly GeoPoint[],\n path: readonly PropertyKey[]\n): ValidationResult<Distinct[]> {\n const distinct: Distinct[] = [];\n for (const [index, vertex] of ring.entries()) {\n const vector = toVector(vertex.longitude, vertex.latitude);\n if (Math.hypot(vector[0], vector[1]) <= TOLERANCE) {\n return fail(\"A GeoPolygon ring cannot contain a pole\", [...path, index]);\n }\n const last = distinct.at(-1);\n if (!last || chord(last.vector, vector) > TOLERANCE) {\n distinct.push({ vertex, index, vector });\n }\n }\n const [first] = distinct;\n const last = distinct.at(-1);\n if (first && last && chord(last.vector, first.vector) > TOLERANCE) {\n distinct.push(first);\n }\n return ok(distinct);\n}\n\n/**\n * The ring's arcs, each taking the short way round in longitude. An edge\n * whose longitudes differ by exactly 180 degrees has no short way: it runs\n * over the pole on the side of its endpoints' mean latitude, along one great\n * circle, and goes round whichever way leaves the ring no turn.\n */\nfunction ringArcs(\n ring: readonly GeoPoint[],\n path: readonly PropertyKey[]\n): ValidationResult<Ring> {\n const distinct = distinctVertices(ring, path);\n if (distinct.issues) return distinct;\n // The ring's turn in longitude, an edge over a pole taken as written.\n let turn = 0;\n for (const [position, { vertex }] of distinct.value.entries()) {\n const previous = distinct.value[position - 1];\n if (previous) {\n turn += shortWay(vertex.longitude - previous.vertex.longitude);\n }\n }\n const arcs: Arc[] = [];\n let wrap = 0;\n let from: UnwrappedPoint | undefined;\n let overPole: Vector | undefined;\n for (const { vertex, index, vector } of distinct.value) {\n let pole: Vector | undefined;\n if (from) {\n const delta = vertex.longitude - from.written;\n if (Math.abs(delta) === 180) {\n pole = [0, 0, Math.sign(vertex.latitude + from.latitude)];\n if (Math.abs(delta - turn) === 180) wrap -= turn;\n }\n wrap += shortWay(delta);\n }\n const to = {\n longitude: vertex.longitude + wrap,\n latitude: vertex.latitude,\n written: vertex.longitude,\n vector,\n };\n if (from) {\n if (chord(antipode(from.vector), vector) < NEAREST_ANTIPODE) {\n return fail(\n \"A GeoPolygon edge cannot join vertices within 0.01 degrees of antipodal\",\n [...path, index]\n );\n }\n // Over both poles the ring has no side away from both, and no way\n // round that leaves it no turn. Over one pole twice it crosses itself\n // there, which the sweep finds.\n if (pole && overPole && pole[2] !== overPole[2]) {\n return fail(\"A GeoPolygon cannot contain a pole\", [...path]);\n }\n overPole ??= pole;\n arcs.push({\n from,\n to,\n start: from.vector,\n end: vector,\n normal: unit(cross(from.vector, vector)),\n pole,\n });\n }\n from = to;\n }\n // Longitudes that went once around the globe enclose a pole, and the ring\n // then has no side away from both poles.\n if (wrap !== 0) return fail(\"A GeoPolygon cannot contain a pole\", [...path]);\n const [first, ...rest] = arcs;\n // The self-intersection no pair of non-neighbor arcs shows: a ring of at\n // most three arcs on one great circle retraces itself, and a ring of one\n // distinct vertex has no arc at all.\n if (\n !first ||\n (rest.length < 3 &&\n rest.every(({ start }) => Math.abs(side(first, start)) <= TOLERANCE))\n ) {\n return fail(\"A GeoPolygon ring must have non-zero area\", [...path]);\n }\n // Neighbors meet at their shared vertex, which `sweep` excuses, unless\n // one doubles back along the other: such arcs overlap, and the sweep\n // cannot order arcs that overlap.\n let behind = first;\n for (const arc of [...rest, first]) {\n if (onArc(arc.end, behind) || onArc(behind.start, arc)) {\n return fail(\"A GeoPolygon ring cannot self-intersect\", [...path]);\n }\n behind = arc;\n }\n return ok([first, ...rest]);\n}\n\n/** The sine of the point's signed angular distance from the arc's circle. */\nfunction side(arc: Arc, point: Vector): number {\n return dot(arc.normal, point);\n}\n\nfunction onArc(point: Vector, arc: Arc): boolean {\n return (\n Math.abs(side(arc, point)) <= TOLERANCE &&\n dot(cross(arc.start, point), arc.normal) >= -TOLERANCE &&\n dot(cross(point, arc.end), arc.normal) >= -TOLERANCE\n );\n}\n\nfunction opposite(first: number, second: number): boolean {\n return (\n (first > TOLERANCE && second < -TOLERANCE) ||\n (first < -TOLERANCE && second > TOLERANCE)\n );\n}\n\n/**\n * The two arcs cross at one point interior to both: each straddles the\n * other's great circle, and they hold the same one of the two antipodal\n * points where the circles meet. An arc shorter than half a circle holds a\n * point of it when the point lies on the side of the arc's middle, where\n * start + end points; arcs that straddle each other but hold opposite points\n * (a ring reaching across all three coordinate planes has such pairs) are\n * apart.\n */\nfunction crosses(first: Arc, second: Arc): boolean {\n if (\n !(\n opposite(side(first, second.start), side(first, second.end)) &&\n opposite(side(second, first.start), side(second, first.end))\n )\n ) {\n return false;\n }\n const meeting = cross(first.normal, second.normal);\n return (\n dot(meeting, first.start) + dot(meeting, first.end) > 0 ===\n dot(meeting, second.start) + dot(meeting, second.end) > 0\n );\n}\n\nfunction meet(first: Arc, second: Arc): boolean {\n return (\n crosses(first, second) ||\n onArc(first.start, second) ||\n onArc(first.end, second) ||\n onArc(second.start, first) ||\n onArc(second.end, first)\n );\n}\n\n/**\n * One ring of the polygon, and where `sweep` places it among the others:\n * `around` is the innermost ring around it, `inside` whether it lies inside\n * the outer ring, `firstAround` and `firstWithin` the first hole around it\n * and inside it.\n */\ninterface RingNode {\n /** 0 the outer ring, then the holes. */\n readonly index: number;\n /** The ring's index in `holes`, none for the outer ring. */\n readonly hole: number;\n readonly points: GeoPoint[];\n readonly arcs: Ring;\n readonly counterClockwise: boolean;\n around: RingNode | undefined;\n inside: boolean;\n firstAround: number;\n firstWithin: number;\n}\n\n/** An arc of `ring` at `index` along it. */\ninterface Placed {\n readonly arc: Arc;\n readonly ring: RingNode;\n readonly index: number;\n}\n\n/**\n * One stretch of an arc between two meridians, as the sweep orders it, from\n * its west end.\n */\ninterface Stretch {\n readonly placed: Placed;\n readonly west: Vector;\n readonly east: Vector;\n /** The arc's unit normal, turned north. */\n readonly north: Vector;\n /** Whether the arc runs east, so that its normal is `north`. */\n readonly eastward: boolean;\n}\n\n/** An arc along a meridian, which the sweep meets at one longitude. */\ninterface Upright {\n readonly placed: Placed;\n readonly south: Vector;\n readonly north: Vector;\n}\n\ninterface Link {\n previous: Entry | undefined;\n next: Entry | undefined;\n}\n\n/** A stretch in the sweep's south-to-north order, a skip list. */\ninterface Entry {\n readonly stretch: Stretch | undefined;\n readonly links: readonly Link[];\n}\n\nconst LEVELS = 24;\n\nfunction createLinks(height: number): Link[] {\n return Array.from({ length: height }, () => ({\n previous: undefined,\n next: undefined,\n }));\n}\n\n/**\n * Whether `entering` starts south of `resident` on the meridian where it\n * enters the sweep; one starting on the resident is ordered by where it\n * heads. Only neighbors in this order are compared, so the order must only\n * be right between arcs that do not meet.\n */\nfunction below(entering: Stretch, resident: Stretch): boolean {\n const height = dot(resident.north, entering.west);\n if (Math.abs(height) > TOLERANCE) return height < 0;\n return dot(resident.north, entering.east) < 0;\n}\n\n/** The last entry south of `point` on the sweep's meridian, or the head. */\nfunction southOf(head: Entry, point: Vector, level: number): Entry {\n let cursor = head;\n for (let at = level; at >= 0; at -= 1) {\n let next = cursor.links[at]?.next;\n while (next?.stretch && dot(next.stretch.north, point) > TOLERANCE) {\n cursor = next;\n next = cursor.links[at]?.next;\n }\n }\n return cursor;\n}\n\nfunction enter(head: Entry, stretch: Stretch, height: number): Entry {\n const entry: Entry = { stretch, links: createLinks(height) };\n let cursor = head;\n for (let level = LEVELS - 1; level >= 0; level -= 1) {\n let next = cursor.links[level]?.next;\n while (next?.stretch && !below(stretch, next.stretch)) {\n cursor = next;\n next = cursor.links[level]?.next;\n }\n const link = entry.links[level];\n const before = cursor.links[level];\n if (link && before) {\n link.previous = cursor;\n link.next = before.next;\n const after = before.next?.links[level];\n if (after) after.previous = entry;\n before.next = entry;\n }\n }\n return entry;\n}\n\nfunction leave(entry: Entry): void {\n for (const [level, { previous, next }] of entry.links.entries()) {\n const before = previous?.links[level];\n if (before) before.next = next;\n const after = next?.links[level];\n if (after) after.previous = previous;\n }\n}\n\n/** The antimeridian on the equator. */\nconst ANTIMERIDIAN = toVector(180, 0);\n\n/** The point where the arc crosses the antimeridian. */\nfunction atAntimeridian(arc: Arc): Vector {\n const meeting = unit(\n cross(arc.normal, [-ANTIMERIDIAN[1], ANTIMERIDIAN[0], 0])\n );\n return dot(meeting, ANTIMERIDIAN) < 0 ? antipode(meeting) : meeting;\n}\n\n/**\n * At one longitude the arcs over a pole leave first, then the stretches\n * starting there enter, then the arcs along the meridian are walked, then the\n * stretches ending there leave.\n */\ntype Event =\n | { readonly longitude: number; readonly rank: 0 | 3; readonly slot: Slot }\n | { readonly longitude: number; readonly rank: 1; readonly slot: Slot }\n | { readonly longitude: number; readonly rank: 2; readonly upright: Upright };\n\ninterface Slot {\n readonly stretch: Stretch;\n entry: Entry | undefined;\n}\n\n/**\n * The arc's sweep events at its written longitudes, west to east, ±180 read\n * as -180 so that arcs meeting on the antimeridian are in the sweep\n * together: one for an arc along a meridian, else an entry and an exit per\n * stretch, two stretches when the arc crosses the antimeridian, split there.\n */\nfunction arcEvents(placed: Placed): Event[] {\n const { from, to, normal, pole } = placed.arc;\n const first = from.written === 180 ? -180 : from.written;\n const second = to.written === 180 ? -180 : to.written;\n if (first === second) {\n const [south, north] =\n from.latitude < to.latitude ? [from, to] : [to, from];\n const upright = { placed, south: south.vector, north: north.vector };\n return [{ longitude: first, rank: 2, upright }];\n }\n const eastward = from.longitude < to.longitude;\n const [west, east] = eastward ? [from, to] : [to, from];\n const north: Vector = eastward\n ? normal\n : [-normal[0], -normal[1], -normal[2]];\n const [low, high] = eastward ? [first, second] : [second, first];\n if (pole) return polarEvents(placed, pole, north, eastward, low, high);\n const span = (start: number, end: number, point: Vector): Event[] => {\n const slot = {\n stretch: { placed, west: point, east: east.vector, north, eastward },\n entry: undefined,\n };\n return [\n { longitude: start, rank: 1, slot },\n { longitude: end, rank: 3, slot },\n ];\n };\n return low < high\n ? span(low, high, west.vector)\n : [\n ...span(low, 180, west.vector),\n ...span(-180, high, atAntimeridian(placed.arc)),\n ];\n}\n\n/**\n * The sweep events of an arc over a pole: an arc along each of its meridians,\n * from its vertex to the pole, and between them a stretch at the pole, beyond\n * every other arc crossing those longitudes. The stretch keeps the arc's\n * circle, which has every point of the meridians between on its far side\n * from the pole. It leaves before the stretches starting on the arc's last\n * meridian enter, since the arc runs along that meridian there, which its\n * walk there covers.\n */\nfunction polarEvents(\n placed: Placed,\n pole: Vector,\n north: Vector,\n eastward: boolean,\n low: number,\n high: number\n): Event[] {\n const walks = [placed.arc.from, placed.arc.to].map(\n ({ written, vector }): Event => ({\n longitude: written === 180 ? -180 : written,\n rank: 2,\n upright: {\n placed,\n south: pole[2] > 0 ? vector : pole,\n north: pole[2] > 0 ? pole : vector,\n },\n })\n );\n const across = (start: number, end: number): Event[] => {\n const slot = {\n stretch: { placed, west: pole, east: pole, north, eastward },\n entry: undefined,\n };\n return [\n { longitude: start, rank: 1, slot },\n { longitude: end, rank: 0, slot },\n ];\n };\n if (low < high) return [...walks, ...across(low, high)];\n return [\n ...walks,\n ...across(low, 180),\n ...(high > -180 ? across(-180, high) : []),\n ];\n}\n\n/**\n * The point's latitude, in radians, which orders points on one meridian. Its\n * z coordinate alone does not: z rounds to ±1 within about 6e-7 degrees of a\n * pole, where rings arriving together would tie.\n */\nfunction latitude(point: Vector): number {\n return Math.atan2(point[2], Math.hypot(point[0], point[1]));\n}\n\n/**\n * A ring on the meridian where the sweep first meets it, and the arc of\n * another ring first north of it there, if any.\n */\ninterface Placement {\n readonly ring: RingNode;\n readonly north: Stretch | undefined;\n}\n\ntype Swept =\n | { readonly meeting: readonly [Placed, Placed] }\n | { readonly meeting?: undefined; readonly placements: Placement[] };\n\n/**\n * The first two arcs found meeting that `apart` does not excuse, by a sweep\n * from the antimeridian eastward that keeps the arcs it crosses in\n * south-to-north order and compares each only with its neighbors in it\n * (Shamos and Hoey): two arcs that meet are neighbors just before the\n * westernmost meeting, so admission takes expected n log n time in the arc\n * count however the arcs lie. At each longitude the arcs starting there enter\n * first; then each arc along that meridian is compared with the arcs crossing\n * its span, found by position; then the arcs ending there leave. Two arcs\n * along one meridian need no comparison of their own: where they meet, one\n * ends on the other, and the arc continuing its ring from that end crosses\n * the meridian there (a ring's arcs along one meridian that continue each\n * other end where the last one does, and a ring doubling back along a\n * meridian is refused in `ringArcs`), so the walk along the other one meets\n * it. An arc over a pole is walked along both its meridians, with a stretch\n * at the pole between them (`polarEvents`): two arcs over one pole meet\n * there, where either their stretches are neighbors at the pole or, when\n * their longitudes only touch, one's walk finds the other's stretch.\n *\n * Failing a meeting, where each ring was first met: once the arcs starting\n * on that meridian have entered, the arc north of the ring's northernmost\n * point there, skipping the ring's own arcs through that point. The rings\n * met on one meridian are listed north to south, so every ring is listed\n * after the ring of the arc north of it.\n */\nfunction sweep(\n arcs: readonly Placed[],\n apart: (first: Placed, second: Placed) => boolean\n): Swept {\n const events = arcs.flatMap(arcEvents);\n events.sort(\n (left, right) => left.longitude - right.longitude || left.rank - right.rank\n );\n const head: Entry = { stretch: undefined, links: createLinks(LEVELS) };\n const meeting = (\n first: Placed | undefined,\n second: Placed | undefined\n ): readonly [Placed, Placed] | undefined => {\n if (!(first && second)) return;\n if (apart(first, second) || !meet(first.arc, second.arc)) return;\n return [first, second];\n };\n const placements: Placement[] = [];\n // Each ring met for the first time on the sweep's meridian, with its\n // northernmost entry there so far.\n const arrivals = new Map<RingNode, { entry: Entry; west: Vector }>();\n const placeArrivals = (): void => {\n const arrived = Array.from(arrivals, ([ring, { entry, west }]) => {\n let next = entry.links[0]?.next;\n while (next?.stretch?.placed.ring === ring) next = next.links[0]?.next;\n return { ring, height: latitude(west), north: next?.stretch };\n });\n arrived.sort((left, right) => right.height - left.height);\n // One push per ring: a spread would pass every ring arriving on this\n // meridian as a call argument, past the engine's argument limit.\n for (const { ring, north } of arrived) placements.push({ ring, north });\n arrivals.clear();\n };\n const met = new Set<RingNode>();\n for (const [index, event] of events.entries()) {\n if (event.rank === 1) {\n // A skip list's heights are coin flips the input cannot know: heights\n // a polygon could predict let it keep its long-lived arcs low and make\n // every search walk them one by one. The verdict does not depend on\n // them: arcs that meet are neighbors before they meet at any height.\n const height = 1 + Math.floor(-Math.log2(1 - Math.random()));\n const entry = enter(head, event.slot.stretch, Math.min(LEVELS, height));\n event.slot.entry = entry;\n const [link] = entry.links;\n const found =\n meeting(link?.previous?.stretch?.placed, entry.stretch?.placed) ??\n meeting(entry.stretch?.placed, link?.next?.stretch?.placed);\n if (found) return { meeting: found };\n const { placed, west } = event.slot.stretch;\n const top = arrivals.get(placed.ring);\n if (\n !met.has(placed.ring) ||\n (top && latitude(west) > latitude(top.west))\n ) {\n met.add(placed.ring);\n arrivals.set(placed.ring, { entry, west });\n }\n const next = events[index + 1];\n if (next?.rank !== 1 || next.longitude !== event.longitude) {\n placeArrivals();\n }\n } else if (event.rank === 2) {\n const { upright } = event;\n // Every arc crossing the meridian within the span meets this one, so\n // the walk stops at the first not excused, or past the north end.\n let entry: Entry | undefined = southOf(head, upright.south, LEVELS - 1);\n entry = entry.stretch ? entry : entry.links[0]?.next;\n while (entry?.stretch) {\n const found = meeting(upright.placed, entry.stretch.placed);\n if (found) return { meeting: found };\n if (dot(entry.stretch.north, upright.north) < -TOLERANCE) break;\n entry = entry.links[0]?.next;\n }\n } else if (event.slot.entry) {\n const [link] = event.slot.entry.links;\n leave(event.slot.entry);\n const found = meeting(\n link?.previous?.stretch?.placed,\n link?.next?.stretch?.placed\n );\n if (found) return { meeting: found };\n }\n }\n return { placements };\n}\n\n/**\n * The ring's signed area in steradians, positive when counterclockwise: the\n * sum of the triangles each arc makes with the north pole (Van Oosterom and\n * Strackee), taken through the south pole's triangle and the lune between the\n * arc's meridians when the arc lies nearer the south pole, where the north\n * pole's triangle loses its precision. The lunes' longitudes telescope, so\n * each run of such arcs adds the longitude from its start to its end: a ring\n * near the south pole is one run, and its lunes add exactly nothing, where\n * summed arc by arc their rounding would outweigh its area. No admitted ring\n * has a pole inside it (`wrap` in `ringArcs`), so this is the area on the\n * ring's pole-free side, and its sign says on which side of its arcs that\n * area lies.\n */\nfunction signedArea(ring: Ring): number {\n let sum = 0;\n let lune = 0;\n let run: number | undefined;\n let end = 0;\n for (const arc of ring) {\n const turn = cross(arc.start, arc.end)[2];\n const along = 1 + dot(arc.start, arc.end);\n const lift = arc.start[2] + arc.end[2];\n if (lift >= 0) {\n sum += 2 * Math.atan2(turn, along + lift);\n if (run !== undefined) lune += arc.from.longitude - run;\n run = undefined;\n } else {\n sum += 2 * Math.atan2(-turn, along - lift);\n run ??= arc.from.longitude;\n }\n end = arc.to.longitude;\n }\n if (run !== undefined) lune += end - run;\n return sum + 2 * lune * RADIANS;\n}\n\n/*\n * A hole must lie strictly inside its outer ring, and holes must neither touch\n * nor overlap: a hole reaching outside its outer ring, or a point in two\n * holes, has no single reading (the ledger's D2 addendum tabulates what each\n * database answered). A touch is refused with them: a hole written touching a\n * straight parallel edge crosses that edge's arc.\n */\n\n/**\n * Kept output normalization, not a refusal: the GeoJSON that withinPolygon\n * binds (adapters/databases/{postgres,mysql}) always carries a counterclockwise\n * outer ring and clockwise holes, because neither database's reading of ring\n * orientation is proven portable (v1-public-api-geopoint-plan.md).\n */\nfunction wound(\n ring: GeoPoint[],\n counterClockwise: boolean,\n wanted: boolean\n): GeoPoint[] {\n return counterClockwise === wanted ? ring : ring.reverse();\n}\n\nfunction ringPath(ring: number): PropertyKey[] {\n return ring === 0 ? [\"outer\"] : [\"holes\", ring - 1];\n}\n\nfunction ringNode(points: GeoPoint[], arcs: Ring, index: number): RingNode {\n return {\n index,\n hole: index === 0 ? Number.POSITIVE_INFINITY : index - 1,\n points,\n arcs,\n counterClockwise: signedArea(arcs) > 0,\n around: undefined,\n inside: false,\n firstAround: Number.POSITIVE_INFINITY,\n firstWithin: Number.POSITIVE_INFINITY,\n };\n}\n\n/**\n * The walker admits the polygon's shape (exact keys, finite in-range\n * vertices, at least three per ring); the geometry then refuses the polygons\n * with no single meaning or outside the domain choices (above): each ring\n * alone, then the rings together.\n */\nexport function validateGeoPolygon(\n value: unknown\n): ValidationResult<GeoPolygon> {\n const polygon = validateSchema(polygonRecord, value);\n if (polygon.issues) return polygon;\n const outer = ringArcs(polygon.value.outer, [\"outer\"]);\n if (outer.issues) return outer;\n const shell = ringNode(polygon.value.outer, outer.value, 0);\n const holes: RingNode[] = [];\n for (const [index, points] of (polygon.value.holes ?? []).entries()) {\n const hole = ringArcs(points, [\"holes\", index]);\n if (hole.issues) return hole;\n holes.push(ringNode(points, hole.value, index + 1));\n }\n const placed = [shell, ...holes].flatMap((ring) =>\n ring.arcs.map((arc, index) => ({ arc, ring, index }))\n );\n // Neighbors along a ring meet at their shared vertex; an arc over a pole\n // meets itself where its walks find its stretch.\n const swept = sweep(\n placed,\n (first, second) =>\n first.ring === second.ring &&\n [0, 1, first.ring.arcs.length - 1].includes(\n Math.abs(first.index - second.index)\n )\n );\n if (swept.meeting) {\n const [first, second] = swept.meeting;\n const later = ringPath(Math.max(first.ring.index, second.ring.index));\n // A ring meeting itself has no single reading (the ledger's D2 table:\n // the bowtie and the ring past a whole turn over itself).\n if (first.ring === second.ring) {\n return fail(\"A GeoPolygon ring cannot self-intersect\", later);\n }\n return Math.min(first.ring.index, second.ring.index) === 0\n ? fail(\"A GeoPolygon hole must be strictly inside its outer ring\", later)\n : fail(\"GeoPolygon holes cannot touch or overlap\", later);\n }\n // No two rings meet, so where the sweep first met a ring places all of it:\n // inside the ring of the arc north of it when that arc has its ring's\n // interior to the south (a counterclockwise ring's interior is on the left\n // of its arcs), else beside that ring, in the ring around it, which the\n // sweep placed first.\n for (const { ring, north } of swept.placements) {\n const other = north?.placed.ring;\n const around =\n other === undefined || other.counterClockwise !== north?.eastward\n ? other\n : other.around;\n ring.around = around;\n ring.inside = around !== undefined && (around.index === 0 || around.inside);\n ring.firstAround = around\n ? Math.min(around.hole, around.firstAround)\n : Number.POSITIVE_INFINITY;\n }\n // Reversed in place, the list's last use: every ring now comes before the\n // ring around it, which collects the first hole within it.\n for (const { ring } of swept.placements.reverse()) {\n const { around } = ring;\n if (around) {\n around.firstWithin = Math.min(\n around.firstWithin,\n ring.hole,\n ring.firstWithin\n );\n }\n }\n for (const { hole, inside, firstAround, firstWithin } of holes) {\n if (!inside) {\n return fail(\"A GeoPolygon hole must be strictly inside its outer ring\", [\n \"holes\",\n hole,\n ]);\n }\n if (Math.min(firstAround, firstWithin) < hole) {\n return fail(\"GeoPolygon holes cannot touch or overlap\", [\"holes\", hole]);\n }\n }\n const wide = wound(shell.points, shell.counterClockwise, true);\n const cut = holes.map(({ points, counterClockwise }) =>\n wound(points, counterClockwise, false)\n );\n // An empty and an absent holes list emit the same GeoJSON; one spelling\n // keeps them one validated argument, and so one cache key.\n return ok(cut.length > 0 ? { outer: wide, holes: cut } : { outer: wide });\n}\n\nconst areaRecord = object({\n bounds: createSchema(\"object\", validateGeoBounds),\n polygon: createSchema(\"object\", validateGeoPolygon),\n});\n\nexport function validateGeoArea(value: unknown): ValidationResult<GeoArea> {\n const area = validateSchema(areaRecord, value);\n if (area.issues) return area;\n const { bounds, polygon } = area.value;\n // Exactly one variant: buildGeoPointWithin (query-engine/builders/\n // geo-point-builder.ts) branches on `\"bounds\" in area`, so a second variant\n // would be dropped silently and a missing one would reach geoPolygonJson as\n // undefined and throw a TypeError instead of a database error.\n if (bounds && !polygon) return ok({ bounds });\n if (polygon && !bounds) return ok({ polygon });\n return fail(\"Expected GeoArea with exactly one of bounds or polygon\");\n}\n\nexport function geoAreaSchema(): VibSchema<GeoArea, GeoArea> {\n return createSchema(\"geo_area\", validateGeoArea);\n}\n"],"mappings":"wKAsBA,MAAM,EAAwB,MAGjB,EAAgC,UAO7C,SAAgB,qBACd,EACA,EACW,CACX,GAAI,GAAU,EACZ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primitives/geo-area-codec.ts"],"sourcesContent":["import type { ValidationResult, VibSchema } from \"../types\";\nimport { geoLatitude, geoLongitude, validateGeoPoint } from \"./geo-point-codec\";\nimport {\n GEO_BOUNDS_KEYS,\n GEO_POLYGON_MIN_RING_POINTS,\n type GeoArea,\n type GeoBounds,\n type GeoPoint,\n type GeoPolygon,\n} from \"./geo-values\";\nimport {\n createSchema,\n fail,\n ok,\n validateArray,\n validateSchema,\n} from \"./helpers\";\nimport { object } from \"./object\";\nimport { optional } from \"./optional\";\n\nexport type { GeoArea, GeoBounds, GeoPolygon } from \"./geo-values\";\n\nconst OUTWARD_BOUND_DEGREES = 1e-10;\n\n/** The fixed spherical Earth model shared by portable GeoPoint distance SQL. */\nexport const GEO_POINT_EARTH_RADIUS_METERS = 6_371_008.8;\n\n/**\n * Construct the smallest conservative latitude/longitude rectangle around a\n * trusted spherical distance cap. The exact distance predicate remains the\n * membership owner; this rectangle is only an index-friendly superset.\n */\nexport function geoBoundsForDistance(\n point: GeoPoint,\n meters: number\n): GeoBounds {\n if (meters <= 0) {\n return {\n south: point.latitude,\n west: point.longitude,\n north: point.latitude,\n east: point.longitude,\n };\n }\n\n const angularRadius = meters / GEO_POINT_EARTH_RADIUS_METERS;\n if (angularRadius >= Math.PI) {\n return { south: -90, west: -180, north: 90, east: 180 };\n }\n\n const latitudeRadians = (point.latitude * Math.PI) / 180;\n const latitudeDelta = (angularRadius * 180) / Math.PI;\n const south = Math.max(\n -90,\n point.latitude - latitudeDelta - OUTWARD_BOUND_DEGREES\n );\n const north = Math.min(\n 90,\n point.latitude + latitudeDelta + OUTWARD_BOUND_DEGREES\n );\n if (south === -90 || north === 90) {\n return { south, west: -180, north, east: 180 };\n }\n\n const longitudeDelta =\n (Math.asin(\n Math.min(1, Math.sin(angularRadius) / Math.cos(latitudeRadians))\n ) *\n 180) /\n Math.PI +\n OUTWARD_BOUND_DEGREES;\n return {\n south,\n west: normalizeLongitude(point.longitude - longitudeDelta),\n north,\n east: normalizeLongitude(point.longitude + longitudeDelta),\n };\n}\n\nfunction normalizeLongitude(longitude: number): number {\n return ((((longitude + 180) % 360) + 360) % 360) - 180;\n}\n\nconst boundsRecord = object(\n {\n [GEO_BOUNDS_KEYS[0]]: geoLatitude,\n [GEO_BOUNDS_KEYS[1]]: geoLongitude,\n [GEO_BOUNDS_KEYS[2]]: geoLatitude,\n [GEO_BOUNDS_KEYS[3]]: geoLongitude,\n },\n { partial: false }\n);\n\nexport function validateGeoBounds(value: unknown): ValidationResult<GeoBounds> {\n const bounds = validateSchema(boundsRecord, value);\n if (bounds.issues) return bounds;\n // An inverted rectangle is no database error: the latitude arm of\n // withinBounds (adapters/shared/geo-point.ts) would silently match nothing.\n if (bounds.value.south > bounds.value.north) {\n return fail(\"GeoBounds south must be less than or equal to north\", [\n \"south\",\n ]);\n }\n return bounds;\n}\n\n/**\n * A ring is its vertices in input order, at least GEO_POLYGON_MIN_RING_POINTS\n * of them: the JSON Schema states that minimum, and closedRing\n * (adapters/shared/geo-point.ts) reads the first vertex of every ring. The\n * count is judged before any vertex, so a short ring reports its length.\n */\nfunction validateRing(value: unknown): ValidationResult<GeoPoint[]> {\n const members = validateArray(value, ok);\n if (members.issues) return members;\n if (members.value.length < GEO_POLYGON_MIN_RING_POINTS) {\n return fail(\n `A GeoPolygon ring needs at least ${GEO_POLYGON_MIN_RING_POINTS} vertices`\n );\n }\n return validateArray(members.value, validateGeoPoint);\n}\n\nconst polygonRecord = object(\n {\n outer: createSchema(\"array\", validateRing),\n holes: optional(\n createSchema(\"array\", (value) => validateArray(value, validateRing))\n ),\n },\n { partial: false }\n);\n\n/*\n * Polygon geometry, judged after the record walker admitted the shape.\n * VibORM reads an edge as the great-circle arc between its vertices, so\n * crossings, touches and containment are judged on the unit sphere, never on\n * straight longitude/latitude lines, and the polygon is the side of its outer\n * ring away from both poles.\n *\n * Refused as having no single meaning on that reading: a ring crossing,\n * touching or retracing itself, a ring of zero area, a hole not strictly\n * inside its outer ring, holes touching or overlapping.\n *\n * DOMAIN CHOICES, each made for the reason given, not a property every valid\n * polygon lacks. A new refusal needs a reason of this kind; \"invalid\n * geometry\" is not one.\n * - Resolution, TOLERANCE (1e-9 degrees): exact tests on float64 vectors need\n * a margin for rounding, one for every ring size. Within it a point is on\n * what it touches: rings closer than it touch and are refused, and an edge\n * shorter than it is a repeated vertex.\n * - Near-antipodal edges, NEAREST_ANTIPODE (0.01 degrees): nearer to\n * antipodal, one float64 step of a written coordinate turns the edge's\n * great circle by more than a third of TOLERANCE, so the coordinates do not\n * fix the edge; it is refused.\n * - Poles: a vertex within TOLERANCE of a pole has no longitude, and a ring\n * winding around a pole or running over both has no side away from both;\n * both are refused. An edge whose longitudes differ by exactly 180 degrees\n * runs over the pole on its vertices' side, and is admitted.\n *\n * A valid polygon is not refused because a database reads it differently:\n * MySQL draws edges on the ellipsoid, PostGIS misreads some rings reaching\n * across all three coordinate planes (docs/content/docs/schema/scalars/\n * point.mdx, \"How each database reads a polygon\", gives the measured\n * differences).\n */\n\ntype Vector = readonly [x: number, y: number, z: number];\n\n/** One ring vertex, its longitude unwrapped past ±180 along the ring. */\ninterface UnwrappedPoint {\n /**\n * The longitude unwrapped: it records how the ring travels (the edges'\n * directions, the area's lunes), never where the vertex lies.\n */\n readonly longitude: number;\n readonly latitude: number;\n /** The longitude as written, where `sweep` places it. */\n readonly written: number;\n /** The vertex on the unit sphere, from its written coordinates. */\n readonly vector: Vector;\n}\n\n/** One ring edge: the great-circle arc from `from` to `to`. */\ninterface Arc {\n readonly from: UnwrappedPoint;\n readonly to: UnwrappedPoint;\n readonly start: Vector;\n readonly end: Vector;\n /** The unit normal of the arc's great circle, start × end. */\n readonly normal: Vector;\n /**\n * The pole the arc runs over, when its longitudes differ by exactly 180\n * degrees: it rises along one meridian and falls along the other.\n */\n readonly pole: Vector | undefined;\n}\n\n/** A ring's arcs; a ring is refused before it could have fewer than two. */\ntype Ring = readonly [Arc, ...Arc[]];\n\nconst RADIANS = Math.PI / 180;\n/**\n * An angle of 1e-9 degrees, about 0.1 mm: a point this near an arc is on it,\n * and an edge this short is a repeated vertex. It is VibORM's resolution, a\n * domain choice (above), at every ring size: a smaller feature reads as a\n * touch or a repeated vertex, so a ring needs no size bound of its own, and a\n * vertex needs no pole clearance. How exactly rings are judged above it is\n * measured in the guard-ownership ledger's D2 addendum.\n */\nconst TOLERANCE = 1e-9 * RADIANS;\n/**\n * The chord between an edge's end and the antipode of its start below which\n * the edge is refused: 0.01 degrees, a domain choice (above). Two antipodal\n * points lie on every great circle through them, and near the antipode the\n * circle an edge takes turns by up to about 3e-12 / d degrees when a written\n * coordinate moves by one float64 step, d degrees from antipodal (measured in\n * the ledger's D2 addendum, \"Near-antipodal edge\"). From 0.01 degrees out the\n * edge's path is fixed to a third of TOLERANCE; nearer, the written\n * coordinates do not decide on which side of it a point lies.\n */\nconst NEAREST_ANTIPODE = 2 * Math.sin(0.005 * RADIANS);\n\nfunction toVector(longitude: number, latitude: number): Vector {\n const cosine = Math.cos(latitude * RADIANS);\n return [\n cosine * Math.cos(longitude * RADIANS),\n cosine * Math.sin(longitude * RADIANS),\n Math.sin(latitude * RADIANS),\n ];\n}\n\nfunction dot(first: Vector, second: Vector): number {\n return first[0] * second[0] + first[1] * second[1] + first[2] * second[2];\n}\n\n/**\n * first × second, taken as (first − second) × (first + second) / 2: the same\n * vector, but the difference of two nearby points is exact, so the normal of\n * a short arc keeps its direction; taken plainly it loses it at 1e-7 degrees\n * (the ledger's D2 addendum, \"Cross products from vertex differences\").\n */\nfunction cross(first: Vector, second: Vector): Vector {\n const dx = first[0] - second[0];\n const dy = first[1] - second[1];\n const dz = first[2] - second[2];\n const sx = first[0] + second[0];\n const sy = first[1] + second[1];\n const sz = first[2] + second[2];\n return [\n (dy * sz - dz * sy) / 2,\n (dz * sx - dx * sz) / 2,\n (dx * sy - dy * sx) / 2,\n ];\n}\n\nfunction unit(vector: Vector): Vector {\n const length = Math.hypot(...vector);\n return [vector[0] / length, vector[1] / length, vector[2] / length];\n}\n\nfunction chord(first: Vector, second: Vector): number {\n return Math.hypot(\n first[0] - second[0],\n first[1] - second[1],\n first[2] - second[2]\n );\n}\n\nfunction antipode(vector: Vector): Vector {\n return [-vector[0], -vector[1], -vector[2]];\n}\n\n/** What an edge adds to its end's longitude to take the short way round. */\nfunction shortWay(delta: number): number {\n if (delta > 180) return -360;\n if (delta < -180) return 360;\n return 0;\n}\n\n/** One distinct ring vertex, at its index in the ring. */\ninterface Distinct {\n readonly vertex: GeoPoint;\n readonly index: number;\n readonly vector: Vector;\n}\n\n/**\n * The ring's distinct vertices, closed on the first. A vertex within TOLERANCE\n * of a pole is refused: on the pole it has no longitude, and so no meridian\n * for its edges. A repeated consecutive vertex, the caller's closing vertex\n * included, is admitted as the zero-length edge both databases ignore, and\n * dropped here.\n */\nfunction distinctVertices(\n ring: readonly GeoPoint[],\n path: readonly PropertyKey[]\n): ValidationResult<Distinct[]> {\n const distinct: Distinct[] = [];\n for (const [index, vertex] of ring.entries()) {\n const vector = toVector(vertex.longitude, vertex.latitude);\n if (Math.hypot(vector[0], vector[1]) <= TOLERANCE) {\n return fail(\"A GeoPolygon ring cannot contain a pole\", [...path, index]);\n }\n const last = distinct.at(-1);\n if (!last || chord(last.vector, vector) > TOLERANCE) {\n distinct.push({ vertex, index, vector });\n }\n }\n const [first] = distinct;\n const last = distinct.at(-1);\n if (first && last && chord(last.vector, first.vector) > TOLERANCE) {\n distinct.push(first);\n }\n return ok(distinct);\n}\n\n/**\n * The ring's arcs, each taking the short way round in longitude. An edge\n * whose longitudes differ by exactly 180 degrees has no short way: it runs\n * over the pole on the side of its endpoints' mean latitude, along one great\n * circle, and goes round whichever way leaves the ring no turn.\n */\nfunction ringArcs(\n ring: readonly GeoPoint[],\n path: readonly PropertyKey[]\n): ValidationResult<Ring> {\n const distinct = distinctVertices(ring, path);\n if (distinct.issues) return distinct;\n // The ring's turn in longitude, an edge over a pole taken as written.\n let turn = 0;\n for (const [position, { vertex }] of distinct.value.entries()) {\n const previous = distinct.value[position - 1];\n if (previous) {\n turn += shortWay(vertex.longitude - previous.vertex.longitude);\n }\n }\n const arcs: Arc[] = [];\n let wrap = 0;\n let from: UnwrappedPoint | undefined;\n let overPole: Vector | undefined;\n for (const { vertex, index, vector } of distinct.value) {\n let pole: Vector | undefined;\n if (from) {\n const delta = vertex.longitude - from.written;\n if (Math.abs(delta) === 180) {\n pole = [0, 0, Math.sign(vertex.latitude + from.latitude)];\n if (Math.abs(delta - turn) === 180) wrap -= turn;\n }\n wrap += shortWay(delta);\n }\n const to = {\n longitude: vertex.longitude + wrap,\n latitude: vertex.latitude,\n written: vertex.longitude,\n vector,\n };\n if (from) {\n if (chord(antipode(from.vector), vector) < NEAREST_ANTIPODE) {\n return fail(\n \"A GeoPolygon edge cannot join vertices within 0.01 degrees of antipodal\",\n [...path, index]\n );\n }\n // Over both poles the ring has no side away from both, and no way\n // round that leaves it no turn. Over one pole twice it crosses itself\n // there, which the sweep finds.\n if (pole && overPole && pole[2] !== overPole[2]) {\n return fail(\"A GeoPolygon cannot contain a pole\", [...path]);\n }\n overPole ??= pole;\n arcs.push({\n from,\n to,\n start: from.vector,\n end: vector,\n normal: unit(cross(from.vector, vector)),\n pole,\n });\n }\n from = to;\n }\n // Longitudes that went once around the globe enclose a pole, and the ring\n // then has no side away from both poles.\n if (wrap !== 0) return fail(\"A GeoPolygon cannot contain a pole\", [...path]);\n const [first, ...rest] = arcs;\n // The self-intersection no pair of non-neighbor arcs shows: a ring of at\n // most three arcs on one great circle retraces itself, and a ring of one\n // distinct vertex has no arc at all.\n if (\n !first ||\n (rest.length < 3 &&\n rest.every(({ start }) => Math.abs(side(first, start)) <= TOLERANCE))\n ) {\n return fail(\"A GeoPolygon ring must have non-zero area\", [...path]);\n }\n // Neighbors meet at their shared vertex, which `sweep` excuses, unless\n // one doubles back along the other: such arcs overlap, and the sweep\n // cannot order arcs that overlap.\n let behind = first;\n for (const arc of [...rest, first]) {\n if (onArc(arc.end, behind) || onArc(behind.start, arc)) {\n return fail(\"A GeoPolygon ring cannot self-intersect\", [...path]);\n }\n behind = arc;\n }\n return ok([first, ...rest]);\n}\n\n/** The sine of the point's signed angular distance from the arc's circle. */\nfunction side(arc: Arc, point: Vector): number {\n return dot(arc.normal, point);\n}\n\nfunction onArc(point: Vector, arc: Arc): boolean {\n return (\n Math.abs(side(arc, point)) <= TOLERANCE &&\n dot(cross(arc.start, point), arc.normal) >= -TOLERANCE &&\n dot(cross(point, arc.end), arc.normal) >= -TOLERANCE\n );\n}\n\nfunction opposite(first: number, second: number): boolean {\n return (\n (first > TOLERANCE && second < -TOLERANCE) ||\n (first < -TOLERANCE && second > TOLERANCE)\n );\n}\n\n/**\n * The two arcs cross at one point interior to both: each straddles the\n * other's great circle, and they hold the same one of the two antipodal\n * points where the circles meet. An arc shorter than half a circle holds a\n * point of it when the point lies on the side of the arc's middle, where\n * start + end points; arcs that straddle each other but hold opposite points\n * (a ring reaching across all three coordinate planes has such pairs) are\n * apart.\n */\nfunction crosses(first: Arc, second: Arc): boolean {\n if (\n !(\n opposite(side(first, second.start), side(first, second.end)) &&\n opposite(side(second, first.start), side(second, first.end))\n )\n ) {\n return false;\n }\n const meeting = cross(first.normal, second.normal);\n return (\n dot(meeting, first.start) + dot(meeting, first.end) > 0 ===\n dot(meeting, second.start) + dot(meeting, second.end) > 0\n );\n}\n\nfunction meet(first: Arc, second: Arc): boolean {\n return (\n crosses(first, second) ||\n onArc(first.start, second) ||\n onArc(first.end, second) ||\n onArc(second.start, first) ||\n onArc(second.end, first)\n );\n}\n\n/**\n * One ring of the polygon, and where `sweep` places it among the others:\n * `around` is the innermost ring around it, `inside` whether it lies inside\n * the outer ring, `firstAround` and `firstWithin` the first hole around it\n * and inside it.\n */\ninterface RingNode {\n /** 0 the outer ring, then the holes. */\n readonly index: number;\n /** The ring's index in `holes`, none for the outer ring. */\n readonly hole: number;\n readonly points: GeoPoint[];\n readonly arcs: Ring;\n readonly counterClockwise: boolean;\n around: RingNode | undefined;\n inside: boolean;\n firstAround: number;\n firstWithin: number;\n}\n\n/** An arc of `ring` at `index` along it. */\ninterface Placed {\n readonly arc: Arc;\n readonly ring: RingNode;\n readonly index: number;\n}\n\n/**\n * One stretch of an arc between two meridians, as the sweep orders it, from\n * its west end.\n */\ninterface Stretch {\n readonly placed: Placed;\n readonly west: Vector;\n readonly east: Vector;\n /** The arc's unit normal, turned north. */\n readonly north: Vector;\n /** Whether the arc runs east, so that its normal is `north`. */\n readonly eastward: boolean;\n}\n\n/** An arc along a meridian, which the sweep meets at one longitude. */\ninterface Upright {\n readonly placed: Placed;\n readonly south: Vector;\n readonly north: Vector;\n}\n\ninterface Link {\n previous: Entry | undefined;\n next: Entry | undefined;\n}\n\n/** A stretch in the sweep's south-to-north order, a skip list. */\ninterface Entry {\n readonly stretch: Stretch | undefined;\n readonly links: readonly Link[];\n}\n\nconst LEVELS = 24;\n\nfunction createLinks(height: number): Link[] {\n return Array.from({ length: height }, () => ({\n previous: undefined,\n next: undefined,\n }));\n}\n\n/**\n * Whether `entering` starts south of `resident` on the meridian where it\n * enters the sweep; one starting on the resident is ordered by where it\n * heads. Only neighbors in this order are compared, so the order must only\n * be right between arcs that do not meet.\n */\nfunction below(entering: Stretch, resident: Stretch): boolean {\n const height = dot(resident.north, entering.west);\n if (Math.abs(height) > TOLERANCE) return height < 0;\n return dot(resident.north, entering.east) < 0;\n}\n\n/** The last entry south of `point` on the sweep's meridian, or the head. */\nfunction southOf(head: Entry, point: Vector, level: number): Entry {\n let cursor = head;\n for (let at = level; at >= 0; at -= 1) {\n let next = cursor.links[at]?.next;\n while (next?.stretch && dot(next.stretch.north, point) > TOLERANCE) {\n cursor = next;\n next = cursor.links[at]?.next;\n }\n }\n return cursor;\n}\n\nfunction enter(head: Entry, stretch: Stretch, height: number): Entry {\n const entry: Entry = { stretch, links: createLinks(height) };\n let cursor = head;\n for (let level = LEVELS - 1; level >= 0; level -= 1) {\n let next = cursor.links[level]?.next;\n while (next?.stretch && !below(stretch, next.stretch)) {\n cursor = next;\n next = cursor.links[level]?.next;\n }\n const link = entry.links[level];\n const before = cursor.links[level];\n if (link && before) {\n link.previous = cursor;\n link.next = before.next;\n const after = before.next?.links[level];\n if (after) after.previous = entry;\n before.next = entry;\n }\n }\n return entry;\n}\n\nfunction leave(entry: Entry): void {\n for (const [level, { previous, next }] of entry.links.entries()) {\n const before = previous?.links[level];\n if (before) before.next = next;\n const after = next?.links[level];\n if (after) after.previous = previous;\n }\n}\n\n/** The antimeridian on the equator. */\nconst ANTIMERIDIAN = toVector(180, 0);\n\n/** The point where the arc crosses the antimeridian. */\nfunction atAntimeridian(arc: Arc): Vector {\n const meeting = unit(\n cross(arc.normal, [-ANTIMERIDIAN[1], ANTIMERIDIAN[0], 0])\n );\n return dot(meeting, ANTIMERIDIAN) < 0 ? antipode(meeting) : meeting;\n}\n\n/**\n * At one longitude the arcs over a pole leave first, then the stretches\n * starting there enter, then the arcs along the meridian are walked, then the\n * stretches ending there leave.\n */\ntype Event =\n | { readonly longitude: number; readonly rank: 0 | 3; readonly slot: Slot }\n | { readonly longitude: number; readonly rank: 1; readonly slot: Slot }\n | { readonly longitude: number; readonly rank: 2; readonly upright: Upright };\n\ninterface Slot {\n readonly stretch: Stretch;\n entry: Entry | undefined;\n}\n\n/**\n * The arc's sweep events at its written longitudes, west to east, ±180 read\n * as -180 so that arcs meeting on the antimeridian are in the sweep\n * together: one for an arc along a meridian, else an entry and an exit per\n * stretch, two stretches when the arc crosses the antimeridian, split there.\n */\nfunction arcEvents(placed: Placed): Event[] {\n const { from, to, normal, pole } = placed.arc;\n const first = from.written === 180 ? -180 : from.written;\n const second = to.written === 180 ? -180 : to.written;\n if (first === second) {\n const [south, north] =\n from.latitude < to.latitude ? [from, to] : [to, from];\n const upright = { placed, south: south.vector, north: north.vector };\n return [{ longitude: first, rank: 2, upright }];\n }\n const eastward = from.longitude < to.longitude;\n const [west, east] = eastward ? [from, to] : [to, from];\n const north: Vector = eastward\n ? normal\n : [-normal[0], -normal[1], -normal[2]];\n const [low, high] = eastward ? [first, second] : [second, first];\n if (pole) return polarEvents(placed, pole, north, eastward, low, high);\n const span = (start: number, end: number, point: Vector): Event[] => {\n const slot = {\n stretch: { placed, west: point, east: east.vector, north, eastward },\n entry: undefined,\n };\n return [\n { longitude: start, rank: 1, slot },\n { longitude: end, rank: 3, slot },\n ];\n };\n return low < high\n ? span(low, high, west.vector)\n : [\n ...span(low, 180, west.vector),\n ...span(-180, high, atAntimeridian(placed.arc)),\n ];\n}\n\n/**\n * The sweep events of an arc over a pole: an arc along each of its meridians,\n * from its vertex to the pole, and between them a stretch at the pole, beyond\n * every other arc crossing those longitudes. The stretch keeps the arc's\n * circle, which has every point of the meridians between on its far side\n * from the pole. It leaves before the stretches starting on the arc's last\n * meridian enter, since the arc runs along that meridian there, which its\n * walk there covers.\n */\nfunction polarEvents(\n placed: Placed,\n pole: Vector,\n north: Vector,\n eastward: boolean,\n low: number,\n high: number\n): Event[] {\n const walks = [placed.arc.from, placed.arc.to].map(\n ({ written, vector }): Event => ({\n longitude: written === 180 ? -180 : written,\n rank: 2,\n upright: {\n placed,\n south: pole[2] > 0 ? vector : pole,\n north: pole[2] > 0 ? pole : vector,\n },\n })\n );\n const across = (start: number, end: number): Event[] => {\n const slot = {\n stretch: { placed, west: pole, east: pole, north, eastward },\n entry: undefined,\n };\n return [\n { longitude: start, rank: 1, slot },\n { longitude: end, rank: 0, slot },\n ];\n };\n if (low < high) return [...walks, ...across(low, high)];\n return [\n ...walks,\n ...across(low, 180),\n ...(high > -180 ? across(-180, high) : []),\n ];\n}\n\n/**\n * The point's latitude, in radians, which orders points on one meridian. Its\n * z coordinate alone does not: z rounds to ±1 within about 6e-7 degrees of a\n * pole, where rings arriving together would tie.\n */\nfunction latitude(point: Vector): number {\n return Math.atan2(point[2], Math.hypot(point[0], point[1]));\n}\n\n/**\n * A ring on the meridian where the sweep first meets it, and the arc of\n * another ring first north of it there, if any.\n */\ninterface Placement {\n readonly ring: RingNode;\n readonly north: Stretch | undefined;\n}\n\ntype Swept =\n | { readonly meeting: readonly [Placed, Placed] }\n | { readonly meeting?: undefined; readonly placements: Placement[] };\n\n/**\n * The first two arcs found meeting that `apart` does not excuse, by a sweep\n * from the antimeridian eastward that keeps the arcs it crosses in\n * south-to-north order and compares each only with its neighbors in it\n * (Shamos and Hoey): two arcs that meet are neighbors just before the\n * westernmost meeting, so admission takes expected n log n time in the arc\n * count however the arcs lie. At each longitude the arcs starting there enter\n * first; then each arc along that meridian is compared with the arcs crossing\n * its span, found by position; then the arcs ending there leave. Two arcs\n * along one meridian need no comparison of their own: where they meet, one\n * ends on the other, and the arc continuing its ring from that end crosses\n * the meridian there (a ring's arcs along one meridian that continue each\n * other end where the last one does, and a ring doubling back along a\n * meridian is refused in `ringArcs`), so the walk along the other one meets\n * it. An arc over a pole is walked along both its meridians, with a stretch\n * at the pole between them (`polarEvents`): two arcs over one pole meet\n * there, where either their stretches are neighbors at the pole or, when\n * their longitudes only touch, one's walk finds the other's stretch.\n *\n * Failing a meeting, where each ring was first met: once the arcs starting\n * on that meridian have entered, the arc north of the ring's northernmost\n * point there, skipping the ring's own arcs through that point. The rings\n * met on one meridian are listed north to south, so every ring is listed\n * after the ring of the arc north of it.\n */\nfunction sweep(\n arcs: readonly Placed[],\n apart: (first: Placed, second: Placed) => boolean\n): Swept {\n const events = arcs.flatMap(arcEvents);\n events.sort(\n (left, right) => left.longitude - right.longitude || left.rank - right.rank\n );\n const head: Entry = { stretch: undefined, links: createLinks(LEVELS) };\n const meeting = (\n first: Placed | undefined,\n second: Placed | undefined\n ): readonly [Placed, Placed] | undefined => {\n if (!(first && second)) return;\n if (apart(first, second) || !meet(first.arc, second.arc)) return;\n return [first, second];\n };\n const placements: Placement[] = [];\n // Each ring met for the first time on the sweep's meridian, with its\n // northernmost entry there so far.\n const arrivals = new Map<RingNode, { entry: Entry; west: Vector }>();\n const placeArrivals = (): void => {\n const arrived = Array.from(arrivals, ([ring, { entry, west }]) => {\n let next = entry.links[0]?.next;\n while (next?.stretch?.placed.ring === ring) next = next.links[0]?.next;\n return { ring, height: latitude(west), north: next?.stretch };\n });\n arrived.sort((left, right) => right.height - left.height);\n // One push per ring: a spread would pass every ring arriving on this\n // meridian as a call argument, past the engine's argument limit.\n for (const { ring, north } of arrived) placements.push({ ring, north });\n arrivals.clear();\n };\n const met = new Set<RingNode>();\n for (const [index, event] of events.entries()) {\n if (event.rank === 1) {\n // A skip list's heights are coin flips the input cannot know: heights\n // a polygon could predict let it keep its long-lived arcs low and make\n // every search walk them one by one. The verdict does not depend on\n // them: arcs that meet are neighbors before they meet at any height.\n const height = 1 + Math.floor(-Math.log2(1 - Math.random()));\n const entry = enter(head, event.slot.stretch, Math.min(LEVELS, height));\n event.slot.entry = entry;\n const [link] = entry.links;\n const found =\n meeting(link?.previous?.stretch?.placed, entry.stretch?.placed) ??\n meeting(entry.stretch?.placed, link?.next?.stretch?.placed);\n if (found) return { meeting: found };\n const { placed, west } = event.slot.stretch;\n const top = arrivals.get(placed.ring);\n if (\n !met.has(placed.ring) ||\n (top && latitude(west) > latitude(top.west))\n ) {\n met.add(placed.ring);\n arrivals.set(placed.ring, { entry, west });\n }\n const next = events[index + 1];\n if (next?.rank !== 1 || next.longitude !== event.longitude) {\n placeArrivals();\n }\n } else if (event.rank === 2) {\n const { upright } = event;\n // Every arc crossing the meridian within the span meets this one, so\n // the walk stops at the first not excused, or past the north end.\n let entry: Entry | undefined = southOf(head, upright.south, LEVELS - 1);\n entry = entry.stretch ? entry : entry.links[0]?.next;\n while (entry?.stretch) {\n const found = meeting(upright.placed, entry.stretch.placed);\n if (found) return { meeting: found };\n if (dot(entry.stretch.north, upright.north) < -TOLERANCE) break;\n entry = entry.links[0]?.next;\n }\n } else if (event.slot.entry) {\n const [link] = event.slot.entry.links;\n leave(event.slot.entry);\n const found = meeting(\n link?.previous?.stretch?.placed,\n link?.next?.stretch?.placed\n );\n if (found) return { meeting: found };\n }\n }\n return { placements };\n}\n\n/**\n * The ring's signed area in steradians, positive when counterclockwise: the\n * sum of the triangles each arc makes with the north pole (Van Oosterom and\n * Strackee), taken through the south pole's triangle and the lune between the\n * arc's meridians when the arc lies nearer the south pole, where the north\n * pole's triangle loses its precision. The lunes' longitudes telescope, so\n * each run of such arcs adds the longitude from its start to its end: a ring\n * near the south pole is one run, and its lunes add exactly nothing, where\n * summed arc by arc their rounding would outweigh its area. No admitted ring\n * has a pole inside it (`wrap` in `ringArcs`), so this is the area on the\n * ring's pole-free side, and its sign says on which side of its arcs that\n * area lies.\n */\nfunction signedArea(ring: Ring): number {\n let sum = 0;\n let lune = 0;\n let run: number | undefined;\n let end = 0;\n for (const arc of ring) {\n const turn = cross(arc.start, arc.end)[2];\n const along = 1 + dot(arc.start, arc.end);\n const lift = arc.start[2] + arc.end[2];\n if (lift >= 0) {\n sum += 2 * Math.atan2(turn, along + lift);\n if (run !== undefined) lune += arc.from.longitude - run;\n run = undefined;\n } else {\n sum += 2 * Math.atan2(-turn, along - lift);\n run ??= arc.from.longitude;\n }\n end = arc.to.longitude;\n }\n if (run !== undefined) lune += end - run;\n return sum + 2 * lune * RADIANS;\n}\n\n/*\n * A hole must lie strictly inside its outer ring, and holes must neither touch\n * nor overlap: a hole reaching outside its outer ring, or a point in two\n * holes, has no single reading (the ledger's D2 addendum tabulates what each\n * database answered). A touch is refused with them: a hole written touching a\n * straight parallel edge crosses that edge's arc.\n */\n\n/**\n * Kept output normalization, not a refusal: the GeoJSON that withinPolygon\n * binds (adapters/databases/{postgres,mysql}) always carries a counterclockwise\n * outer ring and clockwise holes, because neither database's reading of ring\n * orientation is proven portable (v1-public-api-geopoint-plan.md).\n */\nfunction wound(\n ring: GeoPoint[],\n counterClockwise: boolean,\n wanted: boolean\n): GeoPoint[] {\n return counterClockwise === wanted ? ring : ring.reverse();\n}\n\nfunction ringPath(ring: number): PropertyKey[] {\n return ring === 0 ? [\"outer\"] : [\"holes\", ring - 1];\n}\n\nfunction ringNode(points: GeoPoint[], arcs: Ring, index: number): RingNode {\n return {\n index,\n hole: index === 0 ? Number.POSITIVE_INFINITY : index - 1,\n points,\n arcs,\n counterClockwise: signedArea(arcs) > 0,\n around: undefined,\n inside: false,\n firstAround: Number.POSITIVE_INFINITY,\n firstWithin: Number.POSITIVE_INFINITY,\n };\n}\n\n/**\n * The walker admits the polygon's shape (exact keys, finite in-range\n * vertices, at least three per ring); the geometry then refuses the polygons\n * with no single meaning or outside the domain choices (above): each ring\n * alone, then the rings together.\n */\nexport function validateGeoPolygon(\n value: unknown\n): ValidationResult<GeoPolygon> {\n const polygon = validateSchema(polygonRecord, value);\n if (polygon.issues) return polygon;\n const outer = ringArcs(polygon.value.outer, [\"outer\"]);\n if (outer.issues) return outer;\n const shell = ringNode(polygon.value.outer, outer.value, 0);\n const holes: RingNode[] = [];\n for (const [index, points] of (polygon.value.holes ?? []).entries()) {\n const hole = ringArcs(points, [\"holes\", index]);\n if (hole.issues) return hole;\n holes.push(ringNode(points, hole.value, index + 1));\n }\n const placed = [shell, ...holes].flatMap((ring) =>\n ring.arcs.map((arc, index) => ({ arc, ring, index }))\n );\n // Neighbors along a ring meet at their shared vertex; an arc over a pole\n // meets itself where its walks find its stretch.\n const swept = sweep(\n placed,\n (first, second) =>\n first.ring === second.ring &&\n [0, 1, first.ring.arcs.length - 1].includes(\n Math.abs(first.index - second.index)\n )\n );\n if (swept.meeting) {\n const [first, second] = swept.meeting;\n const later = ringPath(Math.max(first.ring.index, second.ring.index));\n // A ring meeting itself has no single reading (the ledger's D2 table:\n // the bowtie and the ring past a whole turn over itself).\n if (first.ring === second.ring) {\n return fail(\"A GeoPolygon ring cannot self-intersect\", later);\n }\n return Math.min(first.ring.index, second.ring.index) === 0\n ? fail(\"A GeoPolygon hole must be strictly inside its outer ring\", later)\n : fail(\"GeoPolygon holes cannot touch or overlap\", later);\n }\n // No two rings meet, so where the sweep first met a ring places all of it:\n // inside the ring of the arc north of it when that arc has its ring's\n // interior to the south (a counterclockwise ring's interior is on the left\n // of its arcs), else beside that ring, in the ring around it, which the\n // sweep placed first.\n for (const { ring, north } of swept.placements) {\n const other = north?.placed.ring;\n const around =\n other === undefined || other.counterClockwise !== north?.eastward\n ? other\n : other.around;\n ring.around = around;\n ring.inside = around !== undefined && (around.index === 0 || around.inside);\n ring.firstAround = around\n ? Math.min(around.hole, around.firstAround)\n : Number.POSITIVE_INFINITY;\n }\n // Reversed in place, the list's last use: every ring now comes before the\n // ring around it, which collects the first hole within it.\n for (const { ring } of swept.placements.reverse()) {\n const { around } = ring;\n if (around) {\n around.firstWithin = Math.min(\n around.firstWithin,\n ring.hole,\n ring.firstWithin\n );\n }\n }\n for (const { hole, inside, firstAround, firstWithin } of holes) {\n if (!inside) {\n return fail(\"A GeoPolygon hole must be strictly inside its outer ring\", [\n \"holes\",\n hole,\n ]);\n }\n if (Math.min(firstAround, firstWithin) < hole) {\n return fail(\"GeoPolygon holes cannot touch or overlap\", [\"holes\", hole]);\n }\n }\n const wide = wound(shell.points, shell.counterClockwise, true);\n const cut = holes.map(({ points, counterClockwise }) =>\n wound(points, counterClockwise, false)\n );\n // An empty and an absent holes list emit the same GeoJSON; one spelling\n // keeps them one validated argument, and so one cache key.\n return ok(cut.length > 0 ? { outer: wide, holes: cut } : { outer: wide });\n}\n\nconst areaRecord = object({\n bounds: createSchema(\"object\", validateGeoBounds),\n polygon: createSchema(\"object\", validateGeoPolygon),\n});\n\nexport function validateGeoArea(value: unknown): ValidationResult<GeoArea> {\n const area = validateSchema(areaRecord, value);\n if (area.issues) return area;\n const { bounds, polygon } = area.value;\n // Exactly one variant: buildGeoPointWithin (query-engine/builders/\n // geo-point-builder.ts) branches on `\"bounds\" in area`, so a second variant\n // would be dropped silently and a missing one would reach geoPolygonJson as\n // undefined and throw a TypeError instead of a database error.\n if (bounds && !polygon) return ok({ bounds });\n if (polygon && !bounds) return ok({ polygon });\n return fail(\"Expected GeoArea with exactly one of bounds or polygon\");\n}\n\nexport function geoAreaSchema(): VibSchema<GeoArea, GeoArea> {\n return createSchema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E,SAAgB,eAA6C,CAC3D,OAAO,EAAa,WAAY,gBAAgB"}
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{s as t}from"./native-types-DgjMUikz.mjs";import{_ as n,b as r}from"./scalar-BHCh7aUz.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-A3zffFWP.mjs.map
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{s as t}from"./native-types-DspZ0Z5E.mjs";import{_ as n,b as r}from"./scalar-B9WizsvR.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-D7U8HACL.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"hydration-A3zffFWP.mjs","names":[],"sources":["../src/schema/hydration.ts"],"sourcesContent":["/**\n * Schema Hydration\n *\n * Hydrates schema name slots (tsName, sqlName) for models and scalars.\n * This is called once at client initialization when the full schema context is available.\n *\n * - tsName: The TypeScript key name in the schema (e.g., \"email\", \"User\")\n * - sqlName: The resolved database name (e.g., \"email_column\", \"users\")\n *\n * Names are stored in the model's nameRegistry, not on the scalar instances.\n * This allows the same scalar to be reused across multiple models with different keys.\n */\n\nimport { isValidSchemaIdentifier } from \"./identifier\";\nimport type { Model, NameRegistry } from \"./model\";\nimport { preflightModelRegistrationIdentity } from \"./registration-preflight\";\nimport type { Scalar } from \"./scalars/base\";\nimport type { SchemaNames } from \"./scalars/common\";\nimport { SchemaValidationError } from \"./validation/error\";\n\n/**\n * Schema type - record of model names to Model instances\n */\nexport type Schema = Record<string, Model<any>>;\n\n/**\n * Hydrate name slots for all models and scalars in a schema.\n *\n * This function populates the model's nameRegistry:\n * - model[\"~\"].names.ts = schema key (e.g., \"User\")\n * - model[\"~\"].names.sql = tableName ?? schema key (e.g., \"users\")\n * - model[\"~\"].nameRegistry.fields.get(fieldKey) = {ts, sql}\n *\n * Operation schemas are registry-owned; hydration only binds reusable schema\n * definitions to model-local names and relation sources.\n *\n * @param schema - The schema object mapping model names to Model instances\n */\nexport function hydrateSchemaNames(schema: Schema, checked = false): void {\n const registrations = Object.entries(schema);\n // A schema `viborm check` validated binds its names without re-proving them.\n if (checked) {\n for (const [modelKey, model] of registrations)\n bindModelNames(modelKey, model);\n return;\n }\n // TWO ordered phases. The preflight proves every model's identity and name\n // stability BEFORE a single registry write, so a schema that fails validation\n // never leaves models 0..N-1 bound while model N is refused.\n const identityIssue = preflightModelRegistrationIdentity(registrations);\n if (identityIssue) throw new SchemaValidationError([identityIssue]);\n for (const [modelKey, model] of registrations) {\n preflightModelIdentifiers(modelKey, model);\n }\n for (const [modelKey, model] of registrations) {\n bindModelNames(modelKey, model);\n }\n}\n\n/**\n * Prove one model's identity: its identifiers are legal, and its schema key is\n * the one this model object is already bound to.\n *\n * A model object binds ONE schema key for its lifetime. Re-registering the same\n * object under the same key is idempotent — the same schema composed twice, or\n * a second client over the same models, is a normal thing to do — while a second\n * key is refused, because every derived name, junction table, index and\n * constraint in the estate is generated from the schema key and two keys would\n * make one model object mean two different tables.\n */\nfunction preflightModelIdentifiers(modelKey: string, model: Model<any>): void {\n const state = model[\"~\"].state;\n\n assertValidIdentifier(\"Model\", modelKey);\n if (state.tableName !== undefined) {\n assertValidIdentifier(\"Mapped table\", state.tableName, modelKey);\n }\n for (const fieldKey of Object.keys(state.shape)) {\n assertValidIdentifier(\"Field\", fieldKey, modelKey);\n }\n for (const scalar of Object.values(state.scalars as Record<string, Scalar>)) {\n if (scalar[\"~\"].state.columnName !== undefined) {\n assertValidIdentifier(\n \"Mapped column\",\n scalar[\"~\"].state.columnName,\n modelKey\n );\n }\n }\n}\n\n/**\n * Bind one model's names and its scalar name registry.\n *\n * A relation has no name entry — its key is its only name, with no column to\n * map — and no relation is given a source model: `.extends()` may reuse one\n * relation object under more than one model or key, so a contextual operation\n * carries its own slot identity instead.\n */\nfunction bindModelNames(modelKey: string, model: Model<any>): void {\n const names = model[\"~\"].names as SchemaNames;\n const state = model[\"~\"].state;\n const registry = model[\"~\"].nameRegistry as NameRegistry;\n\n names.ts = modelKey;\n names.sql = state.tableName ?? modelKey;\n\n for (const [fieldKey, scalar] of Object.entries(\n state.scalars as Record<string, Scalar>\n )) {\n const fieldNames: SchemaNames = {\n ts: fieldKey,\n sql: scalar[\"~\"].state.columnName ?? fieldKey,\n };\n registry.fields.set(fieldKey, fieldNames);\n }\n\n // Operation schemas are built by SchemaRegistry, not during name hydration.\n}\n\nfunction assertValidIdentifier(\n kind: \"Field\" | \"Mapped column\" | \"Mapped table\" | \"Model\",\n identifier: unknown,\n modelName?: string\n): void {\n if (isValidSchemaIdentifier(identifier)) return;\n const location = modelName ? ` in '${modelName}'` : \"\";\n const renderedIdentifier = String(identifier);\n throw new Error(\n `${kind} '${renderedIdentifier}'${location} is invalid identifier; identifiers must be ASCII, at most 63 bytes, and must not collide with Object.prototype properties`\n );\n}\n\n/**\n * Check if a schema has been hydrated\n */\nexport function isSchemaHydrated(schema: Schema): boolean {\n const firstModel = Object.values(schema)[0];\n if (!firstModel) {\n return true;\n } // Empty schema is considered hydrated\n return firstModel[\"~\"].names.ts !== undefined;\n}\n\n/**\n * Get the SQL name for a model (throws if not hydrated)\n */\nexport function getModelSqlName(model: Model<any>): string {\n const sqlName = model[\"~\"].names.sql;\n if (!sqlName) {\n throw new Error(\n \"Schema not hydrated. Call hydrateSchemaNames() or create a client first.\"\n );\n }\n return sqlName;\n}\n\n/**\n * Get the SQL name for a scalar field key.\n * Delegates to model[\"~\"].getFieldName().\n */\nexport function getFieldSqlName(model: Model<any>, fieldKey: string): string {\n return model[\"~\"].getFieldName(fieldKey).sql;\n}\n"],"mappings":"0IAsCA,SAAgB,mBAAmB,EAAgB,EAAU,GAAa,CACxE,IAAM,EAAgB,OAAO,QAAQ,EAAO,CAE5C,GAAI,EAAS,CACX,IAAK,GAAM,CAAC,EAAU,KAAU,EAC9B,eAAe,E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*\n * Hydrates schema name slots (tsName, sqlName) for models and scalars.\n * This is called once at client initialization when the full schema context is available.\n *\n * - tsName: The TypeScript key name in the schema (e.g., \"email\", \"User\")\n * - sqlName: The resolved database name (e.g., \"email_column\", \"users\")\n *\n * Names are stored in the model's nameRegistry, not on the scalar instances.\n * This allows the same scalar to be reused across multiple models with different keys.\n */\n\nimport { isValidSchemaIdentifier } from \"./identifier\";\nimport type { Model, NameRegistry } from \"./model\";\nimport { preflightModelRegistrationIdentity } from \"./registration-preflight\";\nimport type { Scalar } from \"./scalars/base\";\nimport type { SchemaNames } from \"./scalars/common\";\nimport { SchemaValidationError } from \"./validation/error\";\n\n/**\n * Schema type - record of model names to Model instances\n */\nexport type Schema = Record<string, Model<any>>;\n\n/**\n * Hydrate name slots for all models and scalars in a schema.\n *\n * This function populates the model's nameRegistry:\n * - model[\"~\"].names.ts = schema key (e.g., \"User\")\n * - model[\"~\"].names.sql = tableName ?? schema key (e.g., \"users\")\n * - model[\"~\"].nameRegistry.fields.get(fieldKey) = {ts, sql}\n *\n * Operation schemas are registry-owned; hydration only binds reusable schema\n * definitions to model-local names and relation sources.\n *\n * @param schema - The schema object mapping model names to Model instances\n */\nexport function hydrateSchemaNames(schema: Schema, checked = false): void {\n const registrations = Object.entries(schema);\n // A schema `viborm check` validated binds its names without re-proving them.\n if (checked) {\n for (const [modelKey, model] of registrations)\n bindModelNames(modelKey, model);\n return;\n }\n // TWO ordered phases. The preflight proves every model's identity and name\n // stability BEFORE a single registry write, so a schema that fails validation\n // never leaves models 0..N-1 bound while model N is refused.\n const identityIssue = preflightModelRegistrationIdentity(registrations);\n if (identityIssue) throw new SchemaValidationError([identityIssue]);\n for (const [modelKey, model] of registrations) {\n preflightModelIdentifiers(modelKey, model);\n }\n for (const [modelKey, model] of registrations) {\n bindModelNames(modelKey, model);\n }\n}\n\n/**\n * Prove one model's identity: its identifiers are legal, and its schema key is\n * the one this model object is already bound to.\n *\n * A model object binds ONE schema key for its lifetime. Re-registering the same\n * object under the same key is idempotent — the same schema composed twice, or\n * a second client over the same models, is a normal thing to do — while a second\n * key is refused, because every derived name, junction table, index and\n * constraint in the estate is generated from the schema key and two keys would\n * make one model object mean two different tables.\n */\nfunction preflightModelIdentifiers(modelKey: string, model: Model<any>): void {\n const state = model[\"~\"].state;\n\n assertValidIdentifier(\"Model\", modelKey);\n if (state.tableName !== undefined) {\n assertValidIdentifier(\"Mapped table\", state.tableName, modelKey);\n }\n for (const fieldKey of Object.keys(state.shape)) {\n assertValidIdentifier(\"Field\", fieldKey, modelKey);\n }\n for (const scalar of Object.values(state.scalars as Record<string, Scalar>)) {\n if (scalar[\"~\"].state.columnName !== undefined) {\n assertValidIdentifier(\n \"Mapped column\",\n scalar[\"~\"].state.columnName,\n modelKey\n );\n }\n }\n}\n\n/**\n * Bind one model's names and its scalar name registry.\n *\n * A relation has no name entry — its key is its only name, with no column to\n * map — and no relation is given a source model: `.extends()` may reuse one\n * relation object under more than one model or key, so a contextual operation\n * carries its own slot identity instead.\n */\nfunction bindModelNames(modelKey: string, model: Model<any>): void {\n const names = model[\"~\"].names as SchemaNames;\n const state = model[\"~\"].state;\n const registry = model[\"~\"].nameRegistry as NameRegistry;\n\n names.ts = modelKey;\n names.sql = state.tableName ?? modelKey;\n\n for (const [fieldKey, scalar] of Object.entries(\n state.scalars as Record<string, Scalar>\n )) {\n const fieldNames: SchemaNames = {\n ts: fieldKey,\n sql: scalar[\"~\"].state.columnName ?? fieldKey,\n };\n registry.fields.set(fieldKey, fieldNames);\n }\n\n // Operation schemas are built by SchemaRegistry, not during name hydration.\n}\n\nfunction assertValidIdentifier(\n kind: \"Field\" | \"Mapped column\" | \"Mapped table\" | \"Model\",\n identifier: unknown,\n modelName?: string\n): void {\n if (isValidSchemaIdentifier(identifier)) return;\n const location = modelName ? ` in '${modelName}'` : \"\";\n const renderedIdentifier = String(identifier);\n throw new Error(\n `${kind} '${renderedIdentifier}'${location} is invalid identifier; identifiers must be ASCII, at most 63 bytes, and must not collide with Object.prototype properties`\n );\n}\n\n/**\n * Check if a schema has been hydrated\n */\nexport function isSchemaHydrated(schema: Schema): boolean {\n const firstModel = Object.values(schema)[0];\n if (!firstModel) {\n return true;\n } // Empty schema is considered hydrated\n return firstModel[\"~\"].names.ts !== undefined;\n}\n\n/**\n * Get the SQL name for a model (throws if not hydrated)\n */\nexport function getModelSqlName(model: Model<any>): string {\n const sqlName = model[\"~\"].names.sql;\n if (!sqlName) {\n throw new Error(\n \"Schema not hydrated. Call hydrateSchemaNames() or create a client first.\"\n );\n }\n return sqlName;\n}\n\n/**\n * Get the SQL name for a scalar field key.\n * Delegates to model[\"~\"].getFieldName().\n */\nexport function getFieldSqlName(model: Model<any>, fieldKey: string): string {\n return model[\"~\"].getFieldName(fieldKey).sql;\n}\n"],"mappings":"0IAsCA,SAAgB,mBAAmB,EAAgB,EAAU,GAAa,CACxE,IAAM,EAAgB,OAAO,QAAQ,EAAO,CAE5C,GAAI,EAAS,CACX,IAAK,GAAM,CAAC,EAAU,KAAU,EAC9B,eAAe,EAAU,EAAM,CACjC,OAKF,IAAM,EAAgB,EAAmC,EAAc,CACvE,GAAI,EAAe,MAAM,IAAI,EAAsB,CAAC,EAAc,CAAC,CACnE,IAAK,GAAM,CAAC,EAAU,KAAU,EAC9B,0BAA0B,EAAU,EAAM,CAE5C,IAAK,GAAM,CAAC,EAAU,KAAU,EAC9B,eAAe,EAAU,EAAM,CAenC,SAAS,0BAA0B,EAAkB,EAAyB,CAC5E,IAAM,EAAQ,EAAM,KAAK,MAEzB,sBAAsB,QAAS,EAAS,CACpC,EAAM,YAAc,IAAA,IACtB,sBAAsB,eAAgB,EAAM,UAAW,EAAS,CAElE,IAAK,IAAM,KAAY,OAAO,KAAK,EAAM,MAAM,CAC7C,sBAAsB,QAAS,EAAU,EAAS,CAEpD,IAAK,IAAM,KAAU,OAAO,OAAO,EAAM,QAAkC,CACrE,EAAO,KAAK,MAAM,aAAe,IAAA,IACnC,sBACE,gBACA,EAAO,KAAK,MAAM,WAClB,EACD,CAaP,SAAS,eAAe,EAAkB,EAAyB,CACjE,IAAM,EAAQ,EAAM,KAAK,MACnB,EAAQ,EAAM,KAAK,MACnB,EAAW,EAAM,KAAK,aAE5B,EAAM,GAAK,EACX,EAAM,IAAM,EAAM,WAAa,EAE/B,IAAK,GAAM,CAAC,EAAU,KAAW,OAAO,QACtC,EAAM,QACP,CAAE,CACD,IAAM,EAA0B,CAC9B,GAAI,EACJ,IAAK,EAAO,KAAK,MAAM,YAAc,EACtC,CACD,EAAS,OAAO,IAAI,EAAU,EAAW,EAM7C,SAAS,sBACP,EACA,EACA,EACM,CACN,GAAI,EAAwB,EAAW,CAAE,OACzC,IAAM,EAAW,EAAY,QAAQ,EAAU,GAAK,GAC9C,EAAqB,OAAO,EAAW,CAC7C,MAAU,MACR,GAAG,EAAK,IAAI,EAAmB,GAAG,EAAS,4HAC5C"}
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-z-cH5ZBI.mjs";import{t as n}from"./migrations-BMiRjR-N.mjs";import{o as r}from"./sql-3o4DOKm9.mjs";import{ft as i,lt as a}from"./native-types-DgjMUikz.mjs";import{C as o,S as s}from"./scalar-BHCh7aUz.mjs";import{d as c,h as l,n as u,u as d}from"./validator-CZLW7aR3.mjs";import{t as f}from"./hydration-A3zffFWP.mjs";import{t as p}from"./identifiers-s00pGES8.mjs";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:i}};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`?"`":`"`),s=t===`postgresql`&&n?`${a(n)}.`:``;return r.raw(`${s+a(o(e))} AS ${i}`)}function columnSql(e,t,n,i){let a=p(n===`mysql`?"`":`"`);return r.raw(`${i}.${a(s(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 l(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 d(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:l,dialect:d,namespace:p}=e;f(e.schema);let m=u(e.schema),h=c(i,l,m);if(h===void 0||!a(h.format))throw new n(`'${o(i)}.${s(i,l)}' 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,l,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{isPostgresTextToUuid as n,postgresTextToUuidGuard as r,identifierConversionChecks as t};
2
- //# sourceMappingURL=identifier-conversion-DHYPTgzr.mjs.map
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-z-cH5ZBI.mjs";import{t as n}from"./migrations-BMiRjR-N.mjs";import{o as r}from"./sql-BGjAsoBE.mjs";import{ft as i,lt as a}from"./native-types-DspZ0Z5E.mjs";import{C as o,S as s}from"./scalar-B9WizsvR.mjs";import{d as c,h as l,n as u,u as d}from"./validator-CDYlO9HV.mjs";import{t as f}from"./hydration-D7U8HACL.mjs";import{t as p}from"./identifiers-BTCfD5ic.mjs";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:i}};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`?"`":`"`),s=t===`postgresql`&&n?`${a(n)}.`:``;return r.raw(`${s+a(o(e))} AS ${i}`)}function columnSql(e,t,n,i){let a=p(n===`mysql`?"`":`"`);return r.raw(`${i}.${a(s(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 l(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 d(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:l,dialect:d,namespace:p}=e;f(e.schema);let m=u(e.schema),h=c(i,l,m);if(h===void 0||!a(h.format))throw new n(`'${o(i)}.${s(i,l)}' 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,l,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{isPostgresTextToUuid as n,postgresTextToUuidGuard as r,identifierConversionChecks as t};
2
+ //# sourceMappingURL=identifier-conversion-Ci_iaJ0b.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"identifier-conversion-DHYPTgzr.mjs","names":["sql"],"sources":["../src/migrations/identifier-conversion.ts"],"sourcesContent":["/**\n * The three questions an EXISTING text column has to answer before it can\n * become an identifier column — asked as SQL, against the live database, by\n * the person doing the conversion.\n *\n * VibORM does not convert a populated text column on its own: the generated\n * `alterColumn` into a binary column is refused outright\n * ({@link file://./binary-conversion.ts}), and PostgreSQL's one automated leg,\n * `text` → `uuid`, is a per-value cast that either succeeds for the whole table\n * or aborts it. Both routes leave the same work to the author, and this module\n * is the part of that work a machine can state exactly:\n *\n * 1. **Every row is a value of the domain.** Prefix matched whole, payload in\n * the format's own grammar and width — and, for a KSUID, at most the text\n * of the largest value its 20 bytes hold. A row that is not is a row no\n * route can carry.\n * 2. **No two rows fold together.** `uuid` admits uppercase and `ulid`\n * lowercase as ALIASES, so a text column may hold two spellings of one\n * identifier. Compact storage holds the canonical one, so those two rows\n * become one value — violating a unique key, or silently merging two rows\n * where there is none. `ksuid` has no aliases and gets no such check. Asked\n * of the key AND of every referencing column that is a complete key of its\n * own model, because that column carries its own unique constraint through\n * the same fold; a non-unique foreign key holds repeats by design and is\n * never asked.\n * 3. **Every foreign key still finds its parent after the fold.** The FK\n * column converts with its own normalization, so agreement has to be proven\n * against the NORMALIZED sets rather than the stored text.\n *\n * Each check is one row and one boolean column, so each is exactly a\n * {@link MigrationCheckInput} — the `trusted-read` shape `generate()` already\n * accepts as `originChecks` on a manual transition. Run them by hand, or put\n * them in front of your own conversion migration; they are the same SQL either\n * way.\n *\n * Every IDENTITY comparison these checks make is asked of BYTES, because the\n * column they are about answers in bytes. MySQL 8's default collation is\n * `utf8mb4_0900_ai_ci`, where `=` folds case and accents: a bare\n * `p.id = c.userId` there answers TRUE for a KSUID pair that a `BINARY(20)`\n * column will hold as two different values, so an estate certified ready came\n * out of the conversion with a foreign key naming no parent. `CAST(… AS BINARY)`\n * pins it, and it pins across character sets where `COLLATE utf8mb4_bin` raises\n * on a `latin1` column. The grammar match is deliberately NOT cast: MySQL's\n * `REGEXP` refuses a binary operand outright, and every pattern here already\n * spells both cases, so nothing is lost.\n *\n * Pure and connection-free, like every other module in this layer: it renders\n * SQL, it never executes it.\n *\n * What it does NOT cover, deliberately: a junction table's own columns and a\n * polymorphic row carrier's id column. Those hold a key's values too and\n * convert by the same recipe, but they are private storage with no (model,\n * field) to name them by, so the migration guide lists them rather than this\n * module guessing at them.\n */\n\nimport { type Sql, sql } from \"@sql\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { hydrateSchemaNames } from \"../schema/hydration\";\nimport {\n type AnyModel,\n getColumnName,\n getModelKeyCatalog,\n getTableName,\n} from \"../schema/model\";\nimport { idDomainOf } from \"../schema/validation/id-domains\";\nimport {\n type ResolvedRelationIndex,\n resolvedEdges,\n} from \"../schema/validation/relation-resolution\";\nimport { resolveSchemaOrThrow } from \"../schema/validation/validator\";\nimport { createIdentifierQuoter } from \"../sql/identifiers\";\nimport {\n type IdDomain,\n isCompactIdFormat,\n} from \"../validation/primitives/id-codec\";\nimport { KSUID_MAX_TEXT } from \"../validation/primitives/id-formats\";\nimport type { Dialect } from \"./drivers/types\";\nimport type { MigrationCheckInput } from \"./v1-types\";\n\n/** The key whose text column is being converted, and the schema it lives in. */\nexport interface IdentifierConversionRequest {\n /**\n * The WHOLE schema, not just the model: a foreign key's domain is derived\n * from the resolved topology, and so is the list of columns that reference\n * this key. Resolved here, exactly as `serializeModels` resolves it.\n */\n readonly schema: Record<string, AnyModel>;\n readonly model: AnyModel;\n readonly field: string;\n readonly dialect: Dialect;\n /** PostgreSQL's target namespace, when the estate is bound to one. */\n readonly namespace?: string | undefined;\n}\n\n/** One character class, spelled once for both pattern languages. */\nconst HEX = \"[0-9a-fA-F]\";\nconst CROCKFORD = \"[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]\";\nconst BASE62 = \"[0-9A-Za-z]\";\n\n/**\n * The payload grammar of each compact format, as a regex and as a GLOB, and\n * the largest payload text when the grammar alone admits more than the bytes\n * hold.\n *\n * A ULID's grammar carries its own bound — the leading `[0-7]` — but 27 base62\n * characters express more than 2^160 values, and no character class can say\n * where 2^160 falls. So a KSUID is bounded by comparison against the codec's\n * own maximum text, read from `id-formats.ts` rather than spelled here.\n */\nconst PATTERNS = {\n uuid: {\n length: 36,\n regex: `^${HEX}{8}-${HEX}{4}-${HEX}{4}-${HEX}{4}-${HEX}{12}$`,\n glob: `${HEX.repeat(8)}-${HEX.repeat(4)}-${HEX.repeat(4)}-${HEX.repeat(4)}-${HEX.repeat(12)}`,\n fold: \"lower\",\n max: undefined,\n },\n ulid: {\n length: 26,\n regex: `^[0-7]${CROCKFORD}{25}$`,\n glob: `[0-7]${CROCKFORD.repeat(25)}`,\n fold: \"upper\",\n max: undefined,\n },\n ksuid: {\n length: 27,\n regex: `^${BASE62}{27}$`,\n glob: BASE62.repeat(27),\n fold: undefined,\n max: KSUID_MAX_TEXT,\n },\n} as const;\n\n/** `uuidv7` shares a uuid's grammar: the version nibble is not a storage fact. */\nfunction patternOf(domain: IdDomain) {\n if (domain.format === \"ulid\") return PATTERNS.ulid;\n if (domain.format === \"ksuid\") return PATTERNS.ksuid;\n return PATTERNS.uuid;\n}\n\n/** A literal integer: a width, never caller text, so it is text and not a bind. */\nconst int = (value: number): Sql => sql.raw(String(value));\n\n/** One quoted, optionally qualified table name, bound to a one-letter alias. */\nfunction fromSql(\n model: AnyModel,\n dialect: Dialect,\n namespace: string | undefined,\n alias: string\n): Sql {\n const quote = createIdentifierQuoter(dialect === \"mysql\" ? \"`\" : '\"');\n const qualifier =\n dialect === \"postgresql\" && namespace ? `${quote(namespace)}.` : \"\";\n return sql.raw(`${qualifier + quote(getTableName(model))} AS ${alias}`);\n}\n\n/**\n * One column, always written through its table's alias.\n *\n * The FK checks correlate two tables, and a one-to-one child whose primary key\n * IS its foreign key names both columns `id` — an unqualified reference there\n * binds to the inner table and compares a value with itself.\n */\nfunction columnSql(\n model: AnyModel,\n field: string,\n dialect: Dialect,\n alias: string\n): Sql {\n const quote = createIdentifierQuoter(dialect === \"mysql\" ? \"`\" : '\"');\n return sql.raw(`${alias}.${quote(getColumnName(model, field))}`);\n}\n\n/** The payload of a stored value: the whole column, or what follows the prefix. */\nfunction payloadSql(column: Sql, domain: IdDomain): Sql {\n const prefix = domain.prefix;\n if (!prefix) return column;\n return sql`substr(${column}, ${int(prefix.length + 2)})`;\n}\n\n/**\n * One comparison operand, asked as the bytes the compact column will hold.\n *\n * Only MySQL needs it, and only because its default collation answers a\n * different question than the column will: see the module note above. Not\n * applied to `REGEXP`, which refuses a binary operand.\n */\nfunction bytesSql(expression: Sql, dialect: Dialect): Sql {\n return dialect === \"mysql\" ? sql`CAST(${expression} AS BINARY)` : expression;\n}\n\n/**\n * One ORDERING operand, compared byte by byte on every dialect.\n *\n * Fixed-width base62 text sorts as its number only under byte order: every\n * database default here that is not bytes folds case, and there `a` sorts\n * before `V`. MySQL takes the byte pin `bytesSql` already applies; PostgreSQL\n * takes `COLLATE \"C\"`, after a cast to `text` because `citext` — a text-family\n * type a KSUID column may hold — lowercases before any collation is consulted;\n * SQLite's default collation is already `BINARY`, as every identity\n * comparison in this module already relies on.\n */\nfunction orderedSql(expression: Sql, dialect: Dialect): Sql {\n if (dialect === \"postgresql\") {\n return sql`CAST(${expression} AS text) COLLATE \"C\"`;\n }\n return bytesSql(expression, dialect);\n}\n\n/** Whether one stored value is a value of the domain. */\nfunction admitsSql(column: Sql, domain: IdDomain, dialect: Dialect): Sql {\n const pattern = patternOf(domain);\n const payload = payloadSql(column, domain);\n const matches =\n dialect === \"postgresql\"\n ? sql`${payload} ~ ${pattern.regex}`\n : dialect === \"mysql\"\n ? sql`${payload} REGEXP ${pattern.regex}`\n : sql`${payload} GLOB ${pattern.glob}`;\n const width = sql.raw(dialect === \"mysql\" ? \"CHAR_LENGTH\" : \"length\");\n const grammar = sql`${width}(${payload}) = ${int(pattern.length)} AND ${matches}`;\n const sized =\n pattern.max === undefined\n ? grammar\n : sql`${grammar} AND ${orderedSql(payload, dialect)} <= ${pattern.max}`;\n const prefix = domain.prefix;\n if (!prefix) return sized;\n const spelled = bytesSql(\n sql`substr(${column}, 1, ${int(prefix.length + 1)})`,\n dialect\n );\n return sql`${spelled} = ${`${prefix}-`} AND ${sized}`;\n}\n\n/**\n * The canonical spelling of one stored value, as the bytes it will become:\n * the alias fold for a format that has one, then the dialect's byte pin.\n */\nfunction foldSql(column: Sql, domain: IdDomain, dialect: Dialect): Sql {\n const fold = patternOf(domain).fold;\n const payload = payloadSql(column, domain);\n return bytesSql(\n fold === undefined ? payload : sql`${sql.raw(fold)}(${payload})`,\n dialect\n );\n}\n\n/**\n * `COUNT(col) = COUNT(DISTINCT fold(col))`: the question a UNIQUE column has to\n * answer before its aliases collapse into one another.\n */\nfunction foldCollisionCheck(\n from: Sql,\n column: Sql,\n domain: IdDomain,\n dialect: Dialect\n): MigrationCheckInput {\n return {\n kind: \"trusted-read\",\n query: sql`SELECT COUNT(${column}) = COUNT(DISTINCT ${foldSql(column, domain, dialect)}) AS ok FROM ${from}`,\n equals: true,\n };\n}\n\n/**\n * Whether this column is, BY ITSELF, a complete key of its own model.\n *\n * The fold question belongs to every column that carries a uniqueness\n * constraint through it, and a referencing column often does: the one-to-one\n * child whose primary key IS its foreign key is the ordinary shape, and a\n * `.unique()` foreign key is the other. Asking it of a plain many-side foreign\n * key would refuse every healthy estate on earth — repeats there are the\n * relation — so the catalog decides, not the fact of being a reference.\n *\n * `referenceableKeys` is the right catalog rather than the addressable one: a\n * total unique INDEX no selector can name still refuses a duplicate.\n */\nfunction isSingleColumnKey(model: AnyModel, field: string): boolean {\n return getModelKeyCatalog(model).referenceableKeys.some(\n (key) => key.length === 1 && key[0] === field\n );\n}\n\n/** `SELECT NOT EXISTS (…)`, the shape every row check takes. */\nconst noRowWhere = (from: Sql, predicate: Sql): MigrationCheckInput => ({\n kind: \"trusted-read\",\n query: sql`SELECT NOT EXISTS (SELECT 1 FROM ${from} WHERE ${predicate}) AS ok`,\n equals: true,\n});\n\n/** Every foreign-key column that holds this key's values. */\nfunction referencingColumns(\n request: IdentifierConversionRequest,\n index: ResolvedRelationIndex\n): { model: AnyModel; field: string }[] {\n const columns: { model: AnyModel; field: string }[] = [];\n for (const edge of resolvedEdges(index)) {\n if (edge.kind !== \"foreignKey\") continue;\n const other =\n edge.endpoints[0] === edge.owner ? edge.endpoints[1] : edge.endpoints[0];\n if (other.source !== request.model) continue;\n for (const member of edge.reference.members) {\n if (member.referencedField !== request.field) continue;\n columns.push({ model: edge.owner.source, field: member.foreignField });\n }\n }\n return columns;\n}\n\n/**\n * The pre-checks for converting one key's text column into its identifier\n * column, in the order a conversion needs them.\n *\n * Refuses a field with no compactly stored identifier domain rather than\n * answering with an empty list: an empty list reads as \"this estate is ready\",\n * and that is the one answer a caller who named the wrong field must not get.\n */\nexport function identifierConversionChecks(\n request: IdentifierConversionRequest\n): readonly MigrationCheckInput[] {\n const { model, field, dialect, namespace } = request;\n hydrateSchemaNames(request.schema);\n const index = resolveSchemaOrThrow(request.schema);\n const domain = idDomainOf(model, field, index);\n if (domain === undefined || !isCompactIdFormat(domain.format)) {\n throw new MigrationError(\n `'${getTableName(model)}.${getColumnName(model, field)}' has no compactly stored identifier domain, so it has no text conversion to check: only uuid, uuidv7, ulid and ksuid change storage.`,\n VibORMErrorCode.INVALID_INPUT\n );\n }\n const parent = fromSql(model, dialect, namespace, \"p\");\n const key = columnSql(model, field, dialect, \"p\");\n const checks: MigrationCheckInput[] = [\n noRowWhere(\n parent,\n sql`${key} IS NOT NULL AND NOT (${admitsSql(key, domain, dialect)})`\n ),\n ];\n const folds = patternOf(domain).fold !== undefined;\n if (folds) {\n checks.push(foldCollisionCheck(parent, key, domain, dialect));\n }\n for (const reference of referencingColumns(request, index)) {\n const child = fromSql(reference.model, dialect, namespace, \"c\");\n const fk = columnSql(reference.model, reference.field, dialect, \"c\");\n checks.push(\n noRowWhere(\n child,\n sql`${fk} IS NOT NULL AND NOT (${admitsSql(fk, domain, dialect)})`\n )\n );\n if (folds && isSingleColumnKey(reference.model, reference.field)) {\n checks.push(foldCollisionCheck(child, fk, domain, dialect));\n }\n checks.push(\n noRowWhere(\n child,\n sql`${fk} IS NOT NULL AND NOT EXISTS (SELECT 1 FROM ${parent} WHERE ${foldSql(key, domain, dialect)} = ${foldSql(fk, domain, dialect)})`\n )\n );\n }\n return checks;\n}\n\n// =============================================================================\n// THE ONE AUTOMATED LEG\n// =============================================================================\n\n/** The text column spellings PostgreSQL can hold an identifier in. */\nconst PG_TEXT_COLUMN = /^(?:text|citext|varchar\\(\\d+\\)|character varying.*)$/i;\n\n/** A SQL string literal: the only escape a quoted name needs inside one. */\nconst literal = (text: string): string => `'${text.replaceAll(\"'\", \"''\")}'`;\n\n/**\n * The message PostgreSQL's own `col::uuid` does not give.\n *\n * `ALTER COLUMN … TYPE uuid USING col::uuid` converts value by value: it\n * succeeds for an estate of canonical uuids and raises\n * `invalid input syntax for type uuid: \"…\"` on the first row that is not one,\n * aborting the transaction and leaving the column as it was. The outcome is\n * right; the message names one offending row and nothing about the choice the\n * author actually has. This runs FIRST, inside the same transaction, and says\n * how many rows are in the way and what the two routes are.\n *\n * A PREFIXED domain fails here too, and deliberately: `usr-a0ee…` is not uuid\n * text, and no `USING substring(col from 5)::uuid` is emitted for it, because\n * the snapshot carries the column TYPE and not the domain — the prefix is a\n * fact of the declaration that no migration artifact has ever held. Converting\n * a prefixed column is a manual route, and this says so before anything runs.\n *\n * It is not a second refusal: without it the conversion fails anyway. Its whole\n * and only coverage is the message.\n */\nexport function postgresTextToUuidGuard(\n qualifiedTable: string,\n quotedColumn: string\n): string {\n const marker = `${qualifiedTable}.${quotedColumn}`;\n return (\n \"DO $viborm$ DECLARE invalid bigint; BEGIN \" +\n `SELECT count(*) INTO invalid FROM ${qualifiedTable} WHERE ${quotedColumn} IS NOT NULL AND ${quotedColumn} !~ ${literal(PATTERNS.uuid.regex)}; ` +\n \"IF invalid > 0 THEN RAISE EXCEPTION \" +\n `${literal(`VibORM: % row(s) of ${marker} 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; ` +\n \"END IF; END $viborm$\"\n );\n}\n\n/** Whether this alteration is the one text→identifier conversion pg performs. */\nexport function isPostgresTextToUuid(\n fromType: string,\n toType: string\n): boolean {\n return (\n toType.toLowerCase() === \"uuid\" && PG_TEXT_COLUMN.test(fromType.trim())\n );\n}\n"],"mappings":"8aAgGA,MAAM,EAAM,cACN,EAAY,kCACZ,EAAS,cAYT,EAAW,CACf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,MAAO,EAAS,EAAW,IAAI,CACzD,EAAK,UAAU,EAAU,MAAO,EAAU,MAAO,EAAS,IAAI,CACpE,EAAO,KACL,WACE,EACA,CAAG,GAAG,EAAG,wBAAwB,UAAU,EAAI,EAAQ,EAAQ,CAAC,GACjE,CACF,CACG,GAAS,kBAAkB,EAAU,MAAO,EAAU,MAAM,EAC9D,EAAO,KAAK,mBAAmB,EAAO,EAAI,EAAQ,EAAQ,CAAC,CAE7D,EAAO,KACL,WACE,EACA,CAAG,GAAG,EAAG,6CAA6C,EAAO,SAAS,QAAQ,EAAK,EAAQ,EAAQ,CAAC,KAAK,QAAQ,EAAI,EAAQ,EAAQ,CAAC,GACvI,CACF,CAEH,OAAO,EAQT,MAAM,EAAiB,wDAGjB,QAAW,GAAyB,IAAI,EAAK,WAAW,IAAK,KAAK,CAAC,GAsBzE,SAAgB,wBACd,EACA,EACQ,CACR,IAAM,EAAS,GAAG,EAAe,GAAG,IACpC,MACE,iFACqC,EAAe,SAAS,EAAa,mBAAmB,EAAa,MAAM,QAAQ,EAAS,KAAK,MAAM,CAAC,wCAE1I,QAAQ,uBAAuB,EAAO,0aAA0a,CAAC,mCAMxd,SAAgB,qBACd,EACA,EACS,CACT,OACE,EAAO,aAAa,GAAK,QAAU,EAAe,KAAK,EAAS,MAAM,CAAC"}
1
+ {"version":3,"file":"identifier-conversion-Ci_iaJ0b.mjs","names":["sql"],"sources":["../src/migrations/identifier-conversion.ts"],"sourcesContent":["/**\n * The three questions an EXISTING text column has to answer before it can\n * become an identifier column — asked as SQL, against the live database, by\n * the person doing the conversion.\n *\n * VibORM does not convert a populated text column on its own: the generated\n * `alterColumn` into a binary column is refused outright\n * ({@link file://./binary-conversion.ts}), and PostgreSQL's one automated leg,\n * `text` → `uuid`, is a per-value cast that either succeeds for the whole table\n * or aborts it. Both routes leave the same work to the author, and this module\n * is the part of that work a machine can state exactly:\n *\n * 1. **Every row is a value of the domain.** Prefix matched whole, payload in\n * the format's own grammar and width — and, for a KSUID, at most the text\n * of the largest value its 20 bytes hold. A row that is not is a row no\n * route can carry.\n * 2. **No two rows fold together.** `uuid` admits uppercase and `ulid`\n * lowercase as ALIASES, so a text column may hold two spellings of one\n * identifier. Compact storage holds the canonical one, so those two rows\n * become one value — violating a unique key, or silently merging two rows\n * where there is none. `ksuid` has no aliases and gets no such check. Asked\n * of the key AND of every referencing column that is a complete key of its\n * own model, because that column carries its own unique constraint through\n * the same fold; a non-unique foreign key holds repeats by design and is\n * never asked.\n * 3. **Every foreign key still finds its parent after the fold.** The FK\n * column converts with its own normalization, so agreement has to be proven\n * against the NORMALIZED sets rather than the stored text.\n *\n * Each check is one row and one boolean column, so each is exactly a\n * {@link MigrationCheckInput} — the `trusted-read` shape `generate()` already\n * accepts as `originChecks` on a manual transition. Run them by hand, or put\n * them in front of your own conversion migration; they are the same SQL either\n * way.\n *\n * Every IDENTITY comparison these checks make is asked of BYTES, because the\n * column they are about answers in bytes. MySQL 8's default collation is\n * `utf8mb4_0900_ai_ci`, where `=` folds case and accents: a bare\n * `p.id = c.userId` there answers TRUE for a KSUID pair that a `BINARY(20)`\n * column will hold as two different values, so an estate certified ready came\n * out of the conversion with a foreign key naming no parent. `CAST(… AS BINARY)`\n * pins it, and it pins across character sets where `COLLATE utf8mb4_bin` raises\n * on a `latin1` column. The grammar match is deliberately NOT cast: MySQL's\n * `REGEXP` refuses a binary operand outright, and every pattern here already\n * spells both cases, so nothing is lost.\n *\n * Pure and connection-free, like every other module in this layer: it renders\n * SQL, it never executes it.\n *\n * What it does NOT cover, deliberately: a junction table's own columns and a\n * polymorphic row carrier's id column. Those hold a key's values too and\n * convert by the same recipe, but they are private storage with no (model,\n * field) to name them by, so the migration guide lists them rather than this\n * module guessing at them.\n */\n\nimport { type Sql, sql } from \"@sql\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { hydrateSchemaNames } from \"../schema/hydration\";\nimport {\n type AnyModel,\n getColumnName,\n getModelKeyCatalog,\n getTableName,\n} from \"../schema/model\";\nimport { idDomainOf } from \"../schema/validation/id-domains\";\nimport {\n type ResolvedRelationIndex,\n resolvedEdges,\n} from \"../schema/validation/relation-resolution\";\nimport { resolveSchemaOrThrow } from \"../schema/validation/validator\";\nimport { createIdentifierQuoter } from \"../sql/identifiers\";\nimport {\n type IdDomain,\n isCompactIdFormat,\n} from \"../validation/primitives/id-codec\";\nimport { KSUID_MAX_TEXT } from \"../validation/primitives/id-formats\";\nimport type { Dialect } from \"./drivers/types\";\nimport type { MigrationCheckInput } from \"./v1-types\";\n\n/** The key whose text column is being converted, and the schema it lives in. */\nexport interface IdentifierConversionRequest {\n /**\n * The WHOLE schema, not just the model: a foreign key's domain is derived\n * from the resolved topology, and so is the list of columns that reference\n * this key. Resolved here, exactly as `serializeModels` resolves it.\n */\n readonly schema: Record<string, AnyModel>;\n readonly model: AnyModel;\n readonly field: string;\n readonly dialect: Dialect;\n /** PostgreSQL's target namespace, when the estate is bound to one. */\n readonly namespace?: string | undefined;\n}\n\n/** One character class, spelled once for both pattern languages. */\nconst HEX = \"[0-9a-fA-F]\";\nconst CROCKFORD = \"[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]\";\nconst BASE62 = \"[0-9A-Za-z]\";\n\n/**\n * The payload grammar of each compact format, as a regex and as a GLOB, and\n * the largest payload text when the grammar alone admits more than the bytes\n * hold.\n *\n * A ULID's grammar carries its own bound — the leading `[0-7]` — but 27 base62\n * characters express more than 2^160 values, and no character class can say\n * where 2^160 falls. So a KSUID is bounded by comparison against the codec's\n * own maximum text, read from `id-formats.ts` rather than spelled here.\n */\nconst PATTERNS = {\n uuid: {\n length: 36,\n regex: `^${HEX}{8}-${HEX}{4}-${HEX}{4}-${HEX}{4}-${HEX}{12}$`,\n glob: `${HEX.repeat(8)}-${HEX.repeat(4)}-${HEX.repeat(4)}-${HEX.repeat(4)}-${HEX.repeat(12)}`,\n fold: \"lower\",\n max: undefined,\n },\n ulid: {\n length: 26,\n regex: `^[0-7]${CROCKFORD}{25}$`,\n glob: `[0-7]${CROCKFORD.repeat(25)}`,\n fold: \"upper\",\n max: undefined,\n },\n ksuid: {\n length: 27,\n regex: `^${BASE62}{27}$`,\n glob: BASE62.repeat(27),\n fold: undefined,\n max: KSUID_MAX_TEXT,\n },\n} as const;\n\n/** `uuidv7` shares a uuid's grammar: the version nibble is not a storage fact. */\nfunction patternOf(domain: IdDomain) {\n if (domain.format === \"ulid\") return PATTERNS.ulid;\n if (domain.format === \"ksuid\") return PATTERNS.ksuid;\n return PATTERNS.uuid;\n}\n\n/** A literal integer: a width, never caller text, so it is text and not a bind. */\nconst int = (value: number): Sql => sql.raw(String(value));\n\n/** One quoted, optionally qualified table name, bound to a one-letter alias. */\nfunction fromSql(\n model: AnyModel,\n dialect: Dialect,\n namespace: string | undefined,\n alias: string\n): Sql {\n const quote = createIdentifierQuoter(dialect === \"mysql\" ? \"`\" : '\"');\n const qualifier =\n dialect === \"postgresql\" && namespace ? `${quote(namespace)}.` : \"\";\n return sql.raw(`${qualifier + quote(getTableName(model))} AS ${alias}`);\n}\n\n/**\n * One column, always written through its table's alias.\n *\n * The FK checks correlate two tables, and a one-to-one child whose primary key\n * IS its foreign key names both columns `id` — an unqualified reference there\n * binds to the inner table and compares a value with itself.\n */\nfunction columnSql(\n model: AnyModel,\n field: string,\n dialect: Dialect,\n alias: string\n): Sql {\n const quote = createIdentifierQuoter(dialect === \"mysql\" ? \"`\" : '\"');\n return sql.raw(`${alias}.${quote(getColumnName(model, field))}`);\n}\n\n/** The payload of a stored value: the whole column, or what follows the prefix. */\nfunction payloadSql(column: Sql, domain: IdDomain): Sql {\n const prefix = domain.prefix;\n if (!prefix) return column;\n return sql`substr(${column}, ${int(prefix.length + 2)})`;\n}\n\n/**\n * One comparison operand, asked as the bytes the compact column will hold.\n *\n * Only MySQL needs it, and only because its default collation answers a\n * different question than the column will: see the module note above. Not\n * applied to `REGEXP`, which refuses a binary operand.\n */\nfunction bytesSql(expression: Sql, dialect: Dialect): Sql {\n return dialect === \"mysql\" ? sql`CAST(${expression} AS BINARY)` : expression;\n}\n\n/**\n * One ORDERING operand, compared byte by byte on every dialect.\n *\n * Fixed-width base62 text sorts as its number only under byte order: every\n * database default here that is not bytes folds case, and there `a` sorts\n * before `V`. MySQL takes the byte pin `bytesSql` already applies; PostgreSQL\n * takes `COLLATE \"C\"`, after a cast to `text` because `citext` — a text-family\n * type a KSUID column may hold — lowercases before any collation is consulted;\n * SQLite's default collation is already `BINARY`, as every identity\n * comparison in this module already relies on.\n */\nfunction orderedSql(expression: Sql, dialect: Dialect): Sql {\n if (dialect === \"postgresql\") {\n return sql`CAST(${expression} AS text) COLLATE \"C\"`;\n }\n return bytesSql(expression, dialect);\n}\n\n/** Whether one stored value is a value of the domain. */\nfunction admitsSql(column: Sql, domain: IdDomain, dialect: Dialect): Sql {\n const pattern = patternOf(domain);\n const payload = payloadSql(column, domain);\n const matches =\n dialect === \"postgresql\"\n ? sql`${payload} ~ ${pattern.regex}`\n : dialect === \"mysql\"\n ? sql`${payload} REGEXP ${pattern.regex}`\n : sql`${payload} GLOB ${pattern.glob}`;\n const width = sql.raw(dialect === \"mysql\" ? \"CHAR_LENGTH\" : \"length\");\n const grammar = sql`${width}(${payload}) = ${int(pattern.length)} AND ${matches}`;\n const sized =\n pattern.max === undefined\n ? grammar\n : sql`${grammar} AND ${orderedSql(payload, dialect)} <= ${pattern.max}`;\n const prefix = domain.prefix;\n if (!prefix) return sized;\n const spelled = bytesSql(\n sql`substr(${column}, 1, ${int(prefix.length + 1)})`,\n dialect\n );\n return sql`${spelled} = ${`${prefix}-`} AND ${sized}`;\n}\n\n/**\n * The canonical spelling of one stored value, as the bytes it will become:\n * the alias fold for a format that has one, then the dialect's byte pin.\n */\nfunction foldSql(column: Sql, domain: IdDomain, dialect: Dialect): Sql {\n const fold = patternOf(domain).fold;\n const payload = payloadSql(column, domain);\n return bytesSql(\n fold === undefined ? payload : sql`${sql.raw(fold)}(${payload})`,\n dialect\n );\n}\n\n/**\n * `COUNT(col) = COUNT(DISTINCT fold(col))`: the question a UNIQUE column has to\n * answer before its aliases collapse into one another.\n */\nfunction foldCollisionCheck(\n from: Sql,\n column: Sql,\n domain: IdDomain,\n dialect: Dialect\n): MigrationCheckInput {\n return {\n kind: \"trusted-read\",\n query: sql`SELECT COUNT(${column}) = COUNT(DISTINCT ${foldSql(column, domain, dialect)}) AS ok FROM ${from}`,\n equals: true,\n };\n}\n\n/**\n * Whether this column is, BY ITSELF, a complete key of its own model.\n *\n * The fold question belongs to every column that carries a uniqueness\n * constraint through it, and a referencing column often does: the one-to-one\n * child whose primary key IS its foreign key is the ordinary shape, and a\n * `.unique()` foreign key is the other. Asking it of a plain many-side foreign\n * key would refuse every healthy estate on earth — repeats there are the\n * relation — so the catalog decides, not the fact of being a reference.\n *\n * `referenceableKeys` is the right catalog rather than the addressable one: a\n * total unique INDEX no selector can name still refuses a duplicate.\n */\nfunction isSingleColumnKey(model: AnyModel, field: string): boolean {\n return getModelKeyCatalog(model).referenceableKeys.some(\n (key) => key.length === 1 && key[0] === field\n );\n}\n\n/** `SELECT NOT EXISTS (…)`, the shape every row check takes. */\nconst noRowWhere = (from: Sql, predicate: Sql): MigrationCheckInput => ({\n kind: \"trusted-read\",\n query: sql`SELECT NOT EXISTS (SELECT 1 FROM ${from} WHERE ${predicate}) AS ok`,\n equals: true,\n});\n\n/** Every foreign-key column that holds this key's values. */\nfunction referencingColumns(\n request: IdentifierConversionRequest,\n index: ResolvedRelationIndex\n): { model: AnyModel; field: string }[] {\n const columns: { model: AnyModel; field: string }[] = [];\n for (const edge of resolvedEdges(index)) {\n if (edge.kind !== \"foreignKey\") continue;\n const other =\n edge.endpoints[0] === edge.owner ? edge.endpoints[1] : edge.endpoints[0];\n if (other.source !== request.model) continue;\n for (const member of edge.reference.members) {\n if (member.referencedField !== request.field) continue;\n columns.push({ model: edge.owner.source, field: member.foreignField });\n }\n }\n return columns;\n}\n\n/**\n * The pre-checks for converting one key's text column into its identifier\n * column, in the order a conversion needs them.\n *\n * Refuses a field with no compactly stored identifier domain rather than\n * answering with an empty list: an empty list reads as \"this estate is ready\",\n * and that is the one answer a caller who named the wrong field must not get.\n */\nexport function identifierConversionChecks(\n request: IdentifierConversionRequest\n): readonly MigrationCheckInput[] {\n const { model, field, dialect, namespace } = request;\n hydrateSchemaNames(request.schema);\n const index = resolveSchemaOrThrow(request.schema);\n const domain = idDomainOf(model, field, index);\n if (domain === undefined || !isCompactIdFormat(domain.format)) {\n throw new MigrationError(\n `'${getTableName(model)}.${getColumnName(model, field)}' has no compactly stored identifier domain, so it has no text conversion to check: only uuid, uuidv7, ulid and ksuid change storage.`,\n VibORMErrorCode.INVALID_INPUT\n );\n }\n const parent = fromSql(model, dialect, namespace, \"p\");\n const key = columnSql(model, field, dialect, \"p\");\n const checks: MigrationCheckInput[] = [\n noRowWhere(\n parent,\n sql`${key} IS NOT NULL AND NOT (${admitsSql(key, domain, dialect)})`\n ),\n ];\n const folds = patternOf(domain).fold !== undefined;\n if (folds) {\n checks.push(foldCollisionCheck(parent, key, domain, dialect));\n }\n for (const reference of referencingColumns(request, index)) {\n const child = fromSql(reference.model, dialect, namespace, \"c\");\n const fk = columnSql(reference.model, reference.field, dialect, \"c\");\n checks.push(\n noRowWhere(\n child,\n sql`${fk} IS NOT NULL AND NOT (${admitsSql(fk, domain, dialect)})`\n )\n );\n if (folds && isSingleColumnKey(reference.model, reference.field)) {\n checks.push(foldCollisionCheck(child, fk, domain, dialect));\n }\n checks.push(\n noRowWhere(\n child,\n sql`${fk} IS NOT NULL AND NOT EXISTS (SELECT 1 FROM ${parent} WHERE ${foldSql(key, domain, dialect)} = ${foldSql(fk, domain, dialect)})`\n )\n );\n }\n return checks;\n}\n\n// =============================================================================\n// THE ONE AUTOMATED LEG\n// =============================================================================\n\n/** The text column spellings PostgreSQL can hold an identifier in. */\nconst PG_TEXT_COLUMN = /^(?:text|citext|varchar\\(\\d+\\)|character varying.*)$/i;\n\n/** A SQL string literal: the only escape a quoted name needs inside one. */\nconst literal = (text: string): string => `'${text.replaceAll(\"'\", \"''\")}'`;\n\n/**\n * The message PostgreSQL's own `col::uuid` does not give.\n *\n * `ALTER COLUMN … TYPE uuid USING col::uuid` converts value by value: it\n * succeeds for an estate of canonical uuids and raises\n * `invalid input syntax for type uuid: \"…\"` on the first row that is not one,\n * aborting the transaction and leaving the column as it was. The outcome is\n * right; the message names one offending row and nothing about the choice the\n * author actually has. This runs FIRST, inside the same transaction, and says\n * how many rows are in the way and what the two routes are.\n *\n * A PREFIXED domain fails here too, and deliberately: `usr-a0ee…` is not uuid\n * text, and no `USING substring(col from 5)::uuid` is emitted for it, because\n * the snapshot carries the column TYPE and not the domain — the prefix is a\n * fact of the declaration that no migration artifact has ever held. Converting\n * a prefixed column is a manual route, and this says so before anything runs.\n *\n * It is not a second refusal: without it the conversion fails anyway. Its whole\n * and only coverage is the message.\n */\nexport function postgresTextToUuidGuard(\n qualifiedTable: string,\n quotedColumn: string\n): string {\n const marker = `${qualifiedTable}.${quotedColumn}`;\n return (\n \"DO $viborm$ DECLARE invalid bigint; BEGIN \" +\n `SELECT count(*) INTO invalid FROM ${qualifiedTable} WHERE ${quotedColumn} IS NOT NULL AND ${quotedColumn} !~ ${literal(PATTERNS.uuid.regex)}; ` +\n \"IF invalid > 0 THEN RAISE EXCEPTION \" +\n `${literal(`VibORM: % row(s) of ${marker} 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; ` +\n \"END IF; END $viborm$\"\n );\n}\n\n/** Whether this alteration is the one text→identifier conversion pg performs. */\nexport function isPostgresTextToUuid(\n fromType: string,\n toType: string\n): boolean {\n return (\n toType.toLowerCase() === \"uuid\" && PG_TEXT_COLUMN.test(fromType.trim())\n );\n}\n"],"mappings":"8aAgGA,MAAM,EAAM,cACN,EAAY,kCACZ,EAAS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AQ,QAAQ,EAAU,MAAO,EAAS,EAAW,IAAI,CACzD,EAAK,UAAU,EAAU,MAAO,EAAU,MAAO,EAAS,IAAI,CACpE,EAAO,KACL,WACE,EACA,CAAG,GAAG,EAAG,wBAAwB,UAAU,EAAI,EAAQ,EAAQ,CAAC,GACjE,CACF,CACG,GAAS,kBAAkB,EAAU,MAAO,EAAU,MAAM,EAC9D,EAAO,KAAK,mBAAmB,EAAO,EAAI,EAAQ,EAAQ,CAAC,CAE7D,EAAO,KACL,WACE,EACA,CAAG,GAAG,EAAG,6CAA6C,EAAO,SAAS,QAAQ,EAAK,EAAQ,EAAQ,CAAC,KAAK,QAAQ,EAAI,EAAQ,EAAQ,CAAC,GACvI,CACF,CAEH,OAAO,EAQT,MAAM,EAAiB,wDAGjB,QAAW,GAAyB,IAAI,EAAK,WAAW,IAAK,KAAK,CAAC,GAsBzE,SAAgB,wBACd,EACA,EACQ,CACR,IAAM,EAAS,GAAG,EAAe,GAAG,IACpC,MACE,iFACqC,EAAe,SAAS,EAAa,mBAAmB,EAAa,MAAM,QAAQ,EAAS,KAAK,MAAM,CAAC,wCAE1I,QAAQ,uBAAuB,EAAO,0aAA0a,CAAC,mCAMxd,SAAgB,qBACd,EACA,EACS,CACT,OACE,EAAO,aAAa,GAAK,QAAU,EAAe,KAAK,EAAS,MAAM,CAAC"}
@@ -0,0 +1,2 @@
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";const createIdentifierQuoter=e=>{let t=new Map;return n=>{let r=t.get(n);if(r!==void 0)return r;let i=e+(n.indexOf(e)===-1?n:n.replaceAll(e,e+e))+e;return t.size<4096&&t.set(n,i),i}},qualifiedPrefix=(e,t)=>`${e(t)}.`,renderQualifiedIdentifier=(e,t,n)=>t===void 0?e(n):qualifiedPrefix(e,t)+e(n),createQualifiedIdentifierRenderer=(e,t)=>{if(t===void 0)return e;let n=qualifiedPrefix(e,t);return t=>n+e(t)};export{createQualifiedIdentifierRenderer as n,renderQualifiedIdentifier as r,createIdentifierQuoter as t};
2
+ //# sourceMappingURL=identifiers-BTCfD5ic.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"identifiers-BTCfD5ic.mjs","names":[],"sources":["../src/sql/identifiers.ts"],"sourcesContent":["/**\n * Identifier text primitives.\n *\n * Quoting one name for a dialect, and composing a namespace-qualified object\n * name, are string concerns with no `Sql` involvement: runtime adapters wrap the\n * result in `Sql`, migration drivers splice it into DDL text. Both pass their\n * own quoter — the two differ in escape semantics and null handling — so what is\n * shared here is the composition rule alone, and it has one owner.\n */\n\n/** Quote a single identifier for the dialect: `\"name\"` or `` `name` ``. */\nexport type IdentifierQuoter = (name: string) => string;\n\n/** Build an identifier quoter that doubles embedded quote characters to prevent SQL injection. */\nexport const createIdentifierQuoter = (\n quoteChar: '\"' | \"`\"\n): IdentifierQuoter => {\n // The names a statement quotes are its schema's and its own aliases, the\n // same few on every call: each is quoted once. Bounded, so names a caller\n // invents cannot grow it without end.\n const quoted = new Map<string, string>();\n return (name: string): string => {\n const known = quoted.get(name);\n if (known !== undefined) return known;\n const text =\n quoteChar +\n (name.indexOf(quoteChar) === -1\n ? name\n : name.replaceAll(quoteChar, quoteChar + quoteChar)) +\n quoteChar;\n if (quoted.size < 4096) quoted.set(name, text);\n return text;\n };\n};\n\n/**\n * The one qualification rule. A present namespace contributes a quoted prefix;\n * an absent one contributes nothing, which is what unbound MySQL and every\n * SQLite adapter mean.\n */\nconst qualifiedPrefix = (\n quoteIdentifier: IdentifierQuoter,\n namespace: string\n): string => `${quoteIdentifier(namespace)}.`;\n\n/**\n * Compose one namespace-qualified object name. The namespace must already be\n * normalized: this primitive validates nothing, holds nothing, and returns text\n * for exactly one object.\n */\nexport const renderQualifiedIdentifier = (\n quoteIdentifier: IdentifierQuoter,\n namespace: string | undefined,\n object: string\n): string =>\n namespace === undefined\n ? quoteIdentifier(object)\n : qualifiedPrefix(quoteIdentifier, namespace) + quoteIdentifier(object);\n\n/**\n * Bind one namespace so its prefix is quoted once per adapter rather than once\n * per rendered statement. The returned function renders exactly what\n * `renderQualifiedIdentifier` would for the same namespace.\n */\nexport const createQualifiedIdentifierRenderer = (\n quoteIdentifier: IdentifierQuoter,\n namespace: string | undefined\n): IdentifierQuoter => {\n if (namespace === undefined) {\n return quoteIdentifier;\n }\n const prefix = qualifiedPrefix(quoteIdentifier, namespace);\n return (object: string): string => prefix + quoteIdentifier(object);\n};\n"],"mappings":"yCAcA,MAAa,uBACX,GACqB,CAIrB,IAAM,EAAS,IAAI,IACnB,MAAQ,IAAyB,CAC/B,IAAM,EAAQ,EAAO,IAAI,EAAK,CAC9B,GAAI,IAAU,IAAA,GAAW,OAAO,EAChC,IAAM,EACJ,GACC,EAAK,QAAQ,EAAU,GAAK,GACzB,EACA,EAAK,WAAW,EAAW,EAAY,EAAU,EACrD,EAEF,OADI,EAAO,KAAO,MAAM,EAAO,IAAI,EAAM,EAAK,CACvC,IASL,iBACJ,EACA,IACW,GAAG,EAAgB,EAAU,CAAC,GAO9B,2BACX,EACA,EACA,IAEA,IAAc,IAAA,GACV,EAAgB,EAAO,CACvB,gBAAgB,EAAiB,EAAU,CAAG,EAAgB,EAAO,CAO9D,mCACX,EACA,IACqB,CACrB,GAAI,IAAc,IAAA,GAChB,OAAO,EAET,IAAM,EAAS,gBAAgB,EAAiB,EAAU,CAC1D,MAAQ,IAA2B,EAAS,EAAgB,EAAO"}
package/dist/index.d.mts CHANGED
@@ -1,3 +1,3 @@
1
- import { $ as DelegateOperationPayload, $a as QueryEngineError, $n as row, $t as VectorScalar, A as Extension, Ai as PointSchema, An as rule, Ar as WriteOutcome, At as UpdateState$1, B as StampedFields, Ba as ValidationError, Bi as InitialModelState, Bn as modelMethods, Br as SchemaValidationError, C as ArgTest, Ci as BlobScalar, Cn as run, Co as VibORMError, Cr as renderSchemaType, Ct as BigIntScalar, D as ConfiguredBy, Da as ReferentialAction, Di as VectorSchema, Dn as text, Do as toPrismaErrorCode, Dr as UnwrapPendingOperation, Dt as InitialScalarState, E as CallResult, En as table, Eo as isVibORMError, Er as PendingOperation, Et as GeneratorDefaultBrand, F as Part, Fi as isFieldRef, Fn as selecting, Fo as GeoPoint, G as UnitOutcome, Ga as ClientInitializationError, Gn as keep, H as TargetOf, Ha as isValidationError, Hi as ModelInternal, Hn as check, Hr as SchemaValidationIssue, I as Parts, Ii as AnyModel, In as target, Io as GeoPolygon, Ir as InsertValueContext, J as AddedProjectedState, Ja as ForbiddenError, Ji as NumberSchema, Jn as arg, K as Watcher, Ka as ConnectionError, Kn as lazy, L as PlacedArgument, Li as IndexDefinition, Ln as writes, Lo as DecimalDescriptor, Lr as ModelSql, M as NoArguments, Mi as FieldRef, Mn as deletes, Mr as around, N as OperationSet, Ni as ModelFieldRefs, Nn as models, No as GeoArea, Nr as call, O as EmptyFacts, Oa as RelationCardinality, Oi as StringSchema, On as unit, Oo as wrapError, Or as UnwrapPendingOperations, Ot as ScalarState, P as Outcome, Pi as createModelFieldRefs, Pn as reads, Po as GeoBounds, Q as DelegateOperationArgs, Qa as PendingOperationError, Qi as JsonValue, Qn as provided, Qt as NumericScalar, R as Run, Ri as IndexOptions, Rn as work, Ro as Decimal, Rr as validateSchema, S as AnyTarget, Si as BooleanScalar, Sn as parameters, So as PrismaErrorCode, Sr as renderOperationResultType, St as Scalar, T as CallContext, Ta as Getter, Tn as statements, To as isRetryableError, Tr as ProjectedModelOperations, U as UnitContext, Ua as InvalidTransactionInputError, Ui as ModelState, Un as facts, Ur as Severity, V as Target, Va as ValidationErrorSource, Vi as Model, Vn as key, Vr as isSchemaValidationError, Vt as VibSchema, W as UnitKind, Wa as TransactionError, Wi as UpdateState, Wn as gate, Wr as ValidationResult, X as ClientTypeState, Xa as NestedWriteError, Xi as InputJsonValue, Xn as nothing, Ya as NestedWriteAssertionError, Yn as exists, Z as DelegateConfig, Za as NotFoundError, Zi as JsonSchema, Zn as now, _a as DbNull, _i as ReferencesStage, _n as driver, _o as isValueTooLongError, _r as accepts, _t as RowsFragment, aa as ObjectSchema, an as EnumScalar, ao as isUnsupportedOperationError, ar as DisclosurePolicy, at as TransactionClient, b as AnyCallContext, ba as JsonNullSentinel, bi as DateTimeScalar, bn as notes, bo as CacheInvalidTTLError, br as oneOf, bt as VariantToManyRelation, ca as DecimalSchema, cn as getSchemas, co as CheckConstraintError, cr as omitted, ct as VibORMConfig, di as FlatSchema, dn as JoinedSource, do as UniqueConstraintError, dr as within, dt as ChainedExtensionState, en as StringScalar, eo as QueryError, er as unless, et as DelegateOperationResult, fa as BlobSchema, fi as Linked, fn as computed, fo as ValueTooLongError, fr as Codec, ft as ClientExtensionState, ga as AnyNull, gi as ModelToOneRelation, gn as correlation, go as isUniqueConstraintError, gr as watch, gt as RawOperation, ha as AnyJsonNullSentinel, hi as RelationLinks, hn as BatchMember, ho as isNotNullConstraintError, hr as via, ht as ExtensionStateConstraint, ia as IsoTimestampSchema, in as IntScalar, io as isPendingOperationError, ir as disclosed, j as Facts, ji as AnyFieldRef, jn as parts, jr as WriteKind, k as Exact, ka as RelationSlot, kn as settled, ko as DiagnosticDisclosure, kr as isPendingOperation, ln as getRowKey, lo as ForeignKeyError, lr as Database, lt as createClient, ma as BigIntSchema, mi as Links, mn as stored, mo as isForeignKeyError, mr as again, mt as ExtensionResultConsumerState, na as IsoDateSchema, ni as Schema, nn as NumberScalar, no as isClientInitializationError, nr as fields, nt as ExtendedClient, oi as ClientHiddenContext, on as DecimalScalar, oo as MigrationError, or as disclosure, ot as TransactionClientOf, pi as LinkedClientConfig, pn as joined, po as isCheckConstraintError, pr as codec, pt as EmptyClientExtensionState, q as With, qa as FeatureNotSupportedError, qi as IntegerSchema, qn as only, ra as IsoTimeSchema, rn as JsonScalar, ro as isNotFoundError, rr as extension, rt as ExtendedOperationResult, sa as EnumSchema, sn as s, so as isMigrationError, sr as defaults, st as VibORMClient, tn as PointScalar, to as UnsupportedOperationError, tr as when, ua as BooleanSchema, ui as ClientSchema, un as VIBORM_VERSION, uo as NotNullConstraintError, ur as database, ut as AddedExtensionState, va as JsonNull, vi as ModelToManyRelation, vn as failure, vo as CacheConfigurationError, vr as args, vt as ModelShape, w as BoundAccepted, wa as AnyRelation, wn as statement, wo as VibORMErrorCode, wr as validateOperationPayload, wt as AutoGenerate, x as AnyFacts, xa as isJsonNullSentinel, xi as DateScalar, xn as origin, xo as CacheOperationNotCacheableError, xr as getOperationPayloadSchema, xt as VariantToOneRelation, y as Accepted, ya as JsonNullKind, yi as TimeScalar, yn as note, yo as CacheInvalidKeyError, yr as bound, yt as ScalarKeys, z as Selection, zn as methods, zr as validateSchemaOrThrow } from "./database-adapter-BGqvjeEy.mjs";
2
- import { a as isSql, c as sqlTag, i as empty, n as Sql, o as join, r as Value, s as raw, t as RawValue } from "./sql-BVZ8QefY.mjs";
1
+ import { $ as With, $n as only, A as BoundAccepted, Aa as AnyNull, Ai as BooleanScalar, An as statement, Ao as CacheInvalidKeyError, Ar as validateOperationPayload, At as AutoGenerate, B as Outcome, Bi as FieldRef, Bn as reads, Bo as DiagnosticDisclosure, Ci as RelationLinks, Cn as driver, Co as ValueTooLongError, Cr as accepts, Ct as RowsFragment, D as AnyFacts, Di as TimeScalar, Dn as origin, Do as isUniqueConstraintError, Dr as getOperationPayloadSchema, Dt as VariantToOneRelation, E as AnyCallContext, Ea as BlobSchema, Ei as ModelToManyRelation, En as notes, Eo as isNotNullConstraintError, Er as oneOf, Et as VariantToManyRelation, F as Exact, Fa as isJsonNullSentinel, Fi as VectorSchema, Fn as settled, Fo as VibORMErrorCode, Fr as isPendingOperation, G as Selection, Gi as IndexDefinition, Gn as methods, Gr as validateSchemaOrThrow, H as Parts, Ha as RelationCardinality, Hi as createModelFieldRefs, Hn as target, Hr as InsertValueContext, I as Extension, Ii as StringSchema, In as rule, Io as isRetryableError, Ir as WriteOutcome, It as UpdateState$1, J as TargetOf, Ji as InitialModelState, Jn as check, Jr as SchemaValidationIssue, K as StampedFields, Ki as IndexOptions, Kn as modelMethods, Kr as SchemaValidationError, L as Facts, Ln as parts, Lo as isVibORMError, Lr as WriteKind, M as CallResult, Ma as JsonNull, Mn as table, Mo as CacheOperationNotCacheableError, Mr as PendingOperation, Mt as GeneratorDefaultBrand, N as ConfiguredBy, Na as JsonNullKind, Nn as text, No as PrismaErrorCode, Nr as UnwrapPendingOperation, Nt as InitialScalarState, O as AnyTarget, Oa as BigIntSchema, Oi as DateTimeScalar, On as parameters, Oo as isValueTooLongError, Or as renderOperationResultType, Ot as Scalar, P as EmptyFacts, Pa as JsonNullSentinel, Pn as unit, Po as VibORMError, Pr as UnwrapPendingOperations, Pt as ScalarState, Q as Watcher, Qi as UpdateState, Qn as lazy, R as NoArguments, Ra as AnyRelation, Ri as PointSchema, Rn as deletes, Ro as toPrismaErrorCode, Rr as around, Sa as Decimal, Si as Links, Sn as correlation, So as UniqueConstraintError, Sr as watch, St as RawOperation, T as Accepted, Ti as ReferencesStage, Tn as note, To as isForeignKeyError, Tr as bound, Tt as ScalarKeys, U as PlacedArgument, Ua as RelationSlot, Ui as isFieldRef, Un as writes, Ur as ModelSql, V as Part, Va as ReferentialAction, Vi as ModelFieldRefs, Vn as selecting, W as Run, Wi as AnyModel, Wn as work, Wr as validateSchema, X as UnitKind, Xi as ModelInternal, Xn as gate, Xr as ValidationResult, Y as UnitContext, Yi as Model, Yn as facts, Yr as Severity, Z as UnitOutcome, Zi as ModelState, Zn as keep, _a as ObjectSchema, _n as JoinedSource, _o as MigrationError, _r as within, _t as ChainedExtensionState, aa as JsonSchema, an as VectorScalar, ao as ForbiddenError, ar as row, at as DelegateOperationPayload, ba as DecimalSchema, bi as Linked, bn as stored, bo as ForeignKeyError, br as again, bt as ExtensionResultConsumerState, cn as NumberScalar, co as NotFoundError, cr as fields, ct as ExtendedClient, d as ValidationErrorSource, da as IsoTimeSchema, dn as EnumScalar, do as QueryError, dr as DisclosurePolicy, dt as TransactionClient, eo as InvalidTransactionInputError, er as arg, et as AddedProjectedState, f as isValidationError, fa as IsoTimestampSchema, fn as DecimalScalar, fo as UnsupportedOperationError, fr as disclosure, ft as TransactionClientOf, ga as GeoPolygon, gn as VIBORM_VERSION, go as isUnsupportedOperationError, gr as database, gt as AddedExtensionState, ha as GeoPoint, hn as getRowKey, ho as isPendingOperationError, hr as Database, ht as createClient, ia as InputJsonValue, in as NumericScalar, io as FeatureNotSupportedError, ir as provided, it as DelegateOperationArgs, j as CallContext, ja as DbNull, ji as BlobScalar, jn as statements, jo as CacheInvalidTTLError, jr as ProjectedModelOperations, k as ArgTest, ka as AnyJsonNullSentinel, ki as DateScalar, kn as run, ko as CacheConfigurationError, kr as renderSchemaType, kt as BigIntScalar, li as Schema, ln as JsonScalar, lo as PendingOperationError, lr as extension, lt as ExtendedOperationResult, ma as GeoBounds, mn as getSchemas, mo as isNotFoundError, mr as omitted, mt as VibORMConfig, na as NumberSchema, no as ClientInitializationError, nr as nothing, nt as ClientTypeState, oa as JsonValue, on as StringScalar, oo as NestedWriteAssertionError, or as unless, ot as DelegateOperationResult, pa as GeoArea, pi as ClientHiddenContext, pn as s, po as isClientInitializationError, pr as defaults, pt as VibORMClient, q as Target, qn as key, qr as isSchemaValidationError, qt as VibSchema, ro as ConnectionError, rr as now, rt as DelegateConfig, sn as PointScalar, so as NestedWriteError, sr as when, ta as IntegerSchema, to as TransactionError, tr as exists, u as ValidationError, ua as IsoDateSchema, un as IntScalar, uo as QueryEngineError, ur as disclosed, vi as ClientSchema, vn as computed, vo as isMigrationError, vr as Codec, vt as ClientExtensionState, wa as BooleanSchema, wi as ModelToOneRelation, wn as failure, wo as isCheckConstraintError, wr as args, wt as ModelShape, xa as DecimalDescriptor, xi as LinkedClientConfig, xn as BatchMember, xo as NotNullConstraintError, xr as via, xt as ExtensionStateConstraint, ya as EnumSchema, yi as FlatSchema, yn as joined, yo as CheckConstraintError, yr as codec, yt as EmptyClientExtensionState, z as OperationSet, za as Getter, zi as AnyFieldRef, zn as models, zo as wrapError, zr as call } from "./database-adapter-D62c-uC6.mjs";
2
+ import { a as isSql, c as sqlTag, i as empty, n as Sql, o as join, r as Value, s as raw, t as RawValue } from "./sql-CXtSIPzy.mjs";
3
3
  export { Accepted, type AddedExtensionState, type AddedProjectedState, AnyCallContext, AnyFacts, type AnyFieldRef, type AnyJsonNullSentinel, type AnyModel, AnyNull, type AnyRelation, AnyTarget, ArgTest, type AutoGenerate, BatchMember, type BigIntScalar, type BigIntSchema, type BlobScalar, type BlobSchema, type BooleanScalar, type BooleanSchema, BoundAccepted, CacheConfigurationError, CacheInvalidKeyError, CacheInvalidTTLError, CacheOperationNotCacheableError, CallContext, CallResult, type ChainedExtensionState, CheckConstraintError, type ClientExtensionState, type ClientHiddenContext, ClientInitializationError, type ClientSchema, type ClientTypeState, Codec, type InsertValueContext as ComputedContext, ConfiguredBy, ConnectionError, Database, type DateScalar, type DateTimeScalar, DbNull, Decimal, type DecimalDescriptor, type DecimalScalar, type DecimalSchema, type DelegateConfig, type DelegateOperationArgs, type DelegateOperationPayload, type DelegateOperationResult, type DiagnosticDisclosure, DisclosurePolicy, type EmptyClientExtensionState, EmptyFacts, type EnumScalar, type EnumSchema, Exact, type ExtendedClient, type ExtendedOperationResult, Extension, type ExtensionResultConsumerState, type ExtensionStateConstraint as ExtensionState, Facts, FeatureNotSupportedError, type FieldRef, type FlatSchema, ForbiddenError, ForeignKeyError, type GeneratorDefaultBrand, type GeoArea, type GeoBounds, type GeoPoint, type GeoPolygon, type Getter, type IndexDefinition, type IndexOptions, type InitialModelState, type InitialScalarState, type InputJsonValue, type IntScalar, type IntegerSchema, InvalidTransactionInputError, type IsoDateSchema, type IsoTimeSchema, type IsoTimestampSchema, type JoinedSource, JsonNull, type JsonNullKind, JsonNullSentinel, type JsonScalar, type JsonValue, type JsonSchema as JsonValueSchema, type Linked, type LinkedClientConfig, type Links, MigrationError, type Model, type ModelFieldRefs, type ModelInternal, type ModelShape, type ModelSql, type ModelState, type ModelToManyRelation, type ModelToOneRelation, type UpdateState as ModelUpdateState, NestedWriteAssertionError, NestedWriteError, type NoArguments, NotFoundError, NotNullConstraintError, type NumberScalar, type NumberSchema, type NumericScalar, type ObjectSchema, OperationSet, Outcome, Part, Parts, PendingOperation, PendingOperationError, type PlacedArgument, type PointScalar, type PointSchema, type PrismaErrorCode, type ProjectedModelOperations, QueryEngineError, QueryError, type RawOperation, type RawValue, type ReferencesStage, type ReferentialAction, type RelationCardinality, type RelationLinks, type RelationSlot, type RowsFragment, Run, type Scalar, type ScalarKeys, type ScalarState, type UpdateState$1 as ScalarUpdateState, type Schema, SchemaValidationError, type SchemaValidationIssue, Selection, type Severity, Sql, type StampedFields, type StringScalar, type StringSchema, Target, TargetOf, type TimeScalar, type TransactionClient, type TransactionClientOf, TransactionError, UniqueConstraintError, UnitContext, UnitKind, UnitOutcome, UnsupportedOperationError, type UnwrapPendingOperation, type UnwrapPendingOperations, VIBORM_VERSION, ValidationError, type ValidationErrorSource, type ValidationResult, type Value, ValueTooLongError, type VariantToManyRelation, type VariantToOneRelation, type VectorScalar, type VectorSchema, type VibORMClient, type VibORMConfig, VibORMError, VibORMErrorCode, type VibSchema, Watcher, With, WriteKind, WriteOutcome, accepts, again, arg, args, around, bound, call, check, codec, computed, correlation, createClient, createModelFieldRefs, database, defaults, deletes, disclosed, disclosure, driver, empty, exists, extension, facts, failure, fields, gate, getOperationPayloadSchema, getRowKey, getSchemas, isCheckConstraintError, isClientInitializationError, isFieldRef, isForeignKeyError, isJsonNullSentinel, isMigrationError, isNotFoundError, isNotNullConstraintError, isPendingOperation, isPendingOperationError, isRetryableError, isSchemaValidationError, isSql, isUniqueConstraintError, isUnsupportedOperationError, isValidationError, isValueTooLongError, isVibORMError, join, joined, keep, key, lazy, methods, modelMethods, models, note, notes, nothing, now, omitted, oneOf, only, origin, parameters, parts, provided, raw, reads, renderOperationResultType, renderSchemaType, row, rule, run, s, selecting, settled, sqlTag as sql, statement, statements, stored, table, target, text, toPrismaErrorCode, unit, unless, validateOperationPayload, validateSchema, validateSchemaOrThrow, via, watch, when, within, work, wrapError, writes };
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{A as t,C as n,D as r,E as i,O as a,S as o,T as s,b as c,j as l,k as u,v as d,w as f,x as p,y as m}from"./error-mapping-B1-IWkCQ.mjs";import{a as h,i as g,n as _,o as v,s as y,t as b}from"./base-z-cH5ZBI.mjs";import{n as ee,t as te}from"./migrations-BMiRjR-N.mjs";import{_ as ne,a as re,c as ie,d as ae,f as oe,g as se,h as ce,i as le,l as ue,m as de,n as fe,o as pe,p as x,r as S,t as C,u as w,v as T}from"./validation--qS7OPmg.mjs";import{n as E,t as D}from"./transaction-BNomMtme.mjs";import{a as O,i as k,n as A,o as j,r as M,t as N}from"./sql-3o4DOKm9.mjs";import{o as P}from"./value-guards-CBuxSC66.mjs";import{r as F,t as I}from"./extension-CGepsF-p.mjs";import{H as L}from"./native-types-DgjMUikz.mjs";import{J as R,Q as z,X as B,Y as me,Z as he,_ as ge,et as _e,rt as ve,v as ye}from"./scalar-BHCh7aUz.mjs";import{a as be,g as xe,i as Se}from"./validator-CZLW7aR3.mjs";import{r as Ce,t as we}from"./pending-operation-C_eOFOBE.mjs";import{a as Te,i as Ee,r as De,t as Oe}from"./client-DRpX3-vw.mjs";import{c as V,i as ke}from"./validation-CYaJ8ndO.mjs";import{i as Ae,n as je,r as Me,t as Ne}from"./schema-introspection-D0f8cti4.mjs";import{n as H,t as U}from"./methods-part-ZY0f2AV_.mjs";import{a as Pe,c as W,l as Fe,n as Ie,o as Le,r as Re}from"./on-ylYaKuRu.mjs";import{i as ze,n as G,r as Be,t as Ve}from"./args-764KdWMr.mjs";import{n as K,t as q}from"./call-Cz8XUmrl.mjs";import{i as He,n as Ue,r as We,t as Ge}from"./settled-BjyuA76m.mjs";import{n as Ke,r as qe,t as Je}from"./key-hxFFCKed.mjs";import{a as Ye,c as Xe,d as Ze,i as Qe,o as $e,r as et,s as tt,u as nt}from"./rule-words-ZIGm7cDm.mjs";import{a as rt,c as J,i as it,n as at,o as ot,r as st,s as ct}from"./judge-words-CzUyXtJ6.mjs";import{t as lt}from"./confine-DqFBTUw6.mjs";import{n as ut,t as Y}from"./defaults-DwOHWI_M.mjs";import{n as X,r as dt,t as Z}from"./unit-BhHbZyuJ.mjs";import{a as ft,c as pt,d as mt,f as ht,h as gt,i as _t,l as vt,n as yt,o as bt,r as Q,s as xt,t as St,u as Ct}from"./unit-words-CT0yeqfZ.mjs";import{n as wt,r as Tt,t as Et}from"./values-B4aj1i1f.mjs";import{t as Dt}from"./schema-CFIaebgi.mjs";import{t as Ot}from"./version-CXGIA82S.mjs";const $=`$allModels`,kt=new Set([`createMany`,`updateMany`,`deleteMany`]);function planNode(e,t,n,r){let i=e[n[`~`].names.ts]??[],a=P(r?.select)?r.select:void 0,o=P(r?.include)?r.include:void 0,s=P(r?.omit)?r.omit:void 0,c=[],l=a??o,u=l;if(l!==void 0){let r=t.get(n);for(let i of Object.keys(l)){let a=r?.get(i),o=l[i];if(!a||Ee(a)||o!==!0&&!P(o))continue;let s=Te(a,n),d=o===!0?void 0:o,f=planNode(e,t,s,d);f!==void 0&&(c.push([i,f.node]),d?.recurse!==void 0&&f.node.relations.push([i,f.node]),f.args!==d&&(u={...u,[i]:f.args}))}}let d=new Map;for(let[e,t]of i.entries())d.set(t.name,e);let kept=e=>(a?a[e]===!0:!0)&&s?.[e]!==!0,f=[],p=!1;for(let[e,t]of d)p||=(a??s)?.[e]!==void 0,kept(e)&&f.push(t);if(f.length===0&&c.length===0&&!p)return;let m=new Set,h=new Set,close=e=>{if(!m.has(e)){m.add(e);for(let t of i[e].needs)typeof t==`number`?close(t):h.add(t)}};for(let e of f)close(e);let g=new Set;for(let e of h)kept(e)||g.add(e);let _=r;if(s!==void 0){let e={...s};for(let t of d.keys())s[t]!==void 0&&!Object.hasOwn(n[`~`].state.scalars,t)&&delete e[t];for(let t of h)s[t]===!0&&(e[t]=!1);_={..._,omit:e}}if(a!==void 0){let e={...u};for(let t of d.keys())delete e[t];for(let t of h)e[t]=!0;if(!Object.values(e).some(e=>e!==!1)){let[t]=V(n);t!==void 0&&(e[t]=!0,kept(t)||g.add(t))}_={..._,select:e}}else u!==l&&(_={..._,include:u});return{args:_,node:{fields:i,outputs:f,reads:[...h],strip:[...g],relations:c}}}function finishValue(e,t){return Array.isArray(e)?e.map(e=>finishRow(e,t)):finishRow(e,t)}function finishRow(t,n){if(!P(t))return t;let r={...t};for(let[e,t]of n.relations)r[e]!==void 0&&(r[e]=finishValue(r[e],t));for(let e of n.strip)delete r[e];let i=t;for(let e of n.reads){let n=t[e];typeof n!=`object`||!n||(i===t&&(i={...t}),i[e]=detached(n))}let a=new Map,o=e(e=>{if(a.has(e))return a.get(e);let t=n.fields[e],r={};for(let e of t.needs)typeof e==`number`?r[n.fields[e].name]=o(e):r[e]=i[e];let s=t.compute(r);return a.set(e,s),s},`computed`);for(let e of n.outputs){let t=n.fields[e].name,settle=e=>(Object.defineProperty(r,t,{value:e,writable:!0,enumerable:!0,configurable:!0}),e);Object.defineProperty(r,t,{get:()=>settle(o(e)),set:settle,enumerable:!0,configurable:!0})}return r}function detached(e){if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return e.map(detached);if(e instanceof Date)return new Date(e.getTime());if(ArrayBuffer.isView(e))return Object.getPrototypeOf(Uint8Array.prototype).slice.call(e);let t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)return e;let n={};for(let t in e)n[t]=detached(e[t]);return n}function fieldsPart(e){return{join({next:t,name:n,schema:r}){for(let t of Object.keys(e))t!==$&&!Object.hasOwn(r,t)&&F(`Extension "${n}" result names unknown model "${t}".`,n);let i={...t.fields?.fields};for(let t of Object.keys(r)){let a=r[t],o=[...i[t]??[]],s=new Set(V(a));for(let r of[$,t])for(let[i,{needs:c={},compute:l}]of Object.entries(e[r]??{})){let e=`Extension "${n}" result.${r}.${i}`;(i===`_count`||Object.hasOwn(a[`~`].state.relations,i))&&F(`${e} cannot be computed: "${i}" is a relation of model "${t}".`,n);let u=Object.keys(c).filter(e=>c[e]).map(r=>{for(let e=o.length-1;e>=0;e--)if(o[e].name===r)return e;return s.has(r)?r:F(`${e} needs "${r}", which is not a readable scalar or an earlier computed field of model "${t}".`,n)});o.push({name:i,compute:l,needs:u})}o.length>0&&(i[t]=o)}t.fields={fields:i,plan:(e,t,n,r)=>{if(!(De.has(n)||kt.has(n)&&(r.select!==void 0||r.omit!==void 0)))return;let a=planNode(i,e,t,r);if(a===void 0)return;let{node:o}=a;return{args:a.args,finish:e=>finishValue(e,o)}}}}}}function fields(e){return fieldsPart(e)}function parts(){return{extension:I,call:K,around:q,target:W,unit:Z,rule:J,defaults:Y,disclosure:X,args:G,methods:U,modelMethods:H,fields}}const getSchemas=e=>ke(e).proxy;export{R as AnyNull,a as CacheConfigurationError,u as CacheInvalidKeyError,t as CacheInvalidTTLError,l as CacheOperationNotCacheableError,d as CheckConstraintError,S as ClientInitializationError,le as ConnectionError,me as DbNull,L as Decimal,re as FeatureNotSupportedError,pe as ForbiddenError,m as ForeignKeyError,D as InvalidTransactionInputError,B as JsonNull,he as JsonNullSentinel,te as MigrationError,ie as NestedWriteAssertionError,ue as NestedWriteError,w as NotFoundError,c as NotNullConstraintError,we as PendingOperation,ae as PendingOperationError,oe as QueryEngineError,x as QueryError,ge as SchemaValidationError,N as Sql,E as TransactionError,p as UniqueConstraintError,de as UnsupportedOperationError,Ot as VIBORM_VERSION,C as ValidationError,o as ValueTooLongError,b as VibORMError,_ as VibORMErrorCode,Ve as accepts,Ue as again,et as arg,G as args,q as around,Be as bound,K as call,at as check,qe as codec,Et as computed,St as correlation,Oe as createClient,_e as createModelFieldRefs,Ke as database,Y as defaults,Ie as deletes,dt as disclosed,X as disclosure,yt as driver,A as empty,Qe as exists,I as extension,st as facts,Q as failure,fields,it as gate,Ne as getOperationPayloadSchema,xe as getRowKey,getSchemas,n as isCheckConstraintError,ce as isClientInitializationError,ve as isFieldRef,f as isForeignKeyError,z as isJsonNullSentinel,ee as isMigrationError,se as isNotFoundError,s as isNotNullConstraintError,Ce as isPendingOperation,ne as isPendingOperationError,g as isRetryableError,ye as isSchemaValidationError,M as isSql,i as isUniqueConstraintError,T as isUnsupportedOperationError,fe as isValidationError,r as isValueTooLongError,h as isVibORMError,k as join,wt as joined,rt as keep,Je as key,ot as lazy,U as methods,H as modelMethods,Re as models,_t as note,ft as notes,Ye as nothing,$e as now,ut as omitted,ze as oneOf,ct as only,bt as origin,xt as parameters,parts,tt as provided,O as raw,Pe as reads,je as renderOperationResultType,Me as renderSchemaType,Xe as row,J as rule,pt as run,Dt as s,Le as selecting,Ge as settled,j as sql,vt as statement,Ct as statements,Tt as stored,mt as table,W as target,ht as text,v as toPrismaErrorCode,Z as unit,nt as unless,Ae as validateOperationPayload,Se as validateSchema,be as validateSchemaOrThrow,We as via,He as watch,Ze as when,lt as within,gt as work,y as wrapError,Fe as writes};
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{A as t,C as n,D as r,E as i,O as a,S as o,T as s,b as c,j as l,k as u,v as d,w as f,x as p,y as m}from"./error-mapping-DIRlrmDK.mjs";import{a as h,i as g,n as _,o as v,s as y,t as b}from"./base-z-cH5ZBI.mjs";import{n as ee,t as te}from"./migrations-BMiRjR-N.mjs";import{_ as ne,a as re,c as ie,d as ae,f as oe,g as se,h as ce,i as le,l as ue,m as de,n as fe,o as pe,p as x,r as S,t as C,u as w,v as T}from"./validation--qS7OPmg.mjs";import{n as E,t as D}from"./transaction-BNomMtme.mjs";import{a as O,i as k,n as A,o as j,r as M,t as N}from"./sql-BGjAsoBE.mjs";import{o as P}from"./value-guards-CBuxSC66.mjs";import{r as F,t as I}from"./extension-CGepsF-p.mjs";import{H as L}from"./native-types-DspZ0Z5E.mjs";import{J as R,Q as z,X as B,Y as me,Z as he,_ as ge,et as _e,rt as ve,v as ye}from"./scalar-B9WizsvR.mjs";import{a as be,g as xe,i as Se}from"./validator-CDYlO9HV.mjs";import{r as Ce,t as we}from"./pending-operation-Dq4rv-Ml.mjs";import{a as Te,i as Ee,r as De,t as Oe}from"./client-CVCC-D1j.mjs";import{c as V,i as ke}from"./validation-D0LG854o.mjs";import{i as Ae,n as je,r as Me,t as Ne}from"./schema-introspection-wMVZowIF.mjs";import{n as H,t as U}from"./methods-part-DoTrY6b9.mjs";import{a as Pe,c as W,l as Fe,n as Ie,o as Le,r as Re}from"./on-DvrfHGje.mjs";import{i as ze,n as G,r as Be,t as Ve}from"./args-BvA37zBZ.mjs";import{n as K,t as q}from"./call-BWFI7-vU.mjs";import{i as He,n as Ue,r as We,t as Ge}from"./settled-Dkk5w1vE.mjs";import{n as Ke,r as qe,t as Je}from"./key-B3xgpu0M.mjs";import{a as Ye,c as Xe,d as Ze,i as Qe,o as $e,r as et,s as tt,u as nt}from"./rule-words-C4lXzgW2.mjs";import{a as rt,c as J,i as it,n as at,o as ot,r as st,s as ct}from"./judge-words-DpwxOfre.mjs";import{t as lt}from"./confine-BGGv2du0.mjs";import{n as ut,t as Y}from"./defaults-CrtGVdEC.mjs";import{n as X,r as dt,t as Z}from"./unit-CSaAB0su.mjs";import{a as ft,c as pt,d as mt,f as ht,h as gt,i as _t,l as vt,n as yt,o as bt,r as Q,s as xt,t as St,u as Ct}from"./unit-words-BGMVZ1MX.mjs";import{n as wt,r as Tt,t as Et}from"./values-Byqn5wAh.mjs";import{t as Dt}from"./schema-TthAXPVP.mjs";import{t as Ot}from"./version-B_ZLWzLW.mjs";const $=`$allModels`,kt=new Set([`createMany`,`updateMany`,`deleteMany`]);function planNode(e,t,n,r){let i=e[n[`~`].names.ts]??[],a=P(r?.select)?r.select:void 0,o=P(r?.include)?r.include:void 0,s=P(r?.omit)?r.omit:void 0,c=[],l=a??o,u=l;if(l!==void 0){let r=t.get(n);for(let i of Object.keys(l)){let a=r?.get(i),o=l[i];if(!a||Ee(a)||o!==!0&&!P(o))continue;let s=Te(a,n),d=o===!0?void 0:o,f=planNode(e,t,s,d);f!==void 0&&(c.push([i,f.node]),d?.recurse!==void 0&&f.node.relations.push([i,f.node]),f.args!==d&&(u={...u,[i]:f.args}))}}let d=new Map;for(let[e,t]of i.entries())d.set(t.name,e);let kept=e=>(a?a[e]===!0:!0)&&s?.[e]!==!0,f=[],p=!1;for(let[e,t]of d)p||=(a??s)?.[e]!==void 0,kept(e)&&f.push(t);if(f.length===0&&c.length===0&&!p)return;let m=new Set,h=new Set,close=e=>{if(!m.has(e)){m.add(e);for(let t of i[e].needs)typeof t==`number`?close(t):h.add(t)}};for(let e of f)close(e);let g=new Set;for(let e of h)kept(e)||g.add(e);let _=r;if(s!==void 0){let e={...s};for(let t of d.keys())s[t]!==void 0&&!Object.hasOwn(n[`~`].state.scalars,t)&&delete e[t];for(let t of h)s[t]===!0&&(e[t]=!1);_={..._,omit:e}}if(a!==void 0){let e={...u};for(let t of d.keys())delete e[t];for(let t of h)e[t]=!0;if(!Object.values(e).some(e=>e!==!1)){let[t]=V(n);t!==void 0&&(e[t]=!0,kept(t)||g.add(t))}_={..._,select:e}}else u!==l&&(_={..._,include:u});return{args:_,node:{fields:i,outputs:f,reads:[...h],strip:[...g],relations:c}}}function finishValue(e,t){return Array.isArray(e)?e.map(e=>finishRow(e,t)):finishRow(e,t)}function finishRow(t,n){if(!P(t))return t;let r={...t};for(let[e,t]of n.relations)r[e]!==void 0&&(r[e]=finishValue(r[e],t));for(let e of n.strip)delete r[e];let i=t;for(let e of n.reads){let n=t[e];typeof n!=`object`||!n||(i===t&&(i={...t}),i[e]=detached(n))}let a=new Map,o=e(e=>{if(a.has(e))return a.get(e);let t=n.fields[e],r={};for(let e of t.needs)typeof e==`number`?r[n.fields[e].name]=o(e):r[e]=i[e];let s=t.compute(r);return a.set(e,s),s},`computed`);for(let e of n.outputs){let t=n.fields[e].name,settle=e=>(Object.defineProperty(r,t,{value:e,writable:!0,enumerable:!0,configurable:!0}),e);Object.defineProperty(r,t,{get:()=>settle(o(e)),set:settle,enumerable:!0,configurable:!0})}return r}function detached(e){if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return e.map(detached);if(e instanceof Date)return new Date(e.getTime());if(ArrayBuffer.isView(e))return Object.getPrototypeOf(Uint8Array.prototype).slice.call(e);let t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)return e;let n={};for(let t in e)n[t]=detached(e[t]);return n}function fieldsPart(e){return{join({next:t,name:n,schema:r}){for(let t of Object.keys(e))t!==$&&!Object.hasOwn(r,t)&&F(`Extension "${n}" result names unknown model "${t}".`,n);let i={...t.fields?.fields};for(let t of Object.keys(r)){let a=r[t],o=[...i[t]??[]],s=new Set(V(a));for(let r of[$,t])for(let[i,{needs:c={},compute:l}]of Object.entries(e[r]??{})){let e=`Extension "${n}" result.${r}.${i}`;(i===`_count`||Object.hasOwn(a[`~`].state.relations,i))&&F(`${e} cannot be computed: "${i}" is a relation of model "${t}".`,n);let u=Object.keys(c).filter(e=>c[e]).map(r=>{for(let e=o.length-1;e>=0;e--)if(o[e].name===r)return e;return s.has(r)?r:F(`${e} needs "${r}", which is not a readable scalar or an earlier computed field of model "${t}".`,n)});o.push({name:i,compute:l,needs:u})}o.length>0&&(i[t]=o)}t.fields={fields:i,plan:(e,t,n,r)=>{if(!(De.has(n)||kt.has(n)&&(r.select!==void 0||r.omit!==void 0)))return;let a=planNode(i,e,t,r);if(a===void 0)return;let{node:o}=a;return{args:a.args,finish:e=>finishValue(e,o)}}}}}}function fields(e){return fieldsPart(e)}function parts(){return{extension:I,call:K,around:q,target:W,unit:Z,rule:J,defaults:Y,disclosure:X,args:G,methods:U,modelMethods:H,fields}}const getSchemas=e=>ke(e).proxy;export{R as AnyNull,a as CacheConfigurationError,u as CacheInvalidKeyError,t as CacheInvalidTTLError,l as CacheOperationNotCacheableError,d as CheckConstraintError,S as ClientInitializationError,le as ConnectionError,me as DbNull,L as Decimal,re as FeatureNotSupportedError,pe as ForbiddenError,m as ForeignKeyError,D as InvalidTransactionInputError,B as JsonNull,he as JsonNullSentinel,te as MigrationError,ie as NestedWriteAssertionError,ue as NestedWriteError,w as NotFoundError,c as NotNullConstraintError,we as PendingOperation,ae as PendingOperationError,oe as QueryEngineError,x as QueryError,ge as SchemaValidationError,N as Sql,E as TransactionError,p as UniqueConstraintError,de as UnsupportedOperationError,Ot as VIBORM_VERSION,C as ValidationError,o as ValueTooLongError,b as VibORMError,_ as VibORMErrorCode,Ve as accepts,Ue as again,et as arg,G as args,q as around,Be as bound,K as call,at as check,qe as codec,Et as computed,St as correlation,Oe as createClient,_e as createModelFieldRefs,Ke as database,Y as defaults,Ie as deletes,dt as disclosed,X as disclosure,yt as driver,A as empty,Qe as exists,I as extension,st as facts,Q as failure,fields,it as gate,Ne as getOperationPayloadSchema,xe as getRowKey,getSchemas,n as isCheckConstraintError,ce as isClientInitializationError,ve as isFieldRef,f as isForeignKeyError,z as isJsonNullSentinel,ee as isMigrationError,se as isNotFoundError,s as isNotNullConstraintError,Ce as isPendingOperation,ne as isPendingOperationError,g as isRetryableError,ye as isSchemaValidationError,M as isSql,i as isUniqueConstraintError,T as isUnsupportedOperationError,fe as isValidationError,r as isValueTooLongError,h as isVibORMError,k as join,wt as joined,rt as keep,Je as key,ot as lazy,U as methods,H as modelMethods,Re as models,_t as note,ft as notes,Ye as nothing,$e as now,ut as omitted,ze as oneOf,ct as only,bt as origin,xt as parameters,parts,tt as provided,O as raw,Pe as reads,je as renderOperationResultType,Me as renderSchemaType,Xe as row,J as rule,pt as run,Dt as s,Le as selecting,Ge as settled,j as sql,vt as statement,Ct as statements,Tt as stored,mt as table,W as target,ht as text,v as toPrismaErrorCode,Z as unit,nt as unless,Ae as validateOperationPayload,Se as validateSchema,be as validateSchemaOrThrow,We as via,He as watch,Ze as when,lt as within,gt as work,y as wrapError,Fe as writes};
2
2
  //# sourceMappingURL=index.mjs.map
@@ -1,4 +1,4 @@
1
- import { A as Extension, Co as VibORMError, O as EmptyFacts, S as AnyTarget, ko as DiagnosticDisclosure } from "./database-adapter-BGqvjeEy.mjs";
1
+ import { Bo as DiagnosticDisclosure, I as Extension, O as AnyTarget, P as EmptyFacts, Po as VibORMError } from "./database-adapter-D62c-uC6.mjs";
2
2
 
3
3
  //#region src/instrumentation/types.d.ts
4
4