viborm 1.14.2 → 1.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (483) hide show
  1. package/dist/adapter-namespace-DwFnfpED.mjs +2 -0
  2. package/dist/{adapter-namespace-DaRiTIIf.mjs.map → adapter-namespace-DwFnfpED.mjs.map} +1 -1
  3. package/dist/adapters.d.mts +26 -10
  4. package/dist/adapters.mjs +1 -1
  5. package/dist/args-7WgBFd_f.mjs +2 -0
  6. package/dist/{args-764KdWMr.mjs.map → args-7WgBFd_f.mjs.map} +1 -1
  7. package/dist/array-literal-BOzj0E2u.mjs +2 -0
  8. package/dist/{array-literal-DHinAnVs.mjs.map → array-literal-BOzj0E2u.mjs.map} +1 -1
  9. package/dist/base-17NSFtrA.mjs +2 -0
  10. package/dist/base-17NSFtrA.mjs.map +1 -0
  11. package/dist/batch-refs-Bd8HvwUc.mjs +2 -0
  12. package/dist/{batch-refs-C-gx7A4-.mjs.map → batch-refs-Bd8HvwUc.mjs.map} +1 -1
  13. package/dist/better-auth.d.mts +116 -0
  14. package/dist/better-auth.mjs +6 -0
  15. package/dist/better-auth.mjs.map +1 -0
  16. package/dist/bind-parameter-capacity-BAFQM9Jt.mjs +2 -0
  17. package/dist/{bind-parameter-capacity-BMD-bxMO.mjs.map → bind-parameter-capacity-BAFQM9Jt.mjs.map} +1 -1
  18. package/dist/bun-sql.d.mts +1 -1
  19. package/dist/bun-sql.mjs +1 -1
  20. package/dist/bun-sql.mjs.map +1 -1
  21. package/dist/bun-sqlite.d.mts +1 -1
  22. package/dist/bun-sqlite.mjs +1 -1
  23. package/dist/bun-sqlite.mjs.map +1 -1
  24. package/dist/cache/cloudflare-kv.d.mts +1 -1
  25. package/dist/cache/cloudflare-kv.mjs +1 -1
  26. package/dist/cache/cloudflare-kv.mjs.map +1 -1
  27. package/dist/cache/memory.d.mts +1 -1
  28. package/dist/cache/memory.mjs +1 -1
  29. package/dist/cache/memory.mjs.map +1 -1
  30. package/dist/cache.d.mts +2 -2
  31. package/dist/cache.mjs +1 -1
  32. package/dist/cache.mjs.map +1 -1
  33. package/dist/call-0bd_B9Vp.mjs +2 -0
  34. package/dist/{call-Cz8XUmrl.mjs.map → call-0bd_B9Vp.mjs.map} +1 -1
  35. package/dist/cli.mjs +6 -6
  36. package/dist/cli.mjs.map +1 -1
  37. package/dist/client-D7sWgUt2.mjs +2 -0
  38. package/dist/client-D7sWgUt2.mjs.map +1 -0
  39. package/dist/client-DEfFqv4S.mjs +9 -0
  40. package/dist/client-DEfFqv4S.mjs.map +1 -0
  41. package/dist/{client-CRxfhw2y.d.mts → client-Dlz3-2JC.d.mts} +3 -3
  42. package/dist/client.d.mts +3 -3
  43. package/dist/client.mjs +1 -1
  44. package/dist/client.mjs.map +1 -1
  45. package/dist/config.d.mts +2 -2
  46. package/dist/config.mjs +1 -1
  47. package/dist/confine-CyI9IwjC.mjs +2 -0
  48. package/dist/{confine-DqFBTUw6.mjs.map → confine-CyI9IwjC.mjs.map} +1 -1
  49. package/dist/coordination-BxMskOgi.mjs +2 -0
  50. package/dist/coordination-BxMskOgi.mjs.map +1 -0
  51. package/dist/d1.d.mts +2 -30
  52. package/dist/d1.mjs +1 -1
  53. package/dist/d1.mjs.map +1 -1
  54. package/dist/{database-adapter-BGqvjeEy.d.mts → database-adapter-BMjJiBFm.d.mts} +8476 -8386
  55. package/dist/datetime-physical-codec-DAF7WJpy.mjs +2 -0
  56. package/dist/datetime-physical-codec-DAF7WJpy.mjs.map +1 -0
  57. package/dist/defaults-DAPb-tJ4.mjs +2 -0
  58. package/dist/{defaults-DwOHWI_M.mjs.map → defaults-DAPb-tJ4.mjs.map} +1 -1
  59. package/dist/{document-BVTQ-cF-.d.mts → document-CHaVF7Vn.d.mts} +36 -2
  60. package/dist/{driver-BBEmaJZy.d.mts → driver-BvTixv-m.d.mts} +1 -1
  61. package/dist/driver-diagnostics-aQ54bArn.mjs +2 -0
  62. package/dist/{driver-diagnostics-DW9NdckJ.mjs.map → driver-diagnostics-aQ54bArn.mjs.map} +1 -1
  63. package/dist/driver-kiIQS_Fd.mjs +2 -0
  64. package/dist/driver-kiIQS_Fd.mjs.map +1 -0
  65. package/dist/driver-lShUkDmf.mjs +2 -0
  66. package/dist/driver-lShUkDmf.mjs.map +1 -0
  67. package/dist/driver.d.mts +1 -1
  68. package/dist/driver.mjs +1 -1
  69. package/dist/durable-object.d.mts +1 -1
  70. package/dist/durable-object.mjs +2 -2
  71. package/dist/durable-object.mjs.map +1 -1
  72. package/dist/error-mapping-B9rSvgG9.mjs +2 -0
  73. package/dist/error-mapping-B9rSvgG9.mjs.map +1 -0
  74. package/dist/every-JpbiHdMb.mjs +2 -0
  75. package/dist/{every-tOgQmaIE.mjs.map → every-JpbiHdMb.mjs.map} +1 -1
  76. package/dist/execution-context-couU2tgh.mjs +2 -0
  77. package/dist/execution-context-couU2tgh.mjs.map +1 -0
  78. package/dist/{exports-COCJ8f2f.d.mts → exports-DYnTfvQo.d.mts} +1 -1
  79. package/dist/extension-Dh1ddrlA.mjs +2 -0
  80. package/dist/{extension-CGepsF-p.mjs.map → extension-Dh1ddrlA.mjs.map} +1 -1
  81. package/dist/fs-estate-n-QpsFqb.mjs +2 -0
  82. package/dist/{fs-estate-D1Nsg9G1.mjs.map → fs-estate-n-QpsFqb.mjs.map} +1 -1
  83. package/dist/geo-area-codec-Bti2PA2i.mjs +2 -0
  84. package/dist/geo-area-codec-Bti2PA2i.mjs.map +1 -0
  85. package/dist/id-domain-Cg65TLZ-.mjs +2 -0
  86. package/dist/id-domain-Cg65TLZ-.mjs.map +1 -0
  87. package/dist/identifier-conversion-BTDxDwDB.mjs +2 -0
  88. package/dist/identifier-conversion-BTDxDwDB.mjs.map +1 -0
  89. package/dist/identifiers-BxOf57qy.mjs +2 -0
  90. package/dist/identifiers-BxOf57qy.mjs.map +1 -0
  91. package/dist/identity-CJlRQA-m.mjs +2 -0
  92. package/dist/identity-CJlRQA-m.mjs.map +1 -0
  93. package/dist/index.d.mts +3 -3
  94. package/dist/index.mjs +1 -1
  95. package/dist/index.mjs.map +1 -1
  96. package/dist/instrumentation.d.mts +1 -1
  97. package/dist/instrumentation.mjs +1 -1
  98. package/dist/instrumentation.mjs.map +1 -1
  99. package/dist/introspect-q3Rf_Xv8.mjs +2 -0
  100. package/dist/introspect-q3Rf_Xv8.mjs.map +1 -0
  101. package/dist/json-CsAdz9pg.mjs +2 -0
  102. package/dist/json-CsAdz9pg.mjs.map +1 -0
  103. package/dist/json-number-C09rsm1g.mjs +2 -0
  104. package/dist/{json-number-AI-SdUUn.mjs.map → json-number-C09rsm1g.mjs.map} +1 -1
  105. package/dist/json-parameter-D7hDrVKw.mjs +2 -0
  106. package/dist/{json-parameter-oQ8nGaKr.mjs.map → json-parameter-D7hDrVKw.mjs.map} +1 -1
  107. package/dist/judge-words-k5GCc4cV.mjs +2 -0
  108. package/dist/judge-words-k5GCc4cV.mjs.map +1 -0
  109. package/dist/key-BDH6oTyC.mjs +2 -0
  110. package/dist/key-BDH6oTyC.mjs.map +1 -0
  111. package/dist/keys-CIal55WQ.mjs +2 -0
  112. package/dist/{keys-BQxM4c_a.mjs.map → keys-CIal55WQ.mjs.map} +1 -1
  113. package/dist/keys-DZdKAd4n.mjs +2 -0
  114. package/dist/keys-DZdKAd4n.mjs.map +1 -0
  115. package/dist/libsql-DEZ0uhK2.mjs +3 -0
  116. package/dist/libsql-DEZ0uhK2.mjs.map +1 -0
  117. package/dist/libsql.d.mts +2 -20
  118. package/dist/libsql.mjs +1 -1
  119. package/dist/libsql.mjs.map +1 -1
  120. package/dist/light-D2wNSbzY.mjs +2 -0
  121. package/dist/{light-BkJe3-yW.mjs.map → light-D2wNSbzY.mjs.map} +1 -1
  122. package/dist/memory-BaGWNdvk.mjs +2 -0
  123. package/dist/{memory-G4cSuc6A.mjs.map → memory-BaGWNdvk.mjs.map} +1 -1
  124. package/dist/methods-part-BaNx3o7b.mjs +2 -0
  125. package/dist/methods-part-BaNx3o7b.mjs.map +1 -0
  126. package/dist/migrations/mysql.d.mts +5 -5
  127. package/dist/migrations/mysql.mjs +1 -1
  128. package/dist/migrations/postgres.d.mts +5 -5
  129. package/dist/migrations/postgres.mjs +1 -1
  130. package/dist/migrations/snowflake.d.mts +5 -5
  131. package/dist/migrations/snowflake.mjs +1 -1
  132. package/dist/migrations/sqlite.d.mts +5 -5
  133. package/dist/migrations/sqlite.mjs +1 -1
  134. package/dist/migrations/storage/durable-object.d.mts +1 -1
  135. package/dist/migrations/storage/durable-object.mjs +1 -1
  136. package/dist/migrations/storage/durable-object.mjs.map +1 -1
  137. package/dist/migrations/storage/fs.d.mts +1 -1
  138. package/dist/migrations/storage/fs.mjs +1 -1
  139. package/dist/migrations/storage/r2.d.mts +1 -1
  140. package/dist/migrations/storage/r2.mjs +1 -1
  141. package/dist/migrations/storage/r2.mjs.map +1 -1
  142. package/dist/migrations/surrealdb.d.mts +5 -5
  143. package/dist/migrations/surrealdb.mjs +1 -1
  144. package/dist/migrations/tenant.d.mts +3 -3
  145. package/dist/migrations/tenant.mjs +1 -1
  146. package/dist/migrations/tenant.mjs.map +1 -1
  147. package/dist/migrations-DIUltjr3.mjs +2 -0
  148. package/dist/{migrations-BMiRjR-N.mjs.map → migrations-DIUltjr3.mjs.map} +1 -1
  149. package/dist/migrations.d.mts +5 -5
  150. package/dist/migrations.mjs +1 -1
  151. package/dist/model-Dtd37Sky.mjs +2 -0
  152. package/dist/model-Dtd37Sky.mjs.map +1 -0
  153. package/dist/mysql-BFPF8xyv.mjs +9 -0
  154. package/dist/mysql-BFPF8xyv.mjs.map +1 -0
  155. package/dist/mysql-adapter-BFWYPoM0.mjs +2 -0
  156. package/dist/mysql-adapter-BFWYPoM0.mjs.map +1 -0
  157. package/dist/mysql2.d.mts +2 -27
  158. package/dist/mysql2.mjs +1 -1
  159. package/dist/mysql2.mjs.map +1 -1
  160. package/dist/named-statements-CkOOD__I.mjs +2 -0
  161. package/dist/named-statements-CkOOD__I.mjs.map +1 -0
  162. package/dist/named-statements-NF7Iycjk.d.mts +13 -0
  163. package/dist/native-types-1ewJXVks.mjs +2 -0
  164. package/dist/native-types-1ewJXVks.mjs.map +1 -0
  165. package/dist/neon-http.d.mts +1 -1
  166. package/dist/neon-http.mjs +1 -1
  167. package/dist/neon-http.mjs.map +1 -1
  168. package/dist/normalized-result-D7nVkF36.mjs +2 -0
  169. package/dist/normalized-result-D7nVkF36.mjs.map +1 -0
  170. package/dist/{object-store-B_YMoW8u.d.mts → object-store-C4qmW7xf.d.mts} +4 -4
  171. package/dist/object-store-Chq1PMYz.mjs +2 -0
  172. package/dist/object-store-Chq1PMYz.mjs.map +1 -0
  173. package/dist/on-ZkOVmE4-.mjs +2 -0
  174. package/dist/{on-ylYaKuRu.mjs.map → on-ZkOVmE4-.mjs.map} +1 -1
  175. package/dist/on.d.mts +1 -1
  176. package/dist/on.mjs +1 -1
  177. package/dist/on.mjs.map +1 -1
  178. package/dist/ordering/keys.mjs +1 -1
  179. package/dist/ordering.d.mts +9 -3
  180. package/dist/ordering.mjs +10 -10
  181. package/dist/ordering.mjs.map +1 -1
  182. package/dist/pending-operation-D4gUKMxD.mjs +2 -0
  183. package/dist/pending-operation-D4gUKMxD.mjs.map +1 -0
  184. package/dist/permissions.d.mts +1 -1
  185. package/dist/permissions.mjs +1 -1
  186. package/dist/permissions.mjs.map +1 -1
  187. package/dist/pg.d.mts +16 -99
  188. package/dist/pg.mjs +1 -1
  189. package/dist/pg.mjs.map +1 -1
  190. package/dist/pglite.d.mts +3 -1
  191. package/dist/pglite.mjs +1 -1
  192. package/dist/pglite.mjs.map +1 -1
  193. package/dist/physical-DO4PEYcc.mjs +2 -0
  194. package/dist/physical-DO4PEYcc.mjs.map +1 -0
  195. package/dist/pinned-session-Y7-2pRBJ.mjs +2 -0
  196. package/dist/pinned-session-Y7-2pRBJ.mjs.map +1 -0
  197. package/dist/planetscale.d.mts +1 -1
  198. package/dist/planetscale.mjs +1 -1
  199. package/dist/planetscale.mjs.map +1 -1
  200. package/dist/{planner-DHjdvjwk.d.mts → planner-C-zjj19U.d.mts} +123 -1
  201. package/dist/postgres-DQQE2ys_.mjs +34 -0
  202. package/dist/postgres-DQQE2ys_.mjs.map +1 -0
  203. package/dist/postgres-adapter-BpLizOaK.mjs +2 -0
  204. package/dist/{postgres-adapter-axapXX8d.mjs.map → postgres-adapter-BpLizOaK.mjs.map} +1 -1
  205. package/dist/postgres-adapter-psTVfuw7.mjs +2 -0
  206. package/dist/postgres-adapter-psTVfuw7.mjs.map +1 -0
  207. package/dist/postgres-result-133boRW-.mjs +2 -0
  208. package/dist/postgres-result-133boRW-.mjs.map +1 -0
  209. package/dist/postgres.d.mts +27 -59
  210. package/dist/postgres.mjs +1 -1
  211. package/dist/postgres.mjs.map +1 -1
  212. package/dist/provider-limits-Bcsz0EJv.mjs +2 -0
  213. package/dist/provider-limits-Bcsz0EJv.mjs.map +1 -0
  214. package/dist/provider-parameter-snapshot-cyTUDutH.mjs +2 -0
  215. package/dist/provider-parameter-snapshot-cyTUDutH.mjs.map +1 -0
  216. package/dist/quantized-BKBs0joq.mjs +2 -0
  217. package/dist/quantized-BKBs0joq.mjs.map +1 -0
  218. package/dist/query-BTb6iakn.mjs +2 -0
  219. package/dist/query-BTb6iakn.mjs.map +1 -0
  220. package/dist/query-backend-TisPjCPF.mjs +2 -0
  221. package/dist/query-backend-TisPjCPF.mjs.map +1 -0
  222. package/dist/query-inspection-DwYBKSDG.mjs +2 -0
  223. package/dist/query-inspection-DwYBKSDG.mjs.map +1 -0
  224. package/dist/raw-DqEb71JZ.mjs +2 -0
  225. package/dist/raw-DqEb71JZ.mjs.map +1 -0
  226. package/dist/relation-bound-CSNKLyDy.mjs +2 -0
  227. package/dist/{relation-bound-ku_cMdye.mjs.map → relation-bound-CSNKLyDy.mjs.map} +1 -1
  228. package/dist/result-parsing-BbffueEX.mjs +2 -0
  229. package/dist/{result-parsing-B0Y4KGDT.mjs.map → result-parsing-BbffueEX.mjs.map} +1 -1
  230. package/dist/routed-operations-CcKOdn51.mjs +2 -0
  231. package/dist/{routed-operations-wytpbYKv.mjs.map → routed-operations-CcKOdn51.mjs.map} +1 -1
  232. package/dist/rows-of-Bgl9GVtK.mjs +2 -0
  233. package/dist/rows-of-Bgl9GVtK.mjs.map +1 -0
  234. package/dist/rule-words-DMbQuvD2.mjs +2 -0
  235. package/dist/{rule-words-ZIGm7cDm.mjs.map → rule-words-DMbQuvD2.mjs.map} +1 -1
  236. package/dist/scalar-Dm9brvAU.mjs +4 -0
  237. package/dist/scalar-Dm9brvAU.mjs.map +1 -0
  238. package/dist/schema/introspect.d.mts +2 -2
  239. package/dist/schema/introspect.mjs +1 -1
  240. package/dist/schema/json.d.mts +6 -4
  241. package/dist/schema/json.mjs +1 -1
  242. package/dist/schema-DDkAUfOb.mjs +2 -0
  243. package/dist/schema-DDkAUfOb.mjs.map +1 -0
  244. package/dist/schema-DqR_Kcje.mjs +2 -0
  245. package/dist/schema-DqR_Kcje.mjs.map +1 -0
  246. package/dist/schema-introspection-Bbo4DN_d.mjs +4 -0
  247. package/dist/schema-introspection-Bbo4DN_d.mjs.map +1 -0
  248. package/dist/schema.d.mts +2 -2
  249. package/dist/schema.mjs +1 -1
  250. package/dist/select-assembly-CEpNu-Gw.mjs +2 -0
  251. package/dist/select-assembly-CEpNu-Gw.mjs.map +1 -0
  252. package/dist/serializer-ettLu5xG.mjs +33 -0
  253. package/dist/serializer-ettLu5xG.mjs.map +1 -0
  254. package/dist/settle-Pui-1tfJ.mjs +2 -0
  255. package/dist/{settle-1cy5x_52.mjs.map → settle-Pui-1tfJ.mjs.map} +1 -1
  256. package/dist/settled-DYYPcaBX.mjs +2 -0
  257. package/dist/{settled-BjyuA76m.mjs.map → settled-DYYPcaBX.mjs.map} +1 -1
  258. package/dist/snowflake-BfF8xwfP.mjs +2 -0
  259. package/dist/{snowflake-UOCC820W.mjs.map → snowflake-BfF8xwfP.mjs.map} +1 -1
  260. package/dist/snowflake.d.mts +3 -3
  261. package/dist/snowflake.mjs +2 -2
  262. package/dist/snowflake.mjs.map +1 -1
  263. package/dist/soft-delete.d.mts +9 -3
  264. package/dist/soft-delete.mjs +1 -1
  265. package/dist/soft-delete.mjs.map +1 -1
  266. package/dist/{spans-XDUFeTzC.mjs → spans-DwDXMvyd.mjs} +1 -1
  267. package/dist/{spans-XDUFeTzC.mjs.map → spans-DwDXMvyd.mjs.map} +1 -1
  268. package/dist/sql-Bu63iAfT.mjs +2 -0
  269. package/dist/sql-Bu63iAfT.mjs.map +1 -0
  270. package/dist/{sql-BVZ8QefY.d.mts → sql-C4_sFNDm.d.mts} +18 -5
  271. package/dist/sql-statement-tokens-Z5Ta4iDB.mjs +3 -0
  272. package/dist/{sql-statement-tokens-DbeMwHra.mjs.map → sql-statement-tokens-Z5Ta4iDB.mjs.map} +1 -1
  273. package/dist/sql-tegqTqGq.mjs +2 -0
  274. package/dist/sql-tegqTqGq.mjs.map +1 -0
  275. package/dist/sql.d.mts +1 -1
  276. package/dist/sql.mjs +1 -1
  277. package/dist/sqlite-adapter-Cb-SJw2f.mjs +2 -0
  278. package/dist/sqlite-adapter-Cb-SJw2f.mjs.map +1 -0
  279. package/dist/sqlite-statement-classifier-JBHiQO6Q.mjs +2 -0
  280. package/dist/{sqlite-statement-classifier-BAHl-WXS.mjs.map → sqlite-statement-classifier-JBHiQO6Q.mjs.map} +1 -1
  281. package/dist/sqlite-utils-Bfmtkt1b.mjs +2 -0
  282. package/dist/sqlite-utils-Bfmtkt1b.mjs.map +1 -0
  283. package/dist/sqlite3.d.mts +2 -46
  284. package/dist/sqlite3.mjs +1 -1
  285. package/dist/sqlite3.mjs.map +1 -1
  286. package/dist/standard-sql-Bl2OHGfi.mjs +6 -0
  287. package/dist/standard-sql-Bl2OHGfi.mjs.map +1 -0
  288. package/dist/suppressed-failure-CFUDJrUw.mjs +2 -0
  289. package/dist/{suppressed-failure-CQkQsMVS.mjs.map → suppressed-failure-CFUDJrUw.mjs.map} +1 -1
  290. package/dist/surrealdb.d.mts +2 -2
  291. package/dist/surrealdb.mjs +1 -1
  292. package/dist/surrealdb.mjs.map +1 -1
  293. package/dist/surrealql-DY74AUeD.mjs +2 -0
  294. package/dist/surrealql-DY74AUeD.mjs.map +1 -0
  295. package/dist/time-step-DJaIhpAz.mjs +2 -0
  296. package/dist/time-step-DJaIhpAz.mjs.map +1 -0
  297. package/dist/transaction-Bv5nyp-U.mjs +2 -0
  298. package/dist/{transaction-BNomMtme.mjs.map → transaction-Bv5nyp-U.mjs.map} +1 -1
  299. package/dist/transaction-operation-CaWzo7gE.mjs +2 -0
  300. package/dist/{transaction-operation-CVVJxQ19.mjs.map → transaction-operation-CaWzo7gE.mjs.map} +1 -1
  301. package/dist/types-Dy33vBdd.mjs +2 -0
  302. package/dist/{types-DtDnXhwa.mjs.map → types-Dy33vBdd.mjs.map} +1 -1
  303. package/dist/unit-DUPX5Sdd.mjs +2 -0
  304. package/dist/{unit-BhHbZyuJ.mjs.map → unit-DUPX5Sdd.mjs.map} +1 -1
  305. package/dist/unit-words-BXpLpyr2.mjs +2 -0
  306. package/dist/{unit-words-CT0yeqfZ.mjs.map → unit-words-BXpLpyr2.mjs.map} +1 -1
  307. package/dist/utils-BHkJsduV.mjs +26 -0
  308. package/dist/{utils-CpAojrCj.mjs.map → utils-BHkJsduV.mjs.map} +1 -1
  309. package/dist/v1-parse-shared-cJ-uD14P.mjs +2 -0
  310. package/dist/v1-parse-shared-cJ-uD14P.mjs.map +1 -0
  311. package/dist/validation-ATmgN5RE.mjs +2 -0
  312. package/dist/validation-ATmgN5RE.mjs.map +1 -0
  313. package/dist/validation-BHjx13zG.mjs +2 -0
  314. package/dist/validation-BHjx13zG.mjs.map +1 -0
  315. package/dist/validation.d.mts +1 -1
  316. package/dist/validation.mjs +1 -1
  317. package/dist/validator-DMzH5Tz0.mjs +2 -0
  318. package/dist/validator-DMzH5Tz0.mjs.map +1 -0
  319. package/dist/value-guards-CBVIJXlI.mjs +2 -0
  320. package/dist/{value-guards-CBuxSC66.mjs.map → value-guards-CBVIJXlI.mjs.map} +1 -1
  321. package/dist/values-Ch2cTlss.mjs +2 -0
  322. package/dist/{values-B4aj1i1f.mjs.map → values-Ch2cTlss.mjs.map} +1 -1
  323. package/dist/version-0BDwfy7C.mjs +2 -0
  324. package/dist/{version-CXGIA82S.mjs.map → version-0BDwfy7C.mjs.map} +1 -1
  325. package/dist/view-CHgjF2BO.mjs +2 -0
  326. package/dist/view-CHgjF2BO.mjs.map +1 -0
  327. package/dist/write-sinks-Bei5vFHP.mjs +2 -0
  328. package/dist/{write-sinks-3IKCDF-S.mjs.map → write-sinks-Bei5vFHP.mjs.map} +1 -1
  329. package/package.json +50 -37
  330. package/dist/adapter-internals-DOqI8IlQ.mjs +0 -2
  331. package/dist/adapter-internals-DOqI8IlQ.mjs.map +0 -1
  332. package/dist/adapter-namespace-DaRiTIIf.mjs +0 -2
  333. package/dist/adapter-result-parser-3WP82Cm-.mjs +0 -2
  334. package/dist/adapter-result-parser-3WP82Cm-.mjs.map +0 -1
  335. package/dist/args-764KdWMr.mjs +0 -2
  336. package/dist/array-literal-DHinAnVs.mjs +0 -2
  337. package/dist/base-z-cH5ZBI.mjs +0 -2
  338. package/dist/base-z-cH5ZBI.mjs.map +0 -1
  339. package/dist/batch-refs-C-gx7A4-.mjs +0 -2
  340. package/dist/bind-parameter-capacity-BMD-bxMO.mjs +0 -2
  341. package/dist/call-Cz8XUmrl.mjs +0 -2
  342. package/dist/canonical-json-Bl-fKFF_.mjs +0 -2
  343. package/dist/canonical-json-Bl-fKFF_.mjs.map +0 -1
  344. package/dist/chunk-BuuaeEvq.mjs +0 -1
  345. package/dist/client-DRpX3-vw.mjs +0 -2
  346. package/dist/client-DRpX3-vw.mjs.map +0 -1
  347. package/dist/client-y7TV0PRZ.mjs +0 -9
  348. package/dist/client-y7TV0PRZ.mjs.map +0 -1
  349. package/dist/confine-DqFBTUw6.mjs +0 -2
  350. package/dist/coordination-6qZHx_kl.mjs +0 -2
  351. package/dist/coordination-6qZHx_kl.mjs.map +0 -1
  352. package/dist/current-DBTlPsQg.mjs +0 -2
  353. package/dist/current-DBTlPsQg.mjs.map +0 -1
  354. package/dist/datetime-physical-codec-Dj-APo9f.mjs +0 -2
  355. package/dist/datetime-physical-codec-Dj-APo9f.mjs.map +0 -1
  356. package/dist/defaults-DwOHWI_M.mjs +0 -2
  357. package/dist/driver-BGVcgnIX.mjs +0 -2
  358. package/dist/driver-BGVcgnIX.mjs.map +0 -1
  359. package/dist/driver-BIXhOH2_.mjs +0 -2
  360. package/dist/driver-BIXhOH2_.mjs.map +0 -1
  361. package/dist/driver-diagnostics-DW9NdckJ.mjs +0 -2
  362. package/dist/error-mapping-B1-IWkCQ.mjs +0 -2
  363. package/dist/error-mapping-B1-IWkCQ.mjs.map +0 -1
  364. package/dist/every-tOgQmaIE.mjs +0 -2
  365. package/dist/execution-context-BXpcbyPe.mjs +0 -2
  366. package/dist/execution-context-BXpcbyPe.mjs.map +0 -1
  367. package/dist/extension-CGepsF-p.mjs +0 -2
  368. package/dist/fs-estate-D1Nsg9G1.mjs +0 -2
  369. package/dist/geo-area-codec-mHrM3b9A.mjs +0 -2
  370. package/dist/geo-area-codec-mHrM3b9A.mjs.map +0 -1
  371. package/dist/hydration-A3zffFWP.mjs +0 -2
  372. package/dist/hydration-A3zffFWP.mjs.map +0 -1
  373. package/dist/identifier-conversion-DHYPTgzr.mjs +0 -2
  374. package/dist/identifier-conversion-DHYPTgzr.mjs.map +0 -1
  375. package/dist/identifiers-s00pGES8.mjs +0 -2
  376. package/dist/identifiers-s00pGES8.mjs.map +0 -1
  377. package/dist/identity-CtW15WlB.mjs +0 -2
  378. package/dist/identity-CtW15WlB.mjs.map +0 -1
  379. package/dist/introspect-Bm6xnXcG.mjs +0 -2
  380. package/dist/introspect-Bm6xnXcG.mjs.map +0 -1
  381. package/dist/json-DgMc8-GU.mjs +0 -2
  382. package/dist/json-DgMc8-GU.mjs.map +0 -1
  383. package/dist/json-number-AI-SdUUn.mjs +0 -2
  384. package/dist/json-parameter-oQ8nGaKr.mjs +0 -2
  385. package/dist/judge-words-CzUyXtJ6.mjs +0 -2
  386. package/dist/judge-words-CzUyXtJ6.mjs.map +0 -1
  387. package/dist/key-hxFFCKed.mjs +0 -2
  388. package/dist/key-hxFFCKed.mjs.map +0 -1
  389. package/dist/keys-BQxM4c_a.mjs +0 -2
  390. package/dist/libsql-DuGR904j.mjs +0 -3
  391. package/dist/libsql-DuGR904j.mjs.map +0 -1
  392. package/dist/light-BkJe3-yW.mjs +0 -2
  393. package/dist/memory-G4cSuc6A.mjs +0 -2
  394. package/dist/methods-part-ZY0f2AV_.mjs +0 -2
  395. package/dist/methods-part-ZY0f2AV_.mjs.map +0 -1
  396. package/dist/migrations-BMiRjR-N.mjs +0 -2
  397. package/dist/mysql-BNXWfTOo.mjs +0 -100
  398. package/dist/mysql-BNXWfTOo.mjs.map +0 -1
  399. package/dist/mysql-adapter-C69j1sKh.mjs +0 -2
  400. package/dist/mysql-adapter-C69j1sKh.mjs.map +0 -1
  401. package/dist/native-types-DgjMUikz.mjs +0 -2
  402. package/dist/native-types-DgjMUikz.mjs.map +0 -1
  403. package/dist/normalized-result-B8pifWS0.mjs +0 -2
  404. package/dist/normalized-result-B8pifWS0.mjs.map +0 -1
  405. package/dist/object-store-DS0F0yZX.mjs +0 -2
  406. package/dist/object-store-DS0F0yZX.mjs.map +0 -1
  407. package/dist/on-ylYaKuRu.mjs +0 -2
  408. package/dist/pending-operation-C_eOFOBE.mjs +0 -2
  409. package/dist/pending-operation-C_eOFOBE.mjs.map +0 -1
  410. package/dist/physical-CeE2nYmI.mjs +0 -2
  411. package/dist/physical-CeE2nYmI.mjs.map +0 -1
  412. package/dist/pinned-session-DCoAZDOz.mjs +0 -2
  413. package/dist/pinned-session-DCoAZDOz.mjs.map +0 -1
  414. package/dist/postgres-CDdh5dSP.mjs +0 -437
  415. package/dist/postgres-CDdh5dSP.mjs.map +0 -1
  416. package/dist/postgres-adapter-Dlr3ZWd7.mjs +0 -2
  417. package/dist/postgres-adapter-Dlr3ZWd7.mjs.map +0 -1
  418. package/dist/postgres-adapter-axapXX8d.mjs +0 -2
  419. package/dist/postgres-result-DF6DmW3r.mjs +0 -2
  420. package/dist/postgres-result-DF6DmW3r.mjs.map +0 -1
  421. package/dist/provider-limits-Ccsb8PTb.mjs +0 -2
  422. package/dist/provider-limits-Ccsb8PTb.mjs.map +0 -1
  423. package/dist/provider-parameter-snapshot-BikrgKqI.mjs +0 -2
  424. package/dist/provider-parameter-snapshot-BikrgKqI.mjs.map +0 -1
  425. package/dist/query-BZVHfA0s.mjs +0 -2
  426. package/dist/query-BZVHfA0s.mjs.map +0 -1
  427. package/dist/query-inspection-BoG-yAln.mjs +0 -2
  428. package/dist/query-inspection-BoG-yAln.mjs.map +0 -1
  429. package/dist/raw-Dyq6Y6UX.mjs +0 -2
  430. package/dist/raw-Dyq6Y6UX.mjs.map +0 -1
  431. package/dist/relation-bound-ku_cMdye.mjs +0 -2
  432. package/dist/result-parsing-B0Y4KGDT.mjs +0 -2
  433. package/dist/routed-operations-wytpbYKv.mjs +0 -2
  434. package/dist/rule-words-ZIGm7cDm.mjs +0 -2
  435. package/dist/scalar-BHCh7aUz.mjs +0 -4
  436. package/dist/scalar-BHCh7aUz.mjs.map +0 -1
  437. package/dist/schema-BYA-_bpk.mjs +0 -2
  438. package/dist/schema-BYA-_bpk.mjs.map +0 -1
  439. package/dist/schema-CFIaebgi.mjs +0 -2
  440. package/dist/schema-CFIaebgi.mjs.map +0 -1
  441. package/dist/schema-introspection-D0f8cti4.mjs +0 -6
  442. package/dist/schema-introspection-D0f8cti4.mjs.map +0 -1
  443. package/dist/select-assembly-DVI7d3tf.mjs +0 -2
  444. package/dist/select-assembly-DVI7d3tf.mjs.map +0 -1
  445. package/dist/serializer-rBq3v1xr.mjs +0 -51
  446. package/dist/serializer-rBq3v1xr.mjs.map +0 -1
  447. package/dist/settle-1cy5x_52.mjs +0 -2
  448. package/dist/settled-BjyuA76m.mjs +0 -2
  449. package/dist/snowflake-UOCC820W.mjs +0 -2
  450. package/dist/sql-3o4DOKm9.mjs +0 -2
  451. package/dist/sql-3o4DOKm9.mjs.map +0 -1
  452. package/dist/sql-Dl6nykFV.mjs +0 -2
  453. package/dist/sql-Dl6nykFV.mjs.map +0 -1
  454. package/dist/sql-statement-tokens-DbeMwHra.mjs +0 -3
  455. package/dist/sqlite-adapter-Ad0d-m2t.mjs +0 -2
  456. package/dist/sqlite-adapter-Ad0d-m2t.mjs.map +0 -1
  457. package/dist/sqlite-statement-classifier-BAHl-WXS.mjs +0 -2
  458. package/dist/sqlite-utils-BRvbmlQ1.mjs +0 -2
  459. package/dist/sqlite-utils-BRvbmlQ1.mjs.map +0 -1
  460. package/dist/standard-sql-qLcQyCtK.mjs +0 -6
  461. package/dist/standard-sql-qLcQyCtK.mjs.map +0 -1
  462. package/dist/suppressed-failure-CQkQsMVS.mjs +0 -2
  463. package/dist/surrealql-C1dp1sWw.mjs +0 -2
  464. package/dist/surrealql-C1dp1sWw.mjs.map +0 -1
  465. package/dist/to-many-BybuKQM1.mjs +0 -2
  466. package/dist/to-many-BybuKQM1.mjs.map +0 -1
  467. package/dist/transaction-BNomMtme.mjs +0 -2
  468. package/dist/transaction-operation-CVVJxQ19.mjs +0 -2
  469. package/dist/types-DtDnXhwa.mjs +0 -2
  470. package/dist/unit-BhHbZyuJ.mjs +0 -2
  471. package/dist/unit-words-CT0yeqfZ.mjs +0 -2
  472. package/dist/utils-CpAojrCj.mjs +0 -26
  473. package/dist/validation--qS7OPmg.mjs +0 -2
  474. package/dist/validation--qS7OPmg.mjs.map +0 -1
  475. package/dist/validation-CYaJ8ndO.mjs +0 -2
  476. package/dist/validation-CYaJ8ndO.mjs.map +0 -1
  477. package/dist/validator-CZLW7aR3.mjs +0 -2
  478. package/dist/validator-CZLW7aR3.mjs.map +0 -1
  479. package/dist/value-guards-CBuxSC66.mjs +0 -2
  480. package/dist/values-B4aj1i1f.mjs +0 -2
  481. package/dist/version-CXGIA82S.mjs +0 -2
  482. package/dist/write-sinks-3IKCDF-S.mjs +0 -2
  483. /package/dist/{contract-CrIB-3ZJ.d.mts → contract-CxJn0_cV.d.mts} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"file":"error-mapping-B1-IWkCQ.mjs","names":["#values","#lazyCorrelationId","readString","readProperty","trusted","providerSettledBeforeCallback","settledOutcome"],"sources":["../src/drivers/execution-context.ts","../src/errors/cache.ts","../src/errors/constraints.ts","../src/errors/record-series-progress.ts","../src/query-engine/types.ts","../src/errors/logged-errors.ts","../src/drivers/shared/transactions.ts","../src/drivers/driver-error-context.ts","../src/drivers/error-mapping.ts"],"sourcesContent":["import type { ResolvedExtensionChain } from \"@extensions/chain\";\nimport type { QueryExecutionContext } from \"./types\";\n\ninterface TrustedExecutionContext {\n readonly callsite?: string;\n readonly correlationId?: string;\n readonly correlationIdGetter?: () => string;\n readonly extensionChain?: ResolvedExtensionChain;\n readonly model?: string;\n readonly operation?: string;\n readonly transactionPhases?: TransactionPhaseNotifications;\n /**\n * A failure of this execution is recovered by its owner, so it is not the\n * operation's error: the statement it ran logs and traces no failure.\n */\n readonly recoverable?: true;\n}\n\n/** Private exact transaction lifecycle facts attached only to trusted contexts. */\nexport interface TransactionPhaseNotifications {\n readonly readyToCommit: () => void;\n readonly committed: () => void;\n}\n\n/**\n * A context this owner created. The private field is the trust mark: nothing\n * outside this class can set or read it, so a caller cannot forge one, and\n * checking it is cheaper than the per-query WeakMap entry it replaces.\n */\nclass TrustedSnapshot {\n readonly #values: TrustedExecutionContext;\n readonly model?: string;\n readonly operation: string | undefined;\n // Declared only: a field first made as a value, then made again as an accessor, costs each context a shape of its own.\n declare readonly correlationId?: string;\n /**\n * The id made where it is first read. One accessor for every context: a\n * getter of its own would also give each context a shape of its own, four\n * times slower to make and to freeze.\n */\n static readonly #lazyCorrelationId: PropertyDescriptor = {\n configurable: false,\n enumerable: true,\n get(this: object) {\n return TrustedSnapshot.values(this)?.correlationIdGetter?.();\n },\n };\n constructor(values: TrustedExecutionContext) {\n this.#values = values;\n if (values.model) this.model = values.model;\n this.operation = values.operation;\n if (values.correlationIdGetter)\n Object.defineProperty(\n this,\n \"correlationId\",\n TrustedSnapshot.#lazyCorrelationId\n );\n // Always a property of its own, as a field is: set where there is no id too.\n else this.correlationId = values.correlationId || undefined;\n Object.freeze(this);\n }\n static values(context: object): TrustedExecutionContext | undefined {\n return #values in context\n ? (context as TrustedSnapshot).#values\n : undefined;\n }\n}\nconst trusted = (context: object) => TrustedSnapshot.values(context);\n\nexport function createExecutionContext(\n values: QueryExecutionContext,\n correlationIdFactory?: () => string,\n extensionChain?: ResolvedExtensionChain,\n callsite?: string\n): QueryExecutionContext {\n if (!correlationIdFactory) {\n return snapshotExecutionContext(\n values,\n undefined,\n undefined,\n extensionChain\n );\n }\n\n let correlationId: string | undefined;\n const correlationIdGetter = () => {\n correlationId ??= correlationIdFactory();\n return correlationId;\n };\n return createTrustedExecutionContext({\n callsite,\n correlationIdGetter,\n extensionChain,\n model: readString(values, \"model\"),\n operation: readString(values, \"operation\"),\n });\n}\n\nexport function snapshotExecutionContext(\n context: QueryExecutionContext | undefined,\n boundContext?: QueryExecutionContext,\n fallbackOperation?: string,\n extensionChainOverride?: ResolvedExtensionChain\n): QueryExecutionContext {\n const trustedContext = context ? trusted(context) : undefined;\n const contextValues =\n trustedContext ?? snapshotExternalExecutionContext(context);\n const trustedBoundContext = boundContext ? trusted(boundContext) : undefined;\n const boundValues =\n context === boundContext\n ? contextValues\n : (trustedBoundContext ?? snapshotExternalExecutionContext(boundContext));\n const model = contextValues.model ?? boundValues.model;\n const operation =\n contextValues.operation ?? boundValues.operation ?? fallbackOperation;\n const correlationIdGetter =\n contextValues.correlationIdGetter ??\n (contextValues.correlationId === undefined\n ? boundValues.correlationIdGetter\n : undefined);\n const correlationId = correlationIdGetter\n ? undefined\n : (contextValues.correlationId ?? boundValues.correlationId);\n const extensionChain =\n contextValues.extensionChain ??\n boundValues.extensionChain ??\n extensionChainOverride;\n const callsite = contextValues.callsite ?? boundValues.callsite;\n const transactionPhases =\n contextValues.transactionPhases ?? boundValues.transactionPhases;\n const recoverable = contextValues.recoverable ?? boundValues.recoverable;\n\n if (\n context &&\n trustedContext &&\n representsExecutionContext(\n trustedContext,\n model,\n operation,\n correlationId,\n correlationIdGetter,\n extensionChain,\n transactionPhases,\n callsite,\n recoverable\n )\n ) {\n return context;\n }\n if (\n boundContext &&\n trustedBoundContext &&\n representsExecutionContext(\n trustedBoundContext,\n model,\n operation,\n correlationId,\n correlationIdGetter,\n extensionChain,\n transactionPhases,\n callsite,\n recoverable\n )\n ) {\n return boundContext;\n }\n\n return createTrustedExecutionContext({\n callsite,\n correlationId,\n correlationIdGetter,\n extensionChain,\n model,\n operation,\n transactionPhases,\n ...(recoverable && { recoverable }),\n });\n}\n\n/**\n * This context, for an execution whose failure its owner recovers: a\n * `findUnique` batch's shared read, whose callers each run alone when it\n * fails. Its statement then logs and traces no failure of its own.\n */\nexport function deriveRecoverableExecutionContext(\n context: QueryExecutionContext\n): QueryExecutionContext {\n const values = trusted(context) ?? snapshotExternalExecutionContext(context);\n return createTrustedExecutionContext({ ...values, recoverable: true });\n}\n\n/** Whether this trusted context's failure is recovered by its owner. */\nexport function isRecoverableExecution(\n context: QueryExecutionContext | undefined\n): boolean {\n return context !== undefined && trusted(context)?.recoverable === true;\n}\n\n/**\n * Re-attribute a trusted context to the model one statement addresses, keeping\n * the correlation id and extension provenance of the operation\n * it belongs to. Only the snapshot owner can do this without losing the private\n * values, which is why the query engine asks for it rather than rebuilding one.\n */\nexport function deriveStatementExecutionContext(\n context: QueryExecutionContext,\n model: string\n): QueryExecutionContext {\n const values = trusted(context) ?? snapshotExternalExecutionContext(context);\n return createTrustedExecutionContext({ ...values, model });\n}\n\n/**\n * A client view answers this symbol with its official instrumentation's\n * `diagnostics`: what `createMigrationClient` discloses through `$driver`.\n */\nexport const CLIENT_DIAGNOSTICS = Symbol(\"viborm.client.diagnostics\");\n\n/** Read only the chain attached by the trusted context owner. */\nexport function getExecutionExtensionChain(\n context: QueryExecutionContext | undefined\n): ResolvedExtensionChain | undefined {\n if (!context) return undefined;\n return trusted(context)?.extensionChain;\n}\n\n/** `value` as a trusted execution context, if it is one. */\nexport function trustedExecutionContext(\n value: object\n): QueryExecutionContext | undefined {\n return trusted(value) === undefined ? undefined : value;\n}\n\n/** The origin belongs to the exact deferred operation, never caller-spoofed metadata. */\nexport function getExecutionCallsite(\n context: QueryExecutionContext | undefined\n): string | undefined {\n return context ? trusted(context)?.callsite : undefined;\n}\n\n/** Attach private lifecycle notifications without accepting caller-spoofed state. */\nexport function bindExecutionTransactionPhases(\n context: QueryExecutionContext,\n transactionPhases: TransactionPhaseNotifications\n): QueryExecutionContext {\n const values = trusted(context) ?? snapshotExternalExecutionContext(context);\n return createTrustedExecutionContext({ ...values, transactionPhases });\n}\n\n/** Add one private lifecycle reader without replacing an existing consumer. */\nexport function appendExecutionTransactionPhases(\n context: QueryExecutionContext,\n appendedPhases: TransactionPhaseNotifications\n): QueryExecutionContext {\n const values = trusted(context) ?? snapshotExternalExecutionContext(context);\n const existingPhases = values.transactionPhases;\n if (existingPhases === undefined) {\n return createTrustedExecutionContext({\n ...values,\n transactionPhases: appendedPhases,\n });\n }\n return createTrustedExecutionContext({\n ...values,\n transactionPhases: {\n readyToCommit: () => {\n appendedPhases.readyToCommit();\n existingPhases.readyToCommit();\n },\n committed: () => {\n appendedPhases.committed();\n existingPhases.committed();\n },\n },\n });\n}\n\n/** Read lifecycle notifications only from a context created by this owner. */\nexport function getExecutionTransactionPhases(\n context: QueryExecutionContext | undefined\n): TransactionPhaseNotifications | undefined {\n if (!context) return undefined;\n return trusted(context)?.transactionPhases;\n}\n\nfunction createTrustedExecutionContext(\n values: TrustedExecutionContext\n): QueryExecutionContext {\n return new TrustedSnapshot(values) as QueryExecutionContext;\n}\n\nfunction snapshotExternalExecutionContext(\n value: QueryExecutionContext | undefined\n): TrustedExecutionContext {\n return {\n correlationId: readString(value, \"correlationId\"),\n model: readString(value, \"model\"),\n operation: readString(value, \"operation\"),\n };\n}\n\nfunction representsExecutionContext(\n values: TrustedExecutionContext,\n model: string | undefined,\n operation: string | undefined,\n correlationId: string | undefined,\n correlationIdGetter: (() => string) | undefined,\n extensionChain: ResolvedExtensionChain | undefined,\n transactionPhases: TransactionPhaseNotifications | undefined,\n callsite: string | undefined,\n recoverable: true | undefined\n): boolean {\n return (\n values.recoverable === recoverable &&\n values.callsite === callsite &&\n values.model === model &&\n values.operation === operation &&\n values.correlationId === correlationId &&\n values.correlationIdGetter === correlationIdGetter &&\n values.extensionChain === extensionChain &&\n values.transactionPhases === transactionPhases\n );\n}\n\nfunction readString(\n value: QueryExecutionContext | undefined,\n key: keyof QueryExecutionContext\n): string | undefined {\n const member = readProperty(value, key);\n return typeof member === \"string\" ? member : undefined;\n}\n\nfunction readProperty(value: unknown, key: PropertyKey): unknown {\n if ((typeof value !== \"object\" && typeof value !== \"function\") || !value) {\n return undefined;\n }\n try {\n return Reflect.get(value, key);\n } catch {\n return undefined;\n }\n}\n","import {\n coded,\n VibORMError,\n VibORMErrorCode,\n type VibORMErrorMeta,\n} from \"./base\";\n\n/**\n * Invalid TTL format or value\n */\nexport class CacheInvalidTTLError extends coded<\n typeof VibORMErrorCode.CACHE_INVALID_TTL,\n { meta?: VibORMErrorMeta }\n>(\"CacheInvalidTTLError\", VibORMErrorCode.CACHE_INVALID_TTL) {}\n\n/**\n * Invalid cache key (circular reference, uncacheable type)\n */\nexport class CacheInvalidKeyError extends coded<\n typeof VibORMErrorCode.CACHE_INVALID_KEY,\n { meta?: VibORMErrorMeta }\n>(\"CacheInvalidKeyError\", VibORMErrorCode.CACHE_INVALID_KEY) {}\n\n/**\n * Operation cannot be cached (e.g., mutation operations)\n */\nexport class CacheOperationNotCacheableError extends VibORMError {\n static override readonly diagnosticName = \"CacheOperationNotCacheableError\";\n\n /** Literal discriminant: this class always carries `CACHE_OPERATION_NOT_CACHEABLE`. */\n declare readonly code: typeof VibORMErrorCode.CACHE_OPERATION_NOT_CACHEABLE;\n\n constructor(\n operation: string,\n cacheableOperations: string[],\n options?: { meta?: VibORMErrorMeta }\n ) {\n super(\n `Operation \"${operation}\" is not cacheable. Only read operations can be cached: ${cacheableOperations.join(\", \")}`,\n VibORMErrorCode.CACHE_OPERATION_NOT_CACHEABLE,\n {\n meta: { ...options?.meta, operation },\n }\n );\n }\n}\n\n/**\n * Invalid or missing cache configuration (options or driver)\n */\nexport class CacheConfigurationError extends coded<\n typeof VibORMErrorCode.CACHE_CONFIGURATION,\n { cause?: Error | undefined; meta?: VibORMErrorMeta }\n>(\"CacheConfigurationError\", VibORMErrorCode.CACHE_CONFIGURATION) {}\n","import { coded, VibORMErrorCode } from \"./base\";\n\n/**\n * Unique constraint violation\n */\nexport class UniqueConstraintError extends coded<\n typeof VibORMErrorCode.UNIQUE_CONSTRAINT\n>(\"UniqueConstraintError\", VibORMErrorCode.UNIQUE_CONSTRAINT) {}\n\n/**\n * Foreign key constraint violation\n */\nexport class ForeignKeyError extends coded<\n typeof VibORMErrorCode.FOREIGN_KEY_CONSTRAINT\n>(\"ForeignKeyError\", VibORMErrorCode.FOREIGN_KEY_CONSTRAINT) {}\n\n/**\n * Not-null constraint violation\n */\nexport class NotNullConstraintError extends coded<\n typeof VibORMErrorCode.NOT_NULL_CONSTRAINT\n>(\"NotNullConstraintError\", VibORMErrorCode.NOT_NULL_CONSTRAINT) {}\n\n/**\n * Check constraint violation\n */\nexport class CheckConstraintError extends coded<\n typeof VibORMErrorCode.CHECK_CONSTRAINT\n>(\"CheckConstraintError\", VibORMErrorCode.CHECK_CONSTRAINT) {}\n\n/**\n * Value too long for the column's declared type (Prisma P2000)\n *\n * Raised where the database enforces a column length: PostgreSQL SQLSTATE 22001\n * (`string_data_right_truncation`) and MySQL errno 1406 (`ER_DATA_TOO_LONG`).\n *\n * **SQLite raises nothing comparable.** SQLite ignores declared type lengths entirely\n * (`VARCHAR(5)` stores any string), so an over-long value is written, not rejected; the only\n * related error, `SQLITE_TOOBIG`, fires at the ~1GB `SQLITE_MAX_LENGTH` limit and means a\n * different thing. Prisma behaves the same way — quaint's SQLite connector has no arm for it,\n * so it falls through to a generic query error rather than P2000\n * (`quaint/src/connector/sqlite/error.rs`). VibORM therefore keeps `QueryError` on SQLite\n * instead of manufacturing a P2000 that the engine cannot honestly promise.\n */\nexport class ValueTooLongError extends coded<\n typeof VibORMErrorCode.VALUE_TOO_LONG\n>(\"ValueTooLongError\", VibORMErrorCode.VALUE_TOO_LONG) {}\n\n/**\n * Type guard for unique constraint errors\n */\nexport function isUniqueConstraintError(\n error: unknown\n): error is UniqueConstraintError {\n return error instanceof UniqueConstraintError;\n}\n\n/**\n * Type guard for foreign key errors\n */\nexport function isForeignKeyError(error: unknown): error is ForeignKeyError {\n return error instanceof ForeignKeyError;\n}\n\n/**\n * Type guard for not-null constraint errors\n */\nexport function isNotNullConstraintError(\n error: unknown\n): error is NotNullConstraintError {\n return error instanceof NotNullConstraintError;\n}\n\n/**\n * Type guard for check constraint errors\n */\nexport function isCheckConstraintError(\n error: unknown\n): error is CheckConstraintError {\n return error instanceof CheckConstraintError;\n}\n\n/**\n * Type guard for value-too-long errors\n */\nexport function isValueTooLongError(\n error: unknown\n): error is ValueTooLongError {\n return error instanceof ValueTooLongError;\n}\n","import { isVibORMError, type VibORMError } from \"./base\";\nimport {\n getTrustedRecordSeriesProgress,\n type RecordSeriesProgress,\n registerTrustedRecordSeriesProgress,\n sanitizeRecordSeriesProgress,\n} from \"./diagnostics\";\nimport { QueryEngineError } from \"./query\";\n\n/**\n * Enrich the owned failure after segment-atomic execution has stopped. The\n * database executor supplies counters only; this errors-layer boundary validates\n * them, updates direct metadata, and updates trusted serialization together.\n */\nexport function attachRecordSeriesProgress<T extends VibORMError>(\n error: T,\n progress: RecordSeriesProgress\n): T;\nexport function attachRecordSeriesProgress(\n error: unknown,\n progress: RecordSeriesProgress\n): unknown;\nexport function attachRecordSeriesProgress(\n error: unknown,\n progress: RecordSeriesProgress\n): unknown {\n const ownedError = isVibORMError(error)\n ? error\n : new QueryEngineError(\n \"Record-series execution failed at a committed-segment boundary.\",\n error instanceof Error ? { cause: error } : undefined\n );\n // One failure crosses one terminal series boundary. If a wrapper encounters\n // the same error again, retain the first trusted observation so public\n // metadata and trusted serialization cannot diverge.\n const trusted = getTrustedRecordSeriesProgress(ownedError);\n const sanitized = trusted ?? sanitizeRecordSeriesProgress(progress);\n if (!sanitized) return error;\n Object.defineProperty(ownedError.meta, \"recordSeriesProgress\", {\n configurable: true,\n enumerable: true,\n value: sanitized,\n writable: true,\n });\n if (!trusted) {\n registerTrustedRecordSeriesProgress(ownedError, sanitized);\n }\n return ownedError;\n}\n\n/** A committed prefix forbids the routed whole-operation retry. */\nexport function hasCommittedRecordSeriesProgress(error: unknown): boolean {\n if (!isVibORMError(error)) return false;\n const progress = getTrustedRecordSeriesProgress(error);\n return (\n (progress?.committedSegments ?? 0) > 0 ||\n progress?.mayHaveCommittedSegment === true\n );\n}\n","/**\n * Query Engine Types\n *\n * Shared types used across the query engine.\n */\n\nimport type { QueryExecutionContext } from \"@drivers/driver\";\nimport type { QueryResult } from \"@drivers/types\";\nimport type { Model } from \"@schema/model\";\nimport type { RelationCardinality } from \"@schema/relation\";\nimport type { Scalar } from \"@schema/scalars\";\nimport type { NormalizedRecurrence } from \"@validation/relations/recurrence\";\n\n// Re-export errors from unified error hierarchy\nexport {\n NestedWriteError,\n NotFoundError,\n QueryEngineError,\n ValidationError,\n} from \"@errors\";\n// Re-export Sql for convenience\nexport { Sql } from \"@sql\";\n\n// ============================================================\n// BATCH EXECUTION TYPES\n// ============================================================\n\n/**\n * Prepared query ready for batch execution\n */\nexport interface PreparedQuery {\n /** SQL string */\n sql: string;\n /** Query parameters */\n params: unknown[];\n /** Immutable attribution captured when the ORM operation was created. */\n context: QueryExecutionContext;\n}\n\n/**\n * One logical operation expanded into driver-level batch queries.\n */\nexport interface PreparedBatchOperation<T = unknown> {\n queries: PreparedQuery[];\n guards?: PreparedBatchGuard[];\n parseResult: (results: QueryResult<unknown>[]) => T;\n}\n\n/**\n * What a prepared guard publishes when its premise does not hold: the typed\n * failure taxonomy plus the `raceable` bit fixed by the guard's premise class.\n * `batch-error-attribution.ts` is the one algorithm that reads it, and the one\n * place it becomes an `Error`.\n */\nexport interface PreparedGuardFailure {\n readonly kind:\n | \"foreignKey\"\n | \"forbidden\"\n | \"nestedWrite\"\n | \"notFound\"\n | \"query\";\n readonly message: string;\n readonly relation?: string;\n /** A `forbidden` refusal's cause, where the operation alone does not say it. */\n readonly reason?: string;\n readonly raceable: boolean;\n}\n\n/** Declarative ownership for one assertion query in a prepared operation. */\nexport interface PreparedBatchGuard {\n readonly queryIndex: number;\n readonly premise: \"exists\" | \"notExists\";\n readonly probe: import(\"@sql\").Sql;\n readonly failure: PreparedGuardFailure;\n readonly model: string;\n readonly operation: Operation;\n}\n\n/**\n * Options for engine.prepare()\n */\nexport interface PrepareOptions {\n /** Throw NotFoundError if result is null (for OrThrow variants) */\n throwIfNotFound?: boolean;\n /** Original operation name for error messages */\n originalOperation?: string;\n /**\n * The client's last step on this operation's value (its chain's computed\n * fields), applied once, after every extension and the cache have run.\n */\n finishResult?: (value: unknown) => unknown;\n}\n\n/**\n * All supported operations.\n *\n * NOTE — `createManyAndReturn` / `updateManyAndReturn` / `deleteManyAndReturn`\n * are INTERNAL names, not client operations. The public surface has ONE name per\n * bulk family (maintainer decision D-1): `createMany` / `updateMany` /\n * `deleteMany` take an optional `select`, and its presence routes the tree to the\n * row-returning arm. These three tokens name that arm inside the SQL-building\n * substrate (result shape, program lowering, identity helpers); the client never\n * spells them, and they share their family's arg schema.\n */\nexport const OPERATIONS = [\n \"findFirst\",\n \"findMany\",\n \"findUnique\",\n \"create\",\n \"createMany\",\n \"createManyAndReturn\",\n \"update\",\n \"updateMany\",\n \"updateManyAndReturn\",\n \"delete\",\n \"deleteMany\",\n \"deleteManyAndReturn\",\n \"upsert\",\n \"count\",\n \"aggregate\",\n \"groupBy\",\n \"exist\",\n] as const;\n\nexport type Operation = (typeof OPERATIONS)[number];\n\n/** Requested fields inside one aggregate JSON carrier. */\nexport interface ExpectedAggregateResultShape {\n /** Undefined only for the scalar `_count: true` result. */\n fields?: ReadonlySet<string>;\n}\n\n/**\n * One arm of a polymorphic projection that the selection reads\n * (`selectedArm`, result/result-shape.ts); an arm `only` excludes is absent.\n */\nexport interface ExpectedPolymorphicVariantShape {\n readonly model: Model<any>;\n readonly shape: ExpectedResultShape;\n}\n\n/** Exact target-specific result contracts for one polymorphic projection. */\nexport interface ExpectedPolymorphicResultShape {\n /** Which carrier the read emitted: the singular tagged CASE, or the collection document. */\n readonly cardinality: \"one\" | \"many\";\n readonly optional: boolean;\n readonly variants: ReadonlyMap<string, ExpectedPolymorphicVariantShape>;\n}\n\n/** Exact public result contract for one ordinary relation projection. */\nexport interface ExpectedRelationResultShape {\n readonly model: Model<any>;\n readonly shape: ExpectedResultShape;\n readonly cardinality: RelationCardinality;\n readonly optional: boolean;\n /**\n * The admitted recurrence of a recursive slot, the same normalized value\n * execution consumes. `shape` is then the ONE repeated node, and the slot's\n * own key recurs inside every occurrence: absent at a numeric cutoff,\n * present on every occurrence of an exhaustive traversal.\n */\n readonly recurrence?: NormalizedRecurrence;\n}\n\n/** Exact raw columns and nested projections expected for one returned row. */\nexport interface ExpectedResultShape {\n /** Raw statement carrier declared by the compiled operation result. */\n carrier: \"rows\" | \"count\" | \"existence\";\n rawKeys: readonly string[];\n /** Scalar whose selected `_distance` expression produced the private column. */\n readonly distanceScalar?: Scalar;\n relations: ReadonlyMap<string, ExpectedRelationResultShape>;\n polymorphic: ReadonlyMap<string, ExpectedPolymorphicResultShape>;\n aggregates: ReadonlyMap<string, ExpectedAggregateResultShape>;\n relationCounts: ReadonlySet<string>;\n}\n","/**\n * The line of successors the package makes from one failure.\n *\n * One failure can reach a caller as several error objects: a statement fails,\n * then the package clones its error to add the operation's execution context\n * or a commit certainty. Whoever presents failures (the official\n * instrumentation logs a statement's, then the operation's) needs to know\n * that two of them are one: `errorOrigin` gives the first of the line.\n *\n * A `WeakMap` holds no strong reference: an entry disappears with the error\n * that keyed it, so nothing survives a request in a reused isolate.\n */\n\nconst origins = new WeakMap<object, Error>();\n\n/** Record that the package made `successor` from `source`. */\nexport function recordErrorSuccessor(source: Error, successor: Error): void {\n origins.set(successor, origins.get(source) ?? source);\n}\n\n/** The first error `error` was made from, or `error` itself. */\nexport function errorOrigin(error: Error): Error;\nexport function errorOrigin(error: unknown): unknown;\nexport function errorOrigin(error: unknown): unknown {\n return typeof error === \"object\" && error !== null\n ? (origins.get(error) ?? error)\n : error;\n}\n","import { TransactionError } from \"@errors\";\nimport type { TransactionPhaseNotifications } from \"../execution-context\";\n\nexport function nestedTransactionDispatchError(\n driverName: string\n): TransactionError {\n return new TransactionError(\n `Driver \"${driverName}\" received nested provider state outside TransactionBoundDriver.`,\n { meta: { driver: driverName, method: \"$transaction\" } }\n );\n}\n\nexport function unsupportedCallbackTransactionError(\n driverName: string\n): TransactionError {\n return new TransactionError(\n `Driver \"${driverName}\" does not support callback transactions.`,\n { meta: { driver: driverName, method: \"$transaction(callback)\" } }\n );\n}\n\n// A broken provider lifecycle cannot prove whether its handle remains safe.\nexport class ProviderTransactionContractError extends TransactionError {}\n\ntype LifecycleStep = () => unknown | Promise<unknown>;\n\nexport interface TransactionLifecycle<T> {\n readonly begin: LifecycleStep;\n readonly callback: () => Promise<T>;\n readonly commit: LifecycleStep;\n readonly rollback: LifecycleStep;\n readonly close?: LifecycleStep;\n readonly phases?: TransactionPhaseNotifications;\n}\n\nexport interface ProviderManagedTransaction<T, TTransaction> {\n readonly run: (\n callback: (tx: TTransaction) => Promise<T>\n ) => Promise<unknown>;\n readonly callback: (tx: TTransaction) => Promise<T>;\n readonly close: LifecycleStep;\n readonly phases?: TransactionPhaseNotifications;\n}\n\ntype ProviderCallbackOutcome<T> =\n | { readonly status: \"pending\" }\n | { readonly status: \"fulfilled\"; readonly value: T }\n | { readonly error: unknown; readonly status: \"rejected\" };\n\n/** Close provider-owned transaction state when its own cleanup/finalization fails. */\nexport async function runProviderManagedTransaction<T, TTransaction>(\n lifecycle: ProviderManagedTransaction<T, TTransaction>\n): Promise<T> {\n let callbackCallCount = 0;\n let callbackOutcome: ProviderCallbackOutcome<T> = {\n status: \"pending\",\n };\n const readCallbackOutcome = (): ProviderCallbackOutcome<T> => callbackOutcome;\n let callbackPromise: Promise<T> | undefined;\n let closeAttempted = false;\n const capturedCloseFailures: unknown[] = [];\n const closeBeforeCallbackDrain = async () => {\n closeAttempted = true;\n try {\n await lifecycle.close();\n } catch (error) {\n capturedCloseFailures.push(error);\n }\n };\n try {\n await lifecycle.run((tx) => {\n callbackCallCount++;\n if (callbackCallCount > 1) {\n throw new ProviderTransactionContractError(\n \"Transaction provider invoked the transaction callback more than once.\"\n );\n }\n callbackPromise = (async () => {\n try {\n const value = await lifecycle.callback(tx);\n lifecycle.phases?.readyToCommit();\n callbackOutcome = { status: \"fulfilled\", value };\n return value;\n } catch (error) {\n callbackOutcome = { status: \"rejected\", error };\n throw error;\n }\n })();\n callbackPromise.catch(() => undefined);\n return callbackPromise;\n });\n } catch (error) {\n const providerSettledBeforeCallback =\n callbackPromise !== undefined &&\n readCallbackOutcome().status === \"pending\";\n if (callbackPromise && providerSettledBeforeCallback) {\n await closeBeforeCallbackDrain();\n await callbackPromise.catch(() => undefined);\n }\n const settledOutcome = readCallbackOutcome();\n if (\n settledOutcome.status === \"rejected\" &&\n !providerSettledBeforeCallback &&\n error === settledOutcome.error\n ) {\n throw error;\n }\n const primaryFailure =\n settledOutcome.status === \"rejected\" ? settledOutcome.error : error;\n const cleanupFailures: unknown[] = [];\n if (providerSettledBeforeCallback) {\n cleanupFailures.push(\n new ProviderTransactionContractError(\n \"Transaction provider settled before the transaction callback settled.\"\n )\n );\n }\n if (\n settledOutcome.status === \"rejected\" &&\n error !== settledOutcome.error\n ) {\n cleanupFailures.push(\n ...readTransactionCleanupFailures(error, settledOutcome.error)\n );\n }\n cleanupFailures.push(...capturedCloseFailures);\n const cleanupSteps = cleanupFailures.map(failureStep);\n if (!closeAttempted) cleanupSteps.push(lifecycle.close);\n return throwAfterCleanup(primaryFailure, cleanupSteps);\n }\n const providerSettledBeforeCallback =\n callbackPromise !== undefined && readCallbackOutcome().status === \"pending\";\n if (callbackPromise && providerSettledBeforeCallback) {\n await closeBeforeCallbackDrain();\n await callbackPromise.catch(() => undefined);\n }\n const settledOutcome = readCallbackOutcome();\n const contractFailures: TransactionError[] = [];\n if (callbackCallCount !== 1) {\n contractFailures.push(\n new ProviderTransactionContractError(\n callbackCallCount === 0\n ? \"Transaction provider completed without invoking the transaction callback.\"\n : \"Transaction provider invoked the transaction callback more than once.\"\n )\n );\n }\n if (providerSettledBeforeCallback) {\n contractFailures.push(\n new ProviderTransactionContractError(\n \"Transaction provider completed before the transaction callback settled.\"\n )\n );\n }\n if (settledOutcome.status === \"rejected\") {\n contractFailures.push(\n new ProviderTransactionContractError(\n \"Transaction provider resolved after the transaction callback rejected.\"\n )\n );\n }\n if (contractFailures.length > 0) {\n const primaryFailure =\n settledOutcome.status === \"rejected\"\n ? settledOutcome.error\n : contractFailures.shift();\n const cleanupSteps = [\n ...contractFailures.map(failureStep),\n ...capturedCloseFailures.map(failureStep),\n ];\n if (!closeAttempted) cleanupSteps.push(lifecycle.close);\n return throwAfterCleanup(primaryFailure, cleanupSteps);\n }\n if (settledOutcome.status !== \"fulfilled\") {\n return throwAfterCleanup(\n new ProviderTransactionContractError(\n \"Transaction callback outcome was not recorded.\"\n ),\n [lifecycle.close]\n );\n }\n lifecycle.phases?.committed();\n return settledOutcome.value;\n}\n\n/** Run a top-level provider transaction without losing cleanup failures. */\nexport async function runTransactionLifecycle<T>(\n lifecycle: TransactionLifecycle<T>\n): Promise<T> {\n try {\n await lifecycle.begin();\n } catch (error) {\n return throwAfterCleanup(error, lifecycle.close ? [lifecycle.close] : []);\n }\n\n let result: T;\n try {\n result = await lifecycle.callback();\n } catch (error) {\n const cleanup = [lifecycle.rollback];\n if (lifecycle.close) cleanup.push(lifecycle.close);\n return throwAfterCleanup(error, cleanup);\n }\n\n lifecycle.phases?.readyToCommit();\n\n try {\n await lifecycle.commit();\n } catch (error) {\n const cleanup = [lifecycle.rollback];\n if (lifecycle.close) cleanup.push(lifecycle.close);\n return throwAfterCleanup(error, cleanup);\n }\n\n lifecycle.phases?.committed();\n\n if (lifecycle.close) await lifecycle.close();\n return result;\n}\n\nexport const runSavepoint = async <T>(\n executeStatement: (statement: string) => unknown | Promise<unknown>,\n fn: () => Promise<T>\n): Promise<T> => {\n const savepointName = `sp_${crypto.randomUUID().replace(/-/g, \"\")}`;\n await executeStatement(`SAVEPOINT ${savepointName}`);\n\n let result: T;\n try {\n result = await fn();\n } catch (error) {\n return throwAfterCleanup(error, [\n () => executeStatement(`ROLLBACK TO SAVEPOINT ${savepointName}`),\n () => executeStatement(`RELEASE SAVEPOINT ${savepointName}`),\n ]);\n }\n\n try {\n await executeStatement(`RELEASE SAVEPOINT ${savepointName}`);\n } catch (error) {\n return throwAfterCleanup(error, [\n () => executeStatement(`ROLLBACK TO SAVEPOINT ${savepointName}`),\n () => executeStatement(`RELEASE SAVEPOINT ${savepointName}`),\n ]);\n }\n return result;\n};\n\nexport function createTransactionCleanupError(\n primaryFailure: unknown,\n cleanupFailures: readonly unknown[]\n): AggregateError {\n return new AggregateError(\n [primaryFailure, ...cleanupFailures],\n readFailureMessage(primaryFailure),\n { cause: primaryFailure }\n );\n}\n\nexport function readTransactionCleanupFailures(\n error: unknown,\n primaryFailure: unknown\n): readonly unknown[] {\n try {\n if (!(error instanceof AggregateError) || error.cause !== primaryFailure) {\n return [error];\n }\n return error.errors[0] === primaryFailure ? error.errors.slice(1) : [error];\n } catch {\n return [error];\n }\n}\n\nasync function throwAfterCleanup(\n primaryFailure: unknown,\n cleanupSteps: readonly LifecycleStep[]\n): Promise<never> {\n const cleanupFailures: unknown[] = [];\n for (const cleanupStep of cleanupSteps) {\n try {\n await cleanupStep();\n } catch (error) {\n cleanupFailures.push(error);\n }\n }\n\n if (cleanupFailures.length > 0) {\n throw createTransactionCleanupError(primaryFailure, cleanupFailures);\n }\n throw primaryFailure;\n}\n\nfunction failureStep(failure: unknown): LifecycleStep {\n return () => {\n throw failure;\n };\n}\n\nfunction readFailureMessage(error: unknown): string {\n try {\n return error instanceof Error && typeof error.message === \"string\"\n ? error.message\n : \"Transaction failed\";\n } catch {\n return \"Transaction failed\";\n }\n}\n","import {\n CacheConfigurationError,\n CacheInvalidKeyError,\n CacheInvalidTTLError,\n CacheOperationNotCacheableError,\n CheckConstraintError,\n ClientInitializationError,\n ConnectionError,\n type DiagnosticDisclosure,\n FeatureNotSupportedError,\n ForbiddenError,\n ForeignKeyError,\n getTrustedErrorCause,\n getTrustedErrorDisclosure,\n InvalidTransactionInputError,\n MigrationError,\n NestedWriteAssertionError,\n NestedWriteError,\n NotFoundError,\n NotNullConstraintError,\n PendingOperationError,\n QueryEngineError,\n QueryError,\n resolveDiagnosticDisclosure,\n sanitizeErrorMetadata,\n TransactionError,\n UniqueConstraintError,\n UnsupportedOperationError,\n ValidationError,\n type ValidationErrorSource,\n ValueTooLongError,\n VibORMError,\n VibORMErrorCode,\n type VibORMErrorMeta,\n} from \"@errors\";\nimport { OPERATIONS, type Operation } from \"@query-engine/types\";\nimport {\n isArrayValue,\n isError,\n isRecord,\n isTrustedCode,\n safeArrayLength,\n safeOwnPropertyDescriptor,\n sanitizeSqlState,\n} from \"../errors/diagnostic-safety\";\nimport { recordErrorSuccessor } from \"../errors/logged-errors\";\nimport {\n readSuppressedFailures,\n withSuppressedFailure,\n} from \"./shared/suppressed-failure\";\nimport { ProviderTransactionContractError } from \"./shared/transactions\";\nimport type { Dialect } from \"./types\";\n\nexport interface DriverErrorShape {\n code?: string | number;\n bodyCode?: string | number;\n errno?: number;\n stringErrno?: string;\n constraint?: string;\n table?: string;\n column?: string;\n constraint_name?: string;\n table_name?: string;\n column_name?: string;\n sqlState?: string;\n sqlstate?: string;\n status?: string | number;\n statusCode?: string | number;\n}\n\nexport interface DriverErrorContext {\n driverName: string;\n /**\n * The SQL family that raised the error, when the normalizing call site knows\n * it. Only numeric provider codes need it: a symbolic name or a message\n * symbol identifies its own provider, but a bare integer does not.\n */\n dialect?: Dialect;\n model?: string;\n operation?: Operation | string;\n correlationId?: string;\n statementIndex?: number;\n query?: string;\n params?: unknown[];\n diagnostics?: DiagnosticDisclosure;\n callsite?: string;\n forceContext?: boolean;\n}\n\nconst EXECUTION_META_KEYS = [\n \"driver\",\n \"model\",\n \"operation\",\n \"correlationId\",\n \"callsite\",\n \"query\",\n \"params\",\n] as const;\nconst MYSQL_SQLSTATE_IN_MESSAGE_PATTERN = /\\(sqlstate ([^)]+)\\)/i;\nconst MYSQL_KEY_IN_MESSAGE_PATTERN = /for key '([^']+)'/;\n\nexport function readProperty(value: object, key: string): unknown {\n try {\n return Reflect.get(value, key);\n } catch {\n return undefined;\n }\n}\n\nexport function attachExecutionContext(\n error: VibORMError,\n context: DriverErrorContext\n): VibORMError {\n const snapshot = VibORMError.prototype.toJSON.call(error);\n const snapshotMeta = readProperty(snapshot, \"meta\");\n const mergedMeta = sanitizeErrorMetadata(\n isRecord(snapshotMeta) ? snapshotMeta : {},\n context.diagnostics\n );\n const forceContext = context.forceContext !== false;\n if (!forceContext) {\n if (\n resolveDiagnosticDisclosure(context.diagnostics).includeCallsite &&\n context.callsite\n )\n mergedMeta.callsite = context.callsite;\n return cloneVibORMError(error, mergedMeta, snapshot, context.diagnostics);\n }\n const additions = sanitizeErrorMetadata(\n buildMeta({}, context, \"\"),\n context.diagnostics\n );\n for (const key of EXECUTION_META_KEYS) {\n Reflect.deleteProperty(mergedMeta, key);\n }\n for (const key of Reflect.ownKeys(additions)) {\n if (typeof key !== \"string\") continue;\n Object.defineProperty(mergedMeta, key, {\n configurable: true,\n enumerable: true,\n value: additions[key],\n writable: true,\n });\n }\n return cloneVibORMError(error, mergedMeta, snapshot, context.diagnostics);\n}\n\n/**\n * Clone one trusted failure with `additions` on the meta keys it lacks, its\n * class, code, cause and disclosure kept: the inner owner of a fact wins.\n */\nexport function attachMissingMeta(\n error: VibORMError,\n additions: VibORMErrorMeta\n): VibORMError {\n const snapshot = VibORMError.prototype.toJSON.call(error);\n const snapshotMeta = readProperty(snapshot, \"meta\");\n const diagnostics = getTrustedErrorDisclosure(error);\n const meta = sanitizeErrorMetadata(\n isRecord(snapshotMeta) ? snapshotMeta : {},\n diagnostics\n );\n let added = false;\n for (const [key, value] of Object.entries(additions)) {\n if (value === undefined || meta[key] !== undefined) continue;\n meta[key] = value;\n added = true;\n }\n return added ? cloneVibORMError(error, meta, snapshot, diagnostics) : error;\n}\n\n/** Clone one trusted failure with the exact durable write state now known. */\nexport function attachCommitCertainty(\n error: VibORMError,\n commitCertainty: NonNullable<VibORMErrorMeta[\"commitCertainty\"]>\n): VibORMError {\n const snapshot = VibORMError.prototype.toJSON.call(error);\n const snapshotMeta = readProperty(snapshot, \"meta\");\n const diagnostics = getTrustedErrorDisclosure(error);\n const meta = sanitizeErrorMetadata(\n isRecord(snapshotMeta) ? snapshotMeta : {},\n diagnostics\n );\n meta.commitCertainty = commitCertainty;\n return cloneVibORMError(error, meta, snapshot, diagnostics);\n}\n\nfunction cloneVibORMError(\n error: VibORMError,\n meta: VibORMErrorMeta,\n snapshot: Record<string, unknown>,\n diagnostics: DiagnosticDisclosure | undefined\n): VibORMError {\n // The clone runs only the base constructor under the chosen class.\n // ValidationError owns state that constructor cannot rebuild, so it is\n // rebuilt from its snapshot here; every other class keeps its identity only\n // when it is one VibORM defines without such state.\n let cloneConstructor: unknown = VibORMError;\n if (error instanceof ValidationError) {\n const validationClone = cloneValidationError(error, meta, diagnostics);\n if (validationClone) {\n recordErrorSuccessor(error, validationClone);\n return transferSuppressedFailureEvidence(error, validationClone);\n }\n } else {\n cloneConstructor = getCloneConstructor(error);\n }\n const message =\n typeof snapshot.message === \"string\"\n ? snapshot.message\n : \"VibORM operation failed\";\n const code = isVibORMErrorCode(snapshot.code)\n ? snapshot.code\n : VibORMErrorCode.INTERNAL_ERROR;\n const cause = getTrustedErrorCause(error);\n const options = {\n ...(isError(cause) ? { cause } : {}),\n diagnostics,\n meta,\n };\n const newTarget =\n typeof cloneConstructor === \"function\" ? cloneConstructor : VibORMError;\n let candidate: unknown;\n try {\n candidate = Reflect.construct(\n VibORMError,\n [message, code, options],\n newTarget\n );\n } catch {\n candidate = new VibORMError(message, code, options);\n }\n const clonedError =\n candidate instanceof VibORMError\n ? candidate\n : new VibORMError(message, code, options);\n recordErrorSuccessor(error, clonedError);\n return transferSuppressedFailureEvidence(error, clonedError);\n}\n\n/**\n * Carry the evidence a failure retained onto the failure that replaces it, so\n * rebuilding a primary (a clone, a mapped provider error) never drops it.\n */\nexport function transferSuppressedFailureEvidence(\n source: unknown,\n target: VibORMError\n): VibORMError {\n for (const failure of readSuppressedFailures(source)) {\n withSuppressedFailure(target, failure);\n }\n return target;\n}\n\nfunction cloneValidationError(\n error: ValidationError,\n meta: VibORMErrorMeta,\n diagnostics: DiagnosticDisclosure | undefined\n): ValidationError | undefined {\n const serialized = VibORMError.prototype.toJSON.call(error);\n const source = snapshotValidationSource(readProperty(serialized, \"source\"));\n const issues = readProperty(serialized, \"issues\");\n if (!(source && isArrayValue(issues))) return undefined;\n const issueSnapshot = snapshotValidationIssues(issues);\n const cause = getTrustedErrorCause(error);\n return new ValidationError(source, issueSnapshot, {\n ...(isError(cause) ? { cause } : {}),\n diagnostics,\n meta,\n });\n}\n\nfunction snapshotValidationSource(\n value: unknown\n): ValidationErrorSource | undefined {\n if (!isRecord(value)) return undefined;\n const kind = readProperty(value, \"kind\");\n if (kind === \"operation\") {\n const operation = readProperty(value, \"operation\");\n const model = readProperty(value, \"model\");\n if (!isOperation(operation)) return undefined;\n return {\n kind,\n operation,\n ...(typeof model === \"string\" ? { model } : {}),\n };\n }\n if (kind === \"registry\") {\n const model = readProperty(value, \"model\");\n const property = readProperty(value, \"property\");\n return {\n kind,\n ...(typeof model === \"string\" ? { model } : {}),\n ...(typeof property === \"string\" ? { property } : {}),\n };\n }\n if (kind === \"schema-builder\") {\n const builder = readProperty(value, \"builder\");\n const path = readProperty(value, \"path\");\n if (!(typeof builder === \"string\" && typeof path === \"string\")) {\n return undefined;\n }\n return { kind, builder, path };\n }\n if (kind === \"json-schema\") {\n const target = readProperty(value, \"target\");\n const schemaType = readProperty(value, \"schemaType\");\n return {\n kind,\n ...(typeof target === \"string\" ? { target } : {}),\n ...(typeof schemaType === \"string\" ? { schemaType } : {}),\n };\n }\n return undefined;\n}\n\nfunction snapshotValidationIssues(value: unknown[]): Array<{\n path: string;\n message: string;\n}> {\n const issues: Array<{ path: string; message: string }> = [];\n const length = Math.min(safeArrayLength(value), 128);\n for (let index = 0; index < length; index += 1) {\n const descriptor = safeOwnPropertyDescriptor(value, String(index));\n if (!(descriptor && \"value\" in descriptor && isRecord(descriptor.value))) {\n continue;\n }\n const path = readProperty(descriptor.value, \"path\");\n const message = readProperty(descriptor.value, \"message\");\n if (typeof path !== \"string\" || typeof message !== \"string\") continue;\n issues.push({ path, message });\n }\n return issues;\n}\n\nfunction isOperation(value: unknown): value is Operation {\n return (\n typeof value === \"string\" &&\n (OPERATIONS as readonly string[]).includes(value)\n );\n}\n\n// Every VibORM error class whose state the base constructor rebuilds, so its\n// identity survives cloning. A class outside it — a caller's subclass, which\n// may own state no clone can reconstruct, or SchemaValidationError with its\n// issues — degrades to the base class rather than a hollow instance that\n// passes \\`instanceof\\` but breaks on its own members. ValidationError is\n// absent on purpose: it is rebuilt from its snapshot.\nconst CLONE_CONSTRUCTORS = [\n CacheConfigurationError,\n CacheInvalidKeyError,\n CacheInvalidTTLError,\n CacheOperationNotCacheableError,\n CheckConstraintError,\n ClientInitializationError,\n ConnectionError,\n FeatureNotSupportedError,\n ForbiddenError,\n ForeignKeyError,\n InvalidTransactionInputError,\n MigrationError,\n NestedWriteAssertionError,\n NestedWriteError,\n NotFoundError,\n NotNullConstraintError,\n PendingOperationError,\n QueryEngineError,\n QueryError,\n TransactionError,\n UniqueConstraintError,\n UnsupportedOperationError,\n ValueTooLongError,\n] as const;\n\nfunction getCloneConstructor(error: VibORMError): unknown {\n try {\n const prototype = Object.getPrototypeOf(error);\n if (prototype === ProviderTransactionContractError.prototype)\n return TransactionError;\n return (\n CLONE_CONSTRUCTORS.find((ctor) => ctor.prototype === prototype) ??\n VibORMError\n );\n } catch {\n return VibORMError;\n }\n}\n\n// The code shape rule, not membership in the enum object: reading the enum's\n// values would keep the whole object in every bundle, while member accesses\n// are inlined. The snapshot already passed the same rule when it was taken.\nfunction isVibORMErrorCode(value: unknown): value is VibORMErrorCode {\n return isTrustedCode(value);\n}\n\nexport function buildMeta(\n error: DriverErrorShape,\n context: DriverErrorContext,\n message: string\n): VibORMErrorMeta {\n const meta: VibORMErrorMeta = { driver: context.driverName };\n const disclosure = resolveDiagnosticDisclosure(context.diagnostics);\n\n if (disclosure.includeCallsite && context.callsite)\n meta.callsite = context.callsite;\n if (context.model) meta.model = context.model;\n if (context.operation) meta.operation = context.operation;\n if (context.correlationId) meta.correlationId = context.correlationId;\n if (context.statementIndex !== undefined) {\n meta.statementIndex = context.statementIndex;\n }\n if (disclosure.includeSql && context.query !== undefined) {\n meta.query = context.query;\n }\n if (disclosure.includeParams && context.params !== undefined) {\n meta.params = context.params;\n }\n\n const providerCode = error.code ?? error.bodyCode;\n if (typeof providerCode === \"string\" || typeof providerCode === \"number\") {\n meta.providerCode = providerCode;\n }\n if (typeof error.errno === \"number\") meta.providerErrno = error.errno;\n const sqlState =\n error.sqlState ??\n error.sqlstate ??\n sanitizeSqlState(providerCode) ??\n MYSQL_SQLSTATE_IN_MESSAGE_PATTERN.exec(message)?.[1];\n if (typeof sqlState === \"string\") meta.providerSqlState = sqlState;\n const status = error.status ?? error.statusCode;\n if (typeof status === \"string\" || typeof status === \"number\") {\n meta.providerStatus = status;\n }\n\n const constraint = error.constraint ?? error.constraint_name;\n const table = error.table ?? error.table_name;\n const column = error.column ?? error.column_name;\n if (constraint) meta.constraint = constraint;\n if (table) meta.table = table;\n if (column) meta.columns = [column];\n\n if (!meta.constraint) {\n const key = MYSQL_KEY_IN_MESSAGE_PATTERN.exec(message)?.[1];\n if (key) {\n const dotIndex = key.indexOf(\".\");\n if (dotIndex === -1) {\n meta.constraint = key;\n } else {\n meta.constraint = key.slice(dotIndex + 1);\n if (!meta.table) meta.table = key.slice(0, dotIndex);\n }\n }\n }\n return meta;\n}\n","import {\n attachRecordSeriesProgress,\n CheckConstraintError,\n ClientInitializationError,\n ConnectionError,\n type DiagnosticDisclosure,\n ForeignKeyError,\n getTrustedRecordSeriesProgress,\n isVibORMError,\n NESTED_WRITE_ASSERTION_FLOOR_MESSAGE,\n NestedWriteAssertionError,\n NotNullConstraintError,\n QueryError,\n TransactionError,\n type TransactionErrorCode,\n UniqueConstraintError,\n ValueTooLongError,\n type VibORMError,\n VibORMErrorCode,\n type VibORMErrorMeta,\n} from \"@errors\";\nimport {\n attachExecutionContext,\n buildMeta,\n type DriverErrorContext,\n type DriverErrorShape,\n readProperty,\n transferSuppressedFailureEvidence,\n} from \"./driver-error-context\";\nimport type { Dialect } from \"./types\";\n\n// Stop at \":\" so D1's \"users.email: SQLITE_CONSTRAINT\" suffix isn't captured\nconst BUN_SQL_STATE_PATTERN = /^[0-9A-Z]{5}$/;\nconst PROVIDER_CONNECTION_CODE_PATTERN =\n /^(?:CONNECTION_(?:CLOSED|DESTROYED|ENDED)$|ECONNREFUSED|ECONNRESET|ENOTFOUND|EAI_AGAIN|ETIMEDOUT|EPIPE$|ERR_POSTGRES_CONNECTION_|08[0-9A-Z]{3}$|57P0[123]$)/;\nconst SQLITE_CONSTRAINT_COLUMNS_PATTERN = /constraint failed: ([^:]+)/;\n// node-postgres (and the pg-compatible Neon pool) give a connection that\n// dropped under a statement, and every use of that client after it, no code:\n// only these messages. Unrecognized, both read as a refused statement (V2001).\nconst POSTGRES_CONNECTION_LOST_MESSAGES = new Set([\n \"Connection terminated unexpectedly\",\n \"Client has encountered a connection error and is not queryable\",\n]);\n// Symbolic BUSY/LOCKED codes are the exact base name or an underscore-delimited\n// extended family member. The delimiter is load-bearing: startsWith accepted\n// unrelated provider codes such as SQLITE_BUSYWORK and SQLITE_LOCKEDNESS.\nconst SQLITE_CONTENTION_FAMILY_PATTERN =\n /^SQLITE_(?:BUSY|LOCKED)(?:_[A-Z0-9]+)+$/;\nconst ASCII_PROVIDER_SYMBOL_PATTERN = /[A-Za-z0-9_]+/g;\n// An extended result code is `base | (sub << 8)`, so the whole family keeps its\n// base in the low byte. That byte alone proves nothing across providers —\n// MySQL errno 1029 also ends in 5 — so numeric recognition needs the dialect.\nconst SQLITE_BASE_CODE_MASK = 0xff;\nconst SQLITE_BUSY_BASE_CODE = 5;\nconst SQLITE_LOCKED_BASE_CODE = 6;\nconst MYSQL_ERRNO_IN_MESSAGE_PATTERN = /\\(errno (\\d+)\\)/;\n// Batch-plan assertions (adapter.assertions) fail on purpose with a\n// dialect-specific trick: division by zero on PG (SQLSTATE 22012), invalid\n// JSON via JSON_EXTRACT/json_extract on MySQL (errno 3141) and SQLite\n// (\"malformed JSON\"). The statements are identifiable by their column alias.\nexport const ASSERTION_MARKER = \"__viborm_assert__\";\n/**\n * A write judging the row it produces (`adapter.assertions.holds`) carries\n * this alias, and fails on its own refusal: the sentinel text its guard\n * names (PostgreSQL, SQLite: in the message) or, on MySQL, the invalid path\n * its sentinel is (errno 3143). Nothing else the statement raises is a\n * refusal, so a caller's division by zero or invalid JSON in it stays the\n * provider's failure (E5.6).\n */\nexport const JUDGEMENT_MARKER = \"__viborm_judged__\";\nconst REFUSAL_SENTINEL = \"__viborm_refused__\";\nconst MYSQL_INVALID_JSON_PATH = 3143;\nconst POSTGRES_DIVISION_BY_ZERO = \"22012\";\nconst MYSQL_INVALID_JSON_TEXT = 3141;\n\n// `json_each(?))` closes a bound member list (SQLite's `literals.list`): JSON\n// text the adapter stringified, which cannot raise \"malformed JSON\".\nconst JSON_ACCESS_SIGNATURE = /json(?!_each\\(\\?\\)\\))|->/i;\n\n/**\n * The dialects nothing collides with: SurrealDB raises no batch assertion,\n * and Snowflake runs no batch.\n */\ntype NoAssertionCollision = \"surrealql\" | \"snowflake\";\n\n// Every other dialect states its signature: one added to `Dialect` does not\n// compile until it is here or above. Checked by the type only, so the\n// dialects above cost an application no byte.\nconst FOREIGN_ASSERTION_SIGNATURE: Readonly<Partial<Record<Dialect, RegExp>>> =\n {\n postgresql: /[/%]/,\n mysql: JSON_ACCESS_SIGNATURE,\n sqlite: JSON_ACCESS_SIGNATURE,\n } satisfies Record<Exclude<Dialect, NoAssertionCollision>, RegExp>;\n\n/**\n * Report whether an ordinary statement can raise the same provider error as a\n * batch assertion. Assertion statements carry {@link ASSERTION_MARKER}; all\n * other statements are checked against the executing dialect's failure\n * signature. With an ownership set, assertions outside that set also collide.\n * A conservative match leaves the raw provider error unattributed.\n */\nexport function batchMayContainAssertionCollision(\n statements: readonly { readonly sql: string }[],\n dialect: Dialect,\n ownedAssertions?: ReadonlySet<number>\n): boolean {\n const signature = FOREIGN_ASSERTION_SIGNATURE[dialect];\n for (const [index, statement] of statements.entries()) {\n if (\n statement.sql.includes(ASSERTION_MARKER) ||\n statement.sql.includes(JUDGEMENT_MARKER)\n ) {\n if (ownedAssertions && !ownedAssertions.has(index)) return true;\n continue;\n }\n if (signature?.test(statement.sql)) return true;\n }\n return false;\n}\n\nfunction isRefusal(\n code: string | number | undefined,\n errno: number | undefined,\n message: string\n): boolean {\n return (\n message.includes(REFUSAL_SENTINEL) ||\n errno === MYSQL_INVALID_JSON_PATH ||\n code === \"ER_INVALID_JSON_PATH\"\n );\n}\n\nfunction isAssertionFailure(\n code: string | number | undefined,\n errno: number | undefined,\n message: string\n): boolean {\n return (\n code === POSTGRES_DIVISION_BY_ZERO ||\n code === \"ER_INVALID_JSON_TEXT_IN_PARAM\" ||\n errno === MYSQL_INVALID_JSON_TEXT ||\n message.includes(\"division by zero\") ||\n message.includes(\"malformed JSON\") ||\n message.includes(\"Invalid JSON text\")\n );\n}\n\nfunction isSQLiteContentionResultCode(\n value: string | number | undefined\n): boolean {\n if (typeof value !== \"number\" || !Number.isInteger(value) || value <= 0) {\n return false;\n }\n // biome-ignore lint/suspicious/noBitwiseOperators: SQLite defines an extended result code as `base | (sub << 8)`.\n const base = value & SQLITE_BASE_CODE_MASK;\n return base === SQLITE_BUSY_BASE_CODE || base === SQLITE_LOCKED_BASE_CODE;\n}\n\nfunction isSQLiteContentionName(value: string): boolean {\n return (\n value === \"SQLITE_BUSY\" ||\n value === \"SQLITE_LOCKED\" ||\n SQLITE_CONTENTION_FAMILY_PATTERN.test(value)\n );\n}\n\n/**\n * Report whether a provider error is SQLite lock contention, across the three\n * shapes drivers use: an extended symbolic code, an extended numeric result\n * code, or a message carrying the symbol (D1, libsql).\n */\nfunction isSQLiteContention(\n code: string | number | undefined,\n errno: number | undefined,\n message: string,\n dialect: Dialect | undefined\n): boolean {\n if (dialect !== \"sqlite\") return false;\n if (typeof code === \"string\" && isSQLiteContentionName(code)) {\n return true;\n }\n if (\n isSQLiteContentionResultCode(code) ||\n isSQLiteContentionResultCode(errno)\n ) {\n return true;\n }\n return [...message.matchAll(ASCII_PROVIDER_SYMBOL_PATTERN)].some((match) =>\n isSQLiteContentionName(match[0])\n );\n}\n\n/**\n * A recognized failure's class, called with one options shape. `QueryError`\n * is not one: it is the unrecognized fallback, and its `code` family differs.\n */\ntype FailureClass = new (\n message: string,\n options: {\n cause: Error;\n code: TransactionErrorCode | undefined;\n diagnostics: DiagnosticDisclosure | undefined;\n meta: VibORMErrorMeta;\n }\n) => DriverFailure;\n\n/** What one recognized provider failure becomes: class, message, and code when the class has a family. */\ntype FailureConstruction = readonly [\n failure: FailureClass,\n message: string,\n code?: TransactionErrorCode | undefined,\n ...rest: unknown[],\n];\n\ntype ProviderFailure = readonly [\n failure: FailureClass,\n message: string,\n code: TransactionErrorCode | undefined,\n /** PostgreSQL SQLSTATEs and SQLite extended symbolic codes, matched against `code`. */\n providerCodes: readonly unknown[],\n /** MySQL errnos, matched against `errno`. */\n mysqlErrnos: readonly unknown[],\n /** MySQL symbolic names, matched against `code`. */\n mysqlNames: readonly unknown[],\n /** A fragment of the SQLite message that names this failure. */\n sqliteMessage?: string,\n /** Whether that SQLite message lists the failing columns. */\n sqliteColumns?: true,\n];\n\nconst ASSERTION_FAILURE: FailureConstruction = [\n NestedWriteAssertionError,\n NESTED_WRITE_ASSERTION_FLOOR_MESSAGE,\n];\n// SQLite lock refusal is contention, not proof of a deadlock.\nconst SQLITE_CONTENTION_FAILURE: FailureConstruction = [\n TransactionError,\n \"Database is locked\",\n VibORMErrorCode.TRANSACTION_CONTENTION,\n];\n\n/**\n * The recognized provider failures. Precedence is the table read three times:\n * every row's provider code first, then every row's MySQL errno or name, then\n * (after SQLite lock contention) every row's SQLite message fragment. Within a\n * pass, the earlier row wins, so a MySQL errno outranks a later row's name.\n */\nconst PROVIDER_FAILURES: readonly ProviderFailure[] = [\n [\n UniqueConstraintError,\n \"Unique constraint violation\",\n undefined,\n [\"23505\", \"SQLITE_CONSTRAINT_UNIQUE\"],\n [1062],\n [\"ER_DUP_ENTRY\"],\n \"UNIQUE constraint failed\",\n true,\n ],\n [\n ForeignKeyError,\n \"Foreign key constraint violation\",\n undefined,\n // 23001 is restrict_violation — a RESTRICT referential action refused the\n // write. Stock PostgreSQL folds it into 23503; pg-wire servers (CockroachDB)\n // raise it as its own SQLSTATE with the same foreign-key metadata.\n [\"23503\", \"23001\", \"SQLITE_CONSTRAINT_FOREIGNKEY\"],\n // 1451 is ER_ROW_IS_REFERENCED_2: the parent row is still referenced.\n [1452, 1451],\n [\"ER_NO_REFERENCED_ROW_2\", \"ER_ROW_IS_REFERENCED_2\"],\n \"FOREIGN KEY constraint failed\",\n ],\n [\n NotNullConstraintError,\n \"Not-null constraint violation\",\n undefined,\n [\"23502\", \"SQLITE_CONSTRAINT_NOTNULL\"],\n [1048],\n [\"ER_BAD_NULL_ERROR\"],\n \"NOT NULL constraint failed\",\n true,\n ],\n [\n CheckConstraintError,\n \"Check constraint violation\",\n undefined,\n [\"23514\", \"SQLITE_CONSTRAINT_CHECK\"],\n [3819],\n [\"ER_CHECK_CONSTRAINT_VIOLATED\"],\n \"CHECK constraint failed\",\n ],\n [\n ValueTooLongError,\n \"Value too long for column type\",\n undefined,\n // 22001 is string_data_right_truncation and MySQL errno 1406 is\n // ER_DATA_TOO_LONG; Prisma maps both to LengthMismatch/P2000\n // (quaint/src/connector/{postgres,mysql}/error.rs). SQLite has no\n // counterpart: it does not enforce declared column lengths, and quaint's\n // SQLite connector leaves SQLITE_TOOBIG unmapped.\n [\"22001\"],\n [1406],\n [\"ER_DATA_TOO_LONG\"],\n ],\n [\n TransactionError,\n \"Transaction serialization failure\",\n VibORMErrorCode.SERIALIZATION_FAILURE,\n [\"40001\"],\n [],\n [],\n ],\n [\n TransactionError,\n \"Database lock is unavailable\",\n VibORMErrorCode.TRANSACTION_CONTENTION,\n [\"55P03\"],\n [],\n [],\n ],\n [\n TransactionError,\n \"Transaction deadlock detected\",\n VibORMErrorCode.DEADLOCK,\n [\"40P01\"],\n [1213],\n [\"ER_LOCK_DEADLOCK\"],\n ],\n];\n\n/**\n * Every error class {@link mapProviderError} constructs — the driver layer's failure\n * vocabulary, named so it is visible at the call sites instead of erased to `Error`.\n *\n * The members are disjoint by `code` — each class carries its literal — so this union is a\n * discriminated union: `if (failure.code === VibORMErrorCode.UNIQUE_CONSTRAINT)` selects\n * `UniqueConstraintError`, and an exhaustive `switch` over the codes bottoms out at `never`.\n *\n * `mapProviderError` is annotated with it, which is the point: adding a ninth class to the\n * mapper without adding it here is a compile error, not a silently widened return.\n */\nexport type DriverFailure =\n | ClientInitializationError\n | CheckConstraintError\n | ConnectionError\n | ForeignKeyError\n | NestedWriteAssertionError\n | NotNullConstraintError\n | QueryError\n | TransactionError\n | UniqueConstraintError\n | ValueTooLongError;\n\nfunction isConfigurationFailure(\n code: string | number | undefined,\n errno?: number\n): boolean {\n return (\n [\n \"28P01\",\n \"28000\",\n \"3D000\",\n \"ER_ACCESS_DENIED_ERROR\",\n \"ER_BAD_DB_ERROR\",\n ].includes(String(code)) ||\n errno === 1045 ||\n errno === 1049\n );\n}\n\nfunction isConnectionCapacityFailure(\n code: string | number | undefined,\n errno?: number\n): boolean {\n return (\n code === \"53300\" ||\n code === \"ER_CON_COUNT_ERROR\" ||\n code === \"ER_TOO_MANY_USER_CONNECTIONS\" ||\n errno === 1040 ||\n errno === 1203\n );\n}\n\nfunction configurationFailure(\n cause: Error,\n context: DriverErrorContext,\n meta: VibORMErrorMeta\n): ClientInitializationError {\n return new ClientInitializationError(\n \"Database authentication or configuration failed\",\n { cause, meta, diagnostics: context.diagnostics }\n );\n}\n\nfunction withProviderFailureEvidence<T extends DriverFailure>(\n error: unknown,\n failure: T\n): T {\n transferSuppressedFailureEvidence(error, failure);\n return failure;\n}\n\n/**\n * What {@link normalizeDriverError} can hand back.\n *\n * Two arms, and the type is the union of both. A raw provider error is mapped to a\n * {@link DriverFailure}. An error that is ALREADY a VibORM error is passed through with\n * execution context attached — and that arm is honestly `VibORMError`, not `DriverFailure`:\n * the incoming error can be any VibORM error the layers above threw (a `ValidationError`, an\n * engine refusal), `attachExecutionContext` clones it under its own class, and a stateful\n * class it cannot rebuild degrades to the base `VibORMError` (`driver-error-context.ts`).\n * Typing the whole function `DriverFailure` would be a claim this arm cannot keep.\n */\nexport type NormalizedDriverError = DriverFailure | VibORMError;\n\nexport function normalizeDriverError(\n error: unknown,\n context: DriverErrorContext\n): NormalizedDriverError {\n if (isKnownVibORMError(error)) {\n const normalized = attachExecutionContext(error, context);\n const progress = getTrustedRecordSeriesProgress(error);\n return progress\n ? attachRecordSeriesProgress(normalized, progress)\n : normalized;\n }\n return mapProviderError(error, context);\n}\n\n/**\n * Map a raw provider error onto the {@link DriverFailure} vocabulary. Split out of\n * {@link normalizeDriverError} so the constructed union has a return type to be checked\n * against — the passthrough arm above cannot carry that annotation, and a function has one\n * return type. {@link recognizeProviderFailure} decides which failure it is; this is the\n * one place it is constructed.\n */\nfunction mapProviderError(\n error: unknown,\n context: DriverErrorContext\n): DriverFailure {\n const cause = toError(error);\n const rawMessage = getErrorMessage(cause);\n const dbError = readDriverErrorShape(error);\n const meta = buildMeta(dbError, context, rawMessage);\n const stringErrno = dbError.stringErrno;\n const bunSqlState =\n context.driverName === \"bun-sql\" &&\n typeof dbError.code === \"string\" &&\n dbError.code.startsWith(\"ERR_POSTGRES\") &&\n BUN_SQL_STATE_PATTERN.test(stringErrno ?? \"\")\n ? stringErrno\n : undefined;\n const code = bunSqlState ?? dbError.sqlstate ?? dbError.code;\n if (bunSqlState) meta.providerCode = bunSqlState;\n if (isConfigurationFailure(code, dbError.errno))\n return withProviderFailureEvidence(\n error,\n configurationFailure(cause, context, meta)\n );\n const lost =\n code === undefined &&\n context.dialect === \"postgresql\" &&\n POSTGRES_CONNECTION_LOST_MESSAGES.has(rawMessage);\n if (\n lost ||\n (typeof code === \"string\" && PROVIDER_CONNECTION_CODE_PATTERN.test(code))\n ) {\n return withProviderFailureEvidence(\n error,\n new ConnectionError(\"Database connection failed\", {\n cause,\n diagnostics: context.diagnostics,\n meta,\n code:\n code === \"ETIMEDOUT\"\n ? VibORMErrorCode.CONNECTION_TIMEOUT\n : VibORMErrorCode.CONNECTION_FAILED,\n })\n );\n }\n const errno = dbError.errno ?? parseMessageErrno(rawMessage);\n if (errno !== undefined && meta.providerErrno === undefined) {\n meta.providerErrno = errno;\n }\n\n const diagnostics = context.diagnostics;\n // SQLSTATEs and MySQL constants name the physical failure, independently of\n // localized provider text. SQLite exposes these categories only in messages.\n const capacity = isConnectionCapacityFailure(code, errno);\n const schemaMismatch =\n code === \"42P01\" ||\n code === \"42703\" ||\n code === \"ER_NO_SUCH_TABLE\" ||\n code === \"ER_BAD_FIELD_ERROR\" ||\n errno === 1146 ||\n errno === 1054 ||\n (context.dialect === \"sqlite\" &&\n (rawMessage.includes(\"no such table:\") ||\n rawMessage.includes(\"no such column:\") ||\n rawMessage.includes(\"has no column named\")));\n const outOfRange =\n code === \"22003\" ||\n code === \"ER_WARN_DATA_OUT_OF_RANGE\" ||\n code === \"ER_DATA_OUT_OF_RANGE\" ||\n errno === 1264 ||\n errno === 1690 ||\n (context.dialect === \"sqlite\" && rawMessage.includes(\"integer overflow\"));\n if (capacity || schemaMismatch || outOfRange)\n return withProviderFailureEvidence(\n error,\n capacity\n ? new ConnectionError(\"Database connection capacity exhausted\", {\n cause,\n diagnostics,\n meta,\n code: VibORMErrorCode.CONNECTION_CAPACITY,\n })\n : new QueryError(\n schemaMismatch\n ? \"Database table or column does not exist\"\n : \"Value exceeds the database numeric range\",\n {\n cause,\n diagnostics,\n meta,\n code: schemaMismatch\n ? VibORMErrorCode.QUERY_SCHEMA_MISMATCH\n : VibORMErrorCode.QUERY_OUT_OF_RANGE,\n }\n )\n );\n if (code === \"57014\" || code === \"ER_LOCK_WAIT_TIMEOUT\" || errno === 1205) {\n return withProviderFailureEvidence(\n error,\n new QueryError(\"Query timed out\", {\n cause,\n diagnostics,\n meta,\n code: VibORMErrorCode.QUERY_TIMEOUT,\n })\n );\n }\n const recognized = recognizeProviderFailure(\n code,\n errno,\n rawMessage,\n meta,\n context\n );\n let failure: DriverFailure;\n if (recognized) {\n const [Failure, message, failureCode] = recognized;\n failure = new Failure(message, {\n cause,\n code: failureCode,\n diagnostics,\n meta,\n });\n } else {\n failure = new QueryError(\"Query execution failed\", {\n cause,\n diagnostics,\n meta,\n });\n }\n transferSuppressedFailureEvidence(error, failure);\n return failure;\n}\n\n/**\n * Which failure a raw provider error is. An assertion statement's own failure\n * comes first; then {@link PROVIDER_FAILURES} in its three passes, with SQLite\n * lock contention before the SQLite message pass. Anything else is not\n * recognized.\n */\nfunction recognizeProviderFailure(\n code: string | number | undefined,\n errno: number | undefined,\n message: string,\n meta: VibORMErrorMeta,\n context: DriverErrorContext\n): FailureConstruction | undefined {\n if (\n (context.query?.includes(JUDGEMENT_MARKER) &&\n isRefusal(code, errno, message)) ||\n (context.query?.includes(ASSERTION_MARKER) &&\n isAssertionFailure(code, errno, message))\n ) {\n return ASSERTION_FAILURE;\n }\n const recognized =\n PROVIDER_FAILURES.find((row) => row[3].includes(code)) ??\n PROVIDER_FAILURES.find(\n (row) => row[4].includes(errno) || row[5].includes(code)\n );\n if (recognized) {\n if (recognized[7] && typeof code === \"string\" && code.startsWith(\"SQLITE_\"))\n attachSQLiteColumns(message, meta);\n return recognized;\n }\n if (isSQLiteContention(code, errno, message, context.dialect)) {\n return SQLITE_CONTENTION_FAILURE;\n }\n return findSQLiteMessageFailure(message, meta);\n}\n\n/**\n * What {@link normalizeDriverConnectionError} can hand back — the connection variant of\n * {@link NormalizedDriverError}. The constructed arm is exactly {@link ConnectionError}; the\n * passthrough arm is `VibORMError` for the same two reasons documented there.\n */\nexport type NormalizedConnectionError = ConnectionError | VibORMError;\n\nexport function normalizeDriverConnectionError(\n error: unknown,\n context: DriverErrorContext,\n message = \"Database connection failed\"\n): NormalizedConnectionError {\n if (isKnownVibORMError(error)) {\n return attachExecutionContext(error, context);\n }\n\n const cause = toError(error);\n const rawMessage = getErrorMessage(cause);\n const dbError = readDriverErrorShape(error);\n const meta = buildMeta(dbError, context, rawMessage);\n const errno = dbError.errno ?? parseMessageErrno(rawMessage);\n if (errno !== undefined && meta.providerErrno === undefined) {\n meta.providerErrno = errno;\n }\n const code = dbError.sqlstate ?? dbError.code;\n if (isConfigurationFailure(code, errno))\n return withProviderFailureEvidence(\n error,\n configurationFailure(cause, context, meta)\n );\n return withProviderFailureEvidence(\n error,\n new ConnectionError(\n isConnectionCapacityFailure(code, errno)\n ? \"Database connection capacity exhausted\"\n : message,\n {\n cause,\n diagnostics: context.diagnostics,\n meta,\n code: isConnectionCapacityFailure(code, errno)\n ? VibORMErrorCode.CONNECTION_CAPACITY\n : code === \"ETIMEDOUT\"\n ? VibORMErrorCode.CONNECTION_TIMEOUT\n : VibORMErrorCode.CONNECTION_FAILED,\n }\n )\n );\n}\n\nfunction isKnownVibORMError(error: unknown): error is VibORMError {\n try {\n return isVibORMError(error);\n } catch {\n return false;\n }\n}\n\nfunction toError(error: unknown): Error {\n try {\n return error instanceof Error ? error : new Error(\"Unknown provider error\");\n } catch {\n return new Error(\"Unknown provider error\");\n }\n}\n\nfunction getErrorMessage(error: Error): string {\n try {\n return typeof error.message === \"string\"\n ? error.message\n : \"Unknown provider error\";\n } catch {\n return \"Unknown provider error\";\n }\n}\n\nfunction readDriverErrorShape(error: unknown): DriverErrorShape {\n if ((typeof error !== \"object\" && typeof error !== \"function\") || !error) {\n return {};\n }\n const body = readProperty(error, \"body\");\n const errno = readProperty(error, \"errno\");\n return {\n code: readStringOrNumber(error, \"code\"),\n bodyCode:\n body && (typeof body === \"object\" || typeof body === \"function\")\n ? readStringOrNumber(body, \"code\")\n : undefined,\n errno: typeof errno === \"number\" ? errno : undefined,\n stringErrno: typeof errno === \"string\" ? errno : undefined,\n constraint: readString(error, \"constraint\"),\n table: readString(error, \"table\"),\n column: readString(error, \"column\"),\n constraint_name: readString(error, \"constraint_name\"),\n table_name: readString(error, \"table_name\"),\n column_name: readString(error, \"column_name\"),\n sqlState: readString(error, \"sqlState\"),\n sqlstate: readString(error, \"sqlstate\"),\n status: readStringOrNumber(error, \"status\"),\n statusCode: readStringOrNumber(error, \"statusCode\"),\n };\n}\n\nfunction readString(value: object, key: string): string | undefined {\n const member = readProperty(value, key);\n return typeof member === \"string\" ? member : undefined;\n}\n\nfunction readStringOrNumber(\n value: object,\n key: string\n): string | number | undefined {\n const member = readProperty(value, key);\n return typeof member === \"string\" || typeof member === \"number\"\n ? member\n : undefined;\n}\n\nfunction parseMessageErrno(message: string): number | undefined {\n const match = MYSQL_ERRNO_IN_MESSAGE_PATTERN.exec(message);\n return match?.[1] ? Number(match[1]) : undefined;\n}\n\n/**\n * The first row whose SQLite message fragment the provider message carries, in\n * table order. UNIQUE and NOT NULL messages also name their columns.\n */\nfunction findSQLiteMessageFailure(\n message: string,\n meta: VibORMErrorMeta\n): ProviderFailure | undefined {\n const row = PROVIDER_FAILURES.find(\n (candidate) => candidate[6] && message.includes(candidate[6])\n );\n if (row?.[7]) attachSQLiteColumns(message, meta);\n return row;\n}\n\nfunction attachSQLiteColumns(message: string, meta: VibORMErrorMeta): void {\n const match = SQLITE_CONSTRAINT_COLUMNS_PATTERN.exec(message);\n if (!match?.[1]) return;\n // Accept only an unambiguous identifier list. Quoted dots/commas are leaves,\n // not separators; arbitrary constraint expressions never become column names.\n const identifier = String.raw`(?:\"(?:[^\"]|\"\")*\"|\\`(?:[^\\`]|\\`\\`)*\\`|\\[[^\\]]+\\]|[A-Za-z_][A-Za-z0-9_$]*)`;\n const path = `${identifier}(?:\\\\s*\\\\.\\\\s*${identifier})*`;\n if (!new RegExp(`^\\\\s*${path}(?:\\\\s*,\\\\s*${path})*\\\\s*$`).test(match[1]))\n return;\n const paths = match[1].match(new RegExp(path, \"g\"));\n if (!paths) return;\n const columns: string[] = [];\n const tables = new Set<string>();\n for (const qualified of paths) {\n const parts = qualified.match(new RegExp(identifier, \"g\"));\n if (!parts?.length) return;\n const names = parts.map((part) => {\n if (part.startsWith('\"')) return part.slice(1, -1).replaceAll('\"\"', '\"');\n if (part.startsWith(\"`\")) return part.slice(1, -1).replaceAll(\"``\", \"`\");\n if (part.startsWith(\"[\")) return part.slice(1, -1);\n return part;\n });\n const column = names.pop();\n if (column === undefined) return;\n columns.push(column);\n if (names.length) tables.add(names.join(\".\"));\n }\n meta.columns = columns;\n if (tables.size === 1) meta.table = tables.values().next().value;\n}\n"],"mappings":"6eA6BA,IAAM,EAAN,MAAM,eAAgB,CACpB,GACA,MACA,UAQA,OAAA,EAAyD,CACvD,aAAc,GACd,WAAY,GACZ,KAAkB,CAChB,OAAO,gBAAgB,OAAO,KAAK,EAAE,uBAAuB,EAE/D,CACD,YAAY,EAAiC,CAC3C,MAAA,EAAe,EACX,EAAO,QAAO,KAAK,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Y,IAAI,CAAC,CAC1D,GAAI,CAAC,GAAO,OAAQ,OACpB,IAAM,EAAQ,EAAM,IAAK,GACnB,EAAK,WAAW,IAAI,CAAS,EAAK,MAAM,EAAG,GAAG,CAAC,WAAW,KAAM,IAAI,CACpE,EAAK,WAAW,IAAI,CAAS,EAAK,MAAM,EAAG,GAAG,CAAC,WAAW,KAAM,IAAI,CACpE,EAAK,WAAW,IAAI,CAAS,EAAK,MAAM,EAAG,GAAG,CAC3C,EACP,CACI,EAAS,EAAM,KAAK,CAC1B,GAAI,IAAW,IAAA,GAAW,OAC1B,EAAQ,KAAK,EAAO,CAChB,EAAM,QAAQ,EAAO,IAAI,EAAM,KAAK,IAAI,CAAC,CAE/C,EAAK,QAAU,EACX,EAAO,OAAS,IAAG,EAAK,MAAQ,EAAO,QAAQ,CAAC,MAAM,CAAC"}
@@ -1,2 +0,0 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{v as t}from"./serializer-rBq3v1xr.mjs";import{n,t as r}from"./libsql-DuGR904j.mjs";import{t as i}from"./mysql-BNXWfTOo.mjs";import{t as a}from"./postgres-CDdh5dSP.mjs";import{t as o}from"./snowflake-UOCC820W.mjs";import{t as s}from"./surrealql-C1dp1sWw.mjs";function registerEveryMigrationDriver(){t(a),t(n),t(r),t(i),t(s),t(o)}export{registerEveryMigrationDriver as t};
2
- //# sourceMappingURL=every-tOgQmaIE.mjs.map
@@ -1,2 +0,0 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{F as t,R as n,a as r,r as i,z as a}from"./error-mapping-B1-IWkCQ.mjs";import{t as o}from"./base-z-cH5ZBI.mjs";function createOperationExecutionContext(e,n,r){let i=r?.disclosure?.includeCallsite===!0?Error(`VibORM operation created here`).stack:void 0;return t({model:e,operation:n},createCorrelationId,r,i)}function createPendingOperationContext(e,t,n,r,i){return Object.freeze({clientId:n,scopeId:r,attribution:createOperationExecutionContext(e,t,i)})}function withOperationErrorContext(e,t){let i=n(e);if(i===void 0)return t();let s=a(e)?.disclosure,annotate=t=>{throw t instanceof o?r(t,{forceContext:!1,driverName:typeof t.meta.driver==`string`?t.meta.driver:`unknown`,model:e.model,operation:e.operation,correlationId:e.correlationId,callsite:i,diagnostics:s}):t};try{return t().catch(annotate)}catch(e){return Promise.reject().catch(()=>annotate(e))}}async function observeTransactionBatchPhase(e,t,r){let o=a(e)?.disclosure;try{return await r()}catch(r){throw i(r,{driverName:t.driverName,dialect:t.dialect,model:e.model,operation:e.operation,correlationId:e.correlationId,callsite:n(e),diagnostics:o,forceContext:!0})}}function createCorrelationId(){return typeof globalThis.crypto?.randomUUID==`function`?globalThis.crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}export{withOperationErrorContext as i,createPendingOperationContext as n,observeTransactionBatchPhase as r,createOperationExecutionContext as t};
2
- //# sourceMappingURL=execution-context-BXpcbyPe.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"execution-context-BXpcbyPe.mjs","names":[],"sources":["../src/query-engine/execution-context.ts"],"sourcesContent":["import { attachExecutionContext } from \"@drivers/driver-error-context\";\nimport { normalizeDriverError } from \"@drivers/error-mapping\";\nimport {\n createExecutionContext,\n getExecutionCallsite,\n getExecutionExtensionChain,\n} from \"@drivers/execution-context\";\nimport type { AnyDriver, QueryExecutionContext } from \"@drivers/exports\";\nimport { VibORMError } from \"@errors\";\nimport type { ResolvedExtensionChain } from \"@extensions/chain\";\nimport type { Operation } from \"./types\";\n\n/** Immutable ownership and attribution captured when an operation is created. */\nexport interface OperationExecutionContext {\n readonly clientId: symbol;\n readonly scopeId: symbol;\n readonly attribution: QueryExecutionContext;\n}\n\nexport function createOperationExecutionContext(\n model: string,\n operation: Operation | string,\n extensionChain?: ResolvedExtensionChain\n): QueryExecutionContext {\n // Capture before asynchronous request/plan/provider work, and allocate no stack by default.\n const origin =\n extensionChain?.disclosure?.includeCallsite === true\n ? new Error(\"VibORM operation created here\").stack\n : undefined;\n return createExecutionContext(\n { model, operation },\n createCorrelationId,\n extensionChain,\n origin\n );\n}\n\nexport function createPendingOperationContext(\n model: string,\n operation: Operation,\n clientId: symbol,\n scopeId: symbol,\n extensionChain?: ResolvedExtensionChain\n): OperationExecutionContext {\n return Object.freeze({\n clientId,\n scopeId,\n attribution: createOperationExecutionContext(\n model,\n operation,\n extensionChain\n ),\n });\n}\n\n/** Preserve an ORM failure's deferred origin without wrapping errors returned by user extensions. */\nexport function withOperationErrorContext<T>(\n context: QueryExecutionContext,\n execute: () => Promise<T>\n): Promise<T> {\n const callsite = getExecutionCallsite(context);\n if (callsite === undefined) return execute();\n const diagnostics = getExecutionExtensionChain(context)?.disclosure;\n const annotate = (error: unknown): never => {\n throw error instanceof VibORMError\n ? attachExecutionContext(error, {\n forceContext: false,\n driverName:\n typeof error.meta.driver === \"string\"\n ? error.meta.driver\n : \"unknown\",\n model: context.model,\n operation: context.operation,\n correlationId: context.correlationId,\n callsite,\n diagnostics,\n })\n : error;\n };\n try {\n return execute().catch(annotate);\n } catch (error) {\n return Promise.reject().catch(() => annotate(error));\n }\n}\n\n/** Observe native-batch preparation and parsing as one logical operation. */\nexport async function observeTransactionBatchPhase<R>(\n executionContext: QueryExecutionContext,\n driver: AnyDriver,\n execute: () => R | Promise<R>\n): Promise<R> {\n const diagnostics = getExecutionExtensionChain(executionContext)?.disclosure;\n try {\n return await execute();\n } catch (error) {\n throw normalizeDriverError(error, {\n driverName: driver.driverName,\n dialect: driver.dialect,\n model: executionContext.model,\n operation: executionContext.operation,\n correlationId: executionContext.correlationId,\n callsite: getExecutionCallsite(executionContext),\n diagnostics,\n forceContext: true,\n });\n }\n}\n\nexport function createCorrelationId(): string {\n if (typeof globalThis.crypto?.randomUUID === \"function\") {\n return globalThis.crypto.randomUUID();\n }\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;\n}\n"],"mappings":"8JAmBA,SAAgB,gCACd,EACA,EACA,EACuB,CAEvB,IAAM,EACJ,GAAgB,YAAY,kBAAoB,GACxC,MAA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--qS7OPmg.mjs";import{o as n}from"./value-guards-CBuxSC66.mjs";const r=[`declare`,`join`,`seal`];function extensionError(e,n){throw new t(e,{meta:n?{extension:n}:void 0})}function appendParts(e,t,n,i,a,o){t?.extensions.some(e=>e.name===n)&&extensionError(`Extension "${n}" is already present on this client.`,n);let s=new Set(e),c={...t,extensions:[...t?.extensions??[],{name:n}]},l={name:n,chain:t,next:c,owner:{name:n},schema:i,registry:o,bring:e=>{s.add(e)},made:a};for(let e of r)for(let t of s)t[e]?.(l);return c}function shared({made:e,schema:t},n,r){let i=e.get(t),a=Object.keys(t);(i===void 0||a.length!==Object.keys(i.models).length||a.some(e=>i.models[e]!==t[e]))&&(i={models:{...t},values:new Map},e.set(t,i));let{values:o}=i;return o.has(n)||o.set(n,r()),o.get(n)}const isPart=e=>n(e)&&(typeof e.declare==`function`||typeof e.join==`function`||typeof e.seal==`function`);function extension(e,...t){(typeof e!=`string`||e.trim().length===0)&&extensionError(`An extension's name must be a non-empty string.`),t.every(isPart)||extensionError(`Extension "${e}" takes parts built by viborm's part builders.`,e);let n=new WeakMap,r={name:e,append:(r,i,a)=>appendParts(t,r,e,i,n,a)};return Object.freeze(r)}const isAppliedExtension=e=>typeof e==`object`&&!!e&&`append`in e&&typeof e.append==`function`;export{shared as i,isAppliedExtension as n,extensionError as r,extension as t};
2
- //# sourceMappingURL=extension-CGepsF-p.mjs.map
@@ -1,2 +0,0 @@
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{a as r,s as i}from"./identity-CtW15WlB.mjs";import{closeSync as a,constants as o,existsSync as s,fsyncSync as c,linkSync as l,lstatSync as u,mkdirSync as d,openSync as f,readFileSync as p,readdirSync as m,unlinkSync as h,writeSync as g}from"node:fs";import{dirname as _,join as v,resolve as y}from"node:path";const b=`estate.json`;var FsEstateStorage=class{baseDir;constructor(e){this.baseDir=y(e)}async readEstate(){return readOptional(v(this.baseDir,b))}async listStates(){return listHexFiles(v(this.baseDir,`states`),`.json`)}async listSnapshots(){return listHexFiles(v(this.baseDir,`snapshots`),`.json`)}async listSql(){return listHexFiles(v(this.baseDir,`sql`),`.sql`)}async readState(e){return readOptional(v(this.baseDir,`states`,`${e}.json`))}async readSnapshot(e){return readOptional(v(this.baseDir,`snapshots`,`${e}.json`))}async readSql(e){return readOptional(v(this.baseDir,`sql`,`${e}.sql`))}async publishEstate(e){return publishNoReplace(this.baseDir,v(this.baseDir,b),e)}async publishSnapshot(e,t){return publishNoReplace(this.baseDir,v(this.baseDir,`snapshots`,`${e}.json`),t)}async publishSql(e,t){return publishNoReplace(this.baseDir,v(this.baseDir,`sql`,`${e}.sql`),t)}async publishState(e,t){return publishNoReplace(this.baseDir,v(this.baseDir,`states`,`${e}.json`),t)}};function createFsStorageWriter(e){return new FsEstateStorage(e)}function readOptional(e){return s(e)?(refuseSymlink(e),new Uint8Array(p(e))):null}function listHexFiles(e,t){if(!s(e))return[];refuseSymlink(e);let n=m(e),i=[];for(let e of n){if(e.startsWith(`.`)||e.endsWith(`.tmp`)||!e.endsWith(t))continue;let n=e.slice(0,-t.length);r(n)&&i.push(n)}return i.sort()}function publishNoReplace(e,r,u){assertInsideBase(e,r);let m=_(r);if(d(m,{recursive:!0}),refuseSymlink(m),s(r))return refuseSymlink(r),compareExisting(r,u);let y=v(m,`.${randomSuffix()}.tmp`),b=f(y,o.O_CREAT|o.O_EXCL|o.O_WRONLY,420);try{g(b,u),c(b)}finally{a(b)}if(i(p(y))!==i(u))throw h(y),new n(`Temporary estate write did not round-trip`,t.MIGRATION_CORRUPTION);try{l(y,r)}catch(e){if(unlinkQuiet(y),isErrno(e,`EEXIST`))return compareExisting(r,u);throw isErrno(e,`EXDEV`)||isErrno(e,`ENOSYS`)||isErrno(e,`EPERM`)?new n(`Filesystem cannot atomically publish with a no-replace hard link`,t.MIGRATION_STORAGE_REQUIRED,{cause:e instanceof Error?e:void 0}):e}return unlinkQuiet(y),fsyncDirectory(m),{outcome:`created`}}function compareExisting(e,r){if(i(p(e))!==i(r))throw new n(`Content-addressed path ${e} already holds different bytes`,t.MIGRATION_CORRUPTION);return fsyncDirectory(_(e)),{outcome:`identical`}}function refuseSymlink(e){if(u(e).isSymbolicLink())throw new n(`Estate storage refuses to follow symlinks`,t.MIGRATION_INVALID_ESTATE)}function fsyncDirectory(e){let t=f(e,o.O_RDONLY|o.O_DIRECTORY);try{c(t)}finally{a(t)}}function unlinkQuiet(e){try{h(e)}catch{}}function isErrno(e,t){return!!(e&&typeof e==`object`&&`code`in e&&e.code===t)}function randomSuffix(){return`${Date.now().toString(16)}-${Math.random().toString(16).slice(2)}`}function assertInsideBase(e,r){let i=y(r),a=e.endsWith(`/`)?e:`${e}/`;if(i!==y(e)&&!i.startsWith(a))throw new n(`Estate path escapes the storage root`,t.MIGRATION_INVALID_ESTATE)}export{createFsStorageWriter as t};
2
- //# sourceMappingURL=fs-estate-D1Nsg9G1.mjs.map
@@ -1,2 +0,0 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{$ as t,J as n,Lt as r,Mt as i,Q as a,S as o,Y as s,d as c,f as l,l as u,q as d,u as f}from"./native-types-DgjMUikz.mjs";const p=1e-10,m=6371008.8;function geoBoundsForDistance(e,t){if(t<=0)return{south:e.latitude,west:e.longitude,north:e.latitude,east:e.longitude};let n=t/m;if(n>=Math.PI)return{south:-90,west:-180,north:90,east:180};let r=e.latitude*Math.PI/180,i=n*180/Math.PI,a=Math.max(-90,e.latitude-i-p),o=Math.min(90,e.latitude+i+p);if(a===-90||o===90)return{south:a,west:-180,north:o,east:180};let s=Math.asin(Math.min(1,Math.sin(n)/Math.cos(r)))*180/Math.PI+p;return{south:a,west:normalizeLongitude(e.longitude-s),north:o,east:normalizeLongitude(e.longitude+s)}}function normalizeLongitude(e){return((e+180)%360+360)%360-180}const h=o({[i[0]]:u,[i[1]]:f,[i[2]]:u,[i[3]]:f},{partial:!1});function validateGeoBounds(e){let r=t(h,e);return r.issues?r:r.value.south>r.value.north?n(`GeoBounds south must be less than or equal to north`,[`south`]):r}function validateRing(e){let t=a(e,s);return t.issues?t:t.value.length<r?n(`A GeoPolygon ring needs at least ${r} vertices`):a(t.value,c)}const g=o({outer:d(`array`,validateRing),holes:l(d(`array`,e=>a(e,validateRing)))},{partial:!1}),_=Math.PI/180,v=1e-9*_,y=2*Math.sin(.005*_);function toVector(e,t){let n=Math.cos(t*_);return[n*Math.cos(e*_),n*Math.sin(e*_),Math.sin(t*_)]}function dot(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}function cross(e,t){let n=e[0]-t[0],r=e[1]-t[1],i=e[2]-t[2],a=e[0]+t[0],o=e[1]+t[1],s=e[2]+t[2];return[(r*s-i*o)/2,(i*a-n*s)/2,(n*o-r*a)/2]}function unit(e){let t=Math.hypot(...e);return[e[0]/t,e[1]/t,e[2]/t]}function chord(e,t){return Math.hypot(e[0]-t[0],e[1]-t[1],e[2]-t[2])}function antipode(e){return[-e[0],-e[1],-e[2]]}function shortWay(e){return e>180?-360:e<-180?360:0}function distinctVertices(e,t){let r=[];for(let[i,a]of e.entries()){let e=toVector(a.longitude,a.latitude);if(Math.hypot(e[0],e[1])<=v)return n(`A GeoPolygon ring cannot contain a pole`,[...t,i]);let o=r.at(-1);(!o||chord(o.vector,e)>v)&&r.push({vertex:a,index:i,vector:e})}let[i]=r,a=r.at(-1);return i&&a&&chord(a.vector,i.vector)>v&&r.push(i),s(r)}function ringArcs(e,t){let r=distinctVertices(e,t);if(r.issues)return r;let i=0;for(let[e,{vertex:t}]of r.value.entries()){let n=r.value[e-1];n&&(i+=shortWay(t.longitude-n.vertex.longitude))}let a=[],o=0,c,l;for(let{vertex:e,index:s,vector:u}of r.value){let r;if(c){let t=e.longitude-c.written;Math.abs(t)===180&&(r=[0,0,Math.sign(e.latitude+c.latitude)],Math.abs(t-i)===180&&(o-=i)),o+=shortWay(t)}let d={longitude:e.longitude+o,latitude:e.latitude,written:e.longitude,vector:u};if(c){if(chord(antipode(c.vector),u)<y)return n(`A GeoPolygon edge cannot join vertices within 0.01 degrees of antipodal`,[...t,s]);if(r&&l&&r[2]!==l[2])return n(`A GeoPolygon cannot contain a pole`,[...t]);l??=r,a.push({from:c,to:d,start:c.vector,end:u,normal:unit(cross(c.vector,u)),pole:r})}c=d}if(o!==0)return n(`A GeoPolygon cannot contain a pole`,[...t]);let[u,...d]=a;if(!u||d.length<3&&d.every(({start:e})=>Math.abs(side(u,e))<=v))return n(`A GeoPolygon ring must have non-zero area`,[...t]);let f=u;for(let e of[...d,u]){if(onArc(e.end,f)||onArc(f.start,e))return n(`A GeoPolygon ring cannot self-intersect`,[...t]);f=e}return s([u,...d])}function side(e,t){return dot(e.normal,t)}function onArc(e,t){return Math.abs(side(t,e))<=v&&dot(cross(t.start,e),t.normal)>=-v&&dot(cross(e,t.end),t.normal)>=-v}function opposite(e,t){return e>v&&t<-v||e<-v&&t>v}function crosses(e,t){if(!(opposite(side(e,t.start),side(e,t.end))&&opposite(side(t,e.start),side(t,e.end))))return!1;let n=cross(e.normal,t.normal);return dot(n,e.start)+dot(n,e.end)>0==dot(n,t.start)+dot(n,t.end)>0}function meet(e,t){return crosses(e,t)||onArc(e.start,t)||onArc(e.end,t)||onArc(t.start,e)||onArc(t.end,e)}function createLinks(e){return Array.from({length:e},()=>({previous:void 0,next:void 0}))}function below(e,t){let n=dot(t.north,e.west);return Math.abs(n)>v?n<0:dot(t.north,e.east)<0}function southOf(e,t,n){let r=e;for(let e=n;e>=0;--e){let n=r.links[e]?.next;for(;n?.stretch&&dot(n.stretch.north,t)>v;)r=n,n=r.links[e]?.next}return r}function enter(e,t,n){let r={stretch:t,links:createLinks(n)},i=e;for(let e=23;e>=0;--e){let n=i.links[e]?.next;for(;n?.stretch&&!below(t,n.stretch);)i=n,n=i.links[e]?.next;let a=r.links[e],o=i.links[e];if(a&&o){a.previous=i,a.next=o.next;let t=o.next?.links[e];t&&(t.previous=r),o.next=r}}return r}function leave(e){for(let[t,{previous:n,next:r}]of e.links.entries()){let e=n?.links[t];e&&(e.next=r);let i=r?.links[t];i&&(i.previous=n)}}const b=toVector(180,0);function atAntimeridian(e){let t=unit(cross(e.normal,[-b[1],b[0],0]));return dot(t,b)<0?antipode(t):t}function arcEvents(e){let{from:t,to:n,normal:r,pole:i}=e.arc,a=t.written===180?-180:t.written,o=n.written===180?-180:n.written;if(a===o){let[r,i]=t.latitude<n.latitude?[t,n]:[n,t];return[{longitude:a,rank:2,upright:{placed:e,south:r.vector,north:i.vector}}]}let s=t.longitude<n.longitude,[c,l]=s?[t,n]:[n,t],u=s?r:[-r[0],-r[1],-r[2]],[d,f]=s?[a,o]:[o,a];if(i)return polarEvents(e,i,u,s,d,f);let span=(t,n,r)=>{let i={stretch:{placed:e,west:r,east:l.vector,north:u,eastward:s},entry:void 0};return[{longitude:t,rank:1,slot:i},{longitude:n,rank:3,slot:i}]};return d<f?span(d,f,c.vector):[...span(d,180,c.vector),...span(-180,f,atAntimeridian(e.arc))]}function polarEvents(e,t,n,r,i,a){let o=[e.arc.from,e.arc.to].map(({written:n,vector:r})=>({longitude:n===180?-180:n,rank:2,upright:{placed:e,south:t[2]>0?r:t,north:t[2]>0?t:r}})),across=(i,a)=>{let o={stretch:{placed:e,west:t,east:t,north:n,eastward:r},entry:void 0};return[{longitude:i,rank:1,slot:o},{longitude:a,rank:0,slot:o}]};return i<a?[...o,...across(i,a)]:[...o,...across(i,180),...a>-180?across(-180,a):[]]}function latitude(e){return Math.atan2(e[2],Math.hypot(e[0],e[1]))}function sweep(e,t){let n=e.flatMap(arcEvents);n.sort((e,t)=>e.longitude-t.longitude||e.rank-t.rank);let r={stretch:void 0,links:createLinks(24)},meeting=(e,n)=>{if(e&&n&&!(t(e,n)||!meet(e.arc,n.arc)))return[e,n]},i=[],a=new Map,placeArrivals=()=>{let e=Array.from(a,([e,{entry:t,west:n}])=>{let r=t.links[0]?.next;for(;r?.stretch?.placed.ring===e;)r=r.links[0]?.next;return{ring:e,height:latitude(n),north:r?.stretch}});e.sort((e,t)=>t.height-e.height);for(let{ring:t,north:n}of e)i.push({ring:t,north:n});a.clear()},o=new Set;for(let[e,t]of n.entries())if(t.rank===1){let i=1+Math.floor(-Math.log2(1-Math.random())),s=enter(r,t.slot.stretch,Math.min(24,i));t.slot.entry=s;let[c]=s.links,l=meeting(c?.previous?.stretch?.placed,s.stretch?.placed)??meeting(s.stretch?.placed,c?.next?.stretch?.placed);if(l)return{meeting:l};let{placed:u,west:d}=t.slot.stretch,f=a.get(u.ring);(!o.has(u.ring)||f&&latitude(d)>latitude(f.west))&&(o.add(u.ring),a.set(u.ring,{entry:s,west:d}));let p=n[e+1];(p?.rank!==1||p.longitude!==t.longitude)&&placeArrivals()}else if(t.rank===2){let{upright:e}=t,n=southOf(r,e.south,23);for(n=n.stretch?n:n.links[0]?.next;n?.stretch;){let t=meeting(e.placed,n.stretch.placed);if(t)return{meeting:t};if(dot(n.stretch.north,e.north)<-v)break;n=n.links[0]?.next}}else if(t.slot.entry){let[e]=t.slot.entry.links;leave(t.slot.entry);let n=meeting(e?.previous?.stretch?.placed,e?.next?.stretch?.placed);if(n)return{meeting:n}}return{placements:i}}function signedArea(e){let t=0,n=0,r,i=0;for(let a of e){let e=cross(a.start,a.end)[2],o=1+dot(a.start,a.end),s=a.start[2]+a.end[2];s>=0?(t+=2*Math.atan2(e,o+s),r!==void 0&&(n+=a.from.longitude-r),r=void 0):(t+=2*Math.atan2(-e,o-s),r??=a.from.longitude),i=a.to.longitude}return r!==void 0&&(n+=i-r),t+2*n*_}function wound(e,t,n){return t===n?e:e.reverse()}function ringPath(e){return e===0?[`outer`]:[`holes`,e-1]}function ringNode(e,t,n){return{index:n,hole:n===0?1/0:n-1,points:e,arcs:t,counterClockwise:signedArea(t)>0,around:void 0,inside:!1,firstAround:1/0,firstWithin:1/0}}function validateGeoPolygon(e){let r=t(g,e);if(r.issues)return r;let i=ringArcs(r.value.outer,[`outer`]);if(i.issues)return i;let a=ringNode(r.value.outer,i.value,0),o=[];for(let[e,t]of(r.value.holes??[]).entries()){let n=ringArcs(t,[`holes`,e]);if(n.issues)return n;o.push(ringNode(t,n.value,e+1))}let c=sweep([a,...o].flatMap(e=>e.arcs.map((t,n)=>({arc:t,ring:e,index:n}))),(e,t)=>e.ring===t.ring&&[0,1,e.ring.arcs.length-1].includes(Math.abs(e.index-t.index)));if(c.meeting){let[e,t]=c.meeting,r=ringPath(Math.max(e.ring.index,t.ring.index));return e.ring===t.ring?n(`A GeoPolygon ring cannot self-intersect`,r):Math.min(e.ring.index,t.ring.index)===0?n(`A GeoPolygon hole must be strictly inside its outer ring`,r):n(`GeoPolygon holes cannot touch or overlap`,r)}for(let{ring:e,north:t}of c.placements){let n=t?.placed.ring,r=n===void 0||n.counterClockwise!==t?.eastward?n:n.around;e.around=r,e.inside=r!==void 0&&(r.index===0||r.inside),e.firstAround=r?Math.min(r.hole,r.firstAround):1/0}for(let{ring:e}of c.placements.reverse()){let{around:t}=e;t&&(t.firstWithin=Math.min(t.firstWithin,e.hole,e.firstWithin))}for(let{hole:e,inside:t,firstAround:r,firstWithin:i}of o){if(!t)return n(`A GeoPolygon hole must be strictly inside its outer ring`,[`holes`,e]);if(Math.min(r,i)<e)return n(`GeoPolygon holes cannot touch or overlap`,[`holes`,e])}let l=wound(a.points,a.counterClockwise,!0),u=o.map(({points:e,counterClockwise:t})=>wound(e,t,!1));return s(u.length>0?{outer:l,holes:u}:{outer:l})}const x=o({bounds:d(`object`,validateGeoBounds),polygon:d(`object`,validateGeoPolygon)});function validateGeoArea(e){let r=t(x,e);if(r.issues)return r;let{bounds:i,polygon:a}=r.value;return i&&!a?s({bounds:i}):a&&!i?s({polygon:a}):n(`Expected GeoArea with exactly one of bounds or polygon`)}function geoAreaSchema(){return d(`geo_area`,validateGeoArea)}export{geoAreaSchema as n,geoBoundsForDistance as r,m as t};
2
- //# sourceMappingURL=geo-area-codec-mHrM3b9A.mjs.map
@@ -1 +0,0 @@
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,MAAO,CACL,MAAO,EAAM,SACb,KAAM,EAAM,UACZ,MAAO,EAAM,SACb,KAAM,EAAM,UACb,CAGH,IAAM,EAAgB,EAAS,EAC/B,GAAI,GAAiB,KAAK,GACxB,MAAO,CAAE,MAAO,IAAK,KAAM,KAAM,MAAO,GAAI,KAAM,IAAK,CAGzD,IAAM,EAAmB,EAAM,SAAW,KAAK,GAAM,IAC/C,EAAiB,EAAgB,IAAO,KAAK,GAC7C,EAAQ,KAAK,IACjB,IACA,EAAM,SAAW,EAAgB,EAClC,CACK,EAAQ,KAAK,IACjB,GACA,EAAM,SAAW,EAAgB,EAClC,CACD,GAAI,IAAU,KAAO,IAAU,GAC7B,MAAO,CAAE,QAAO,KAAM,KAAM,QAAO,KAAM,IAAK,CAGhD,IAAM,EACH,KAAK,KACJ,KAAK,IAAI,EAAG,KAAK,IAAI,EAAc,CAAG,KAAK,IAAI,EAAgB,CAAC,CACjE,CACC,IACA,KAAK,GACP,EACF,MAAO,CACL,QACA,KAAM,mBAAmB,EAAM,UAAY,EAAe,CAC1D,QACA,KAAM,mBAAmB,EAAM,UAAY,EAAe,CAC3D,CAGH,SAAS,mBAAmB,EAA2B,CACrD,QAAW,EAAY,KAAO,IAAO,KAAO,IAAO,IAGrD,MAAM,EAAe,EACnB,EACG,EAAgB,IAAK,GACrB,EAAgB,IAAK,GACrB,EAAgB,IAAK,GACrB,EAAgB,IAAK,EACvB,CACD,CAAE,QAAS,GAAO,CACnB,CAED,SAAgB,kBAAkB,EAA6C,CAC7E,IAAM,EAAS,EAAe,EAAc,EAAM,CASlD,OARI,EAAO,OAAe,EAGtB,EAAO,MAAM,MAAQ,EAAO,MAAM,MAC7B,EAAK,sDAA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C,EAAe,EAAG,CAAE,UAAS,CAAC,CACvC,EAAK,yDAAyD,CAGvE,SAAgB,eAA6C,CAC3D,OAAO,EAAa,WAAY,gBAAgB"}
@@ -1,2 +0,0 @@
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 +0,0 @@
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,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 +0,0 @@
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 +0,0 @@
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,KAAM,CACJ,OAAQ,GACR,MAAO,IAAI,EAAI,MAAM,EAAI,MAAM,EAAI,MAAM,EAAI,MAAM,EAAI,OACvD,KAAM,GAAG,EAAI,OAAO,EAAE,CAAC,GAAG,EAAI,OAAO,EAAE,CAAC,GAAG,EAAI,OAAO,EAAE,CAAC,GAAG,EAAI,OAAO,EAAE,CAAC,GAAG,EAAI,OAAO,GAAG,GAC3F,KAAM,QACN,IAAK,IAAA,GACN,CACD,KAAM,CACJ,OAAQ,GACR,MAAO,SAAS,EAAU,OAC1B,KAAM,QAAQ,EAAU,OAAO,GAAG,GAClC,KAAM,QACN,IAAK,IAAA,GACN,CACD,MAAO,CACL,OAAQ,GACR,MAAO,IAAI,EAAO,OAClB,KAAM,EAAO,OAAO,GAAG,CACvB,KAAM,IAAA,GACN,IAAK,EACN,CACF,CAGD,SAAS,UAAU,EAAkB,CAGnC,OAFI,EAAO,SAAW,OAAe,EAAS,KAC1C,EAAO,SAAW,QAAgB,EAAS,MACxC,EAAS,KAIlB,MAAM,IAAO,GAAuBA,EAAI,IAAI,OAAO,EAAM,CAAC,CAG1D,SAAS,QACP,EACA,EACA,EACA,EACK,CACL,IAAM,EAAQ,EAAuB,IAAY,QAAU,IAAM,IAAI,CAC/D,EACJ,IAAY,cAAgB,EAAY,GAAG,EAAM,EAAU,CAAC,GAAK,GACnE,OAAOA,EAAI,IAAI,GAAG,EAAY,EAAM,EAAa,EAAM,CAAC,CAAC,MAA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f(e)===-1?t:t.replaceAll(e,e+e))+e,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-s00pGES8.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"identifiers-s00pGES8.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: '\"' | \"`\"): IdentifierQuoter =>\n (name: string): string => {\n const escaped =\n name.indexOf(quoteChar) === -1\n ? name\n : name.replaceAll(quoteChar, quoteChar + quoteChar);\n return quoteChar + escaped + quoteChar;\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,uBACV,GACA,GAKQ,GAHL,EAAK,QAAQ,EAAU,GAAK,GACxB,EACA,EAAK,WAAW,EAAW,EAAY,EAAU,EAC1B,EAQ3B,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"}
@@ -1,2 +0,0 @@
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";const r=2**32,words=e=>{let t=new DataView(new ArrayBuffer(e.length*4));for(let[n,r]of e.entries())t.setUint32(n*4,r);return t},i=words([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),a=new Uint8Array(words([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]).buffer),o=new Uint8Array(32),s=new DataView(o.buffer),c=new DataView(new ArrayBuffer(256)),rotate=(e,t)=>e>>>t|e<<32-t,fold=(e,t)=>{s.setInt32(e,s.getInt32(e)+t|0)};function compress(e,t){for(let n=0;n<16;n++)c.setInt32(n*4,e.getInt32(t+n*4));for(let e=16;e<64;e++){let t=c.getInt32((e-15)*4),n=c.getInt32((e-2)*4),r=rotate(t,7)^rotate(t,18)^t>>>3,i=rotate(n,17)^rotate(n,19)^n>>>10;c.setInt32(e*4,i+c.getInt32((e-7)*4)+r+c.getInt32((e-16)*4)|0)}let n=s.getInt32(0),r=s.getInt32(4),a=s.getInt32(8),o=s.getInt32(12),l=s.getInt32(16),u=s.getInt32(20),d=s.getInt32(24),f=s.getInt32(28);for(let e=0;e<64;e++){let t=rotate(l,6)^rotate(l,11)^rotate(l,25),s=l&u^~l&d,p=f+t+s+i.getInt32(e*4)+c.getInt32(e*4)|0,m=rotate(n,2)^rotate(n,13)^rotate(n,22),h=n&r^n&a^r&a;f=d,d=u,u=l,l=o+p|0,o=a,a=r,r=n,n=p+m+h|0}fold(0,n),fold(4,r),fold(8,a),fold(12,o),fold(16,l),fold(20,u),fold(24,d),fold(28,f)}function sha256(e){o.set(a);let t=e.length,n=new DataView(e.buffer,e.byteOffset,t),i=Math.floor(t/64);for(let e=0;e<i;e++)compress(n,e*64);let s=t-i*64,c=new Uint8Array(s>55?128:64);c.set(e.subarray(i*64)),c[s]=128;let l=new DataView(c.buffer),u=t*8;l.setUint32(c.length-8,Math.floor(u/r)),l.setUint32(c.length-4,u%r);for(let e=0;e<c.length;e+=64)compress(l,e);return Uint8Array.from(o)}const l=`sha256`,u={estate:`viborm.migration.estate.v1`,snapshot:`viborm.migration.snapshot.v1`,snapshotDelta:`viborm.migration.snapshot-delta.v1`,sql:`viborm.migration.sql.v1`,dispatch:`viborm.migration.dispatch.v1`,transition:`viborm.migration.transition.v1`,state:`viborm.migration.state.v1`,path:`viborm.migration.path.v1`,plan:`viborm.migration.plan.v1`,resetPlan:`viborm.migration.reset-plan.v1`,event:`viborm.migration.event.v1`,rawIndex:`viborm.migration.raw-index.v1`},d=/^[0-9a-f]{64}$/,f=new TextEncoder;function isSha256(e){return typeof e==`string`&&d.test(e)}function parseSha256(e,r){if(!isSha256(e))throw new n(`${r} is not a lowercase 64-hex SHA-256 digest`,t.MIGRATION_INVALID_ESTATE);return e}function sha256Hex(e){let t=``;for(let n of sha256(e))t+=n.toString(16).padStart(2,`0`);return t}function domainHash(e,t){let n=f.encode(e),r=new Uint8Array(n.length+1+t.length);return r.set(n,0),r[n.length]=0,r.set(t,n.length+1),sha256Hex(r)}function utf8Bytes(e){return f.encode(e)}function decodeUtf8(e){return new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0}).decode(e)}export{isSha256 as a,utf8Bytes as c,domainHash as i,u as n,parseSha256 as o,decodeUtf8 as r,sha256Hex as s,l as t};
2
- //# sourceMappingURL=identity-CtW15WlB.mjs.map