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
@@ -0,0 +1 @@
1
+ {"version":3,"file":"identifier-conversion-BTDxDwDB.mjs","names":[],"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 compact identifier domain (uuid/uuidv7/ulid/ksuid).`,\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 (prefixed IDs unsupported); convert manually or keep a text native type.`)}, 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":"mXAgGA,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,EAAU,EAAkB,CAGnC,OAFI,EAAO,SAAW,OAAe,EAAS,KAC1C,EAAO,SAAW,QAAgB,EAAS,MACxC,EAAS,KAIlB,MAAM,EAAO,GAAuB,EAAI,IAAI,OAAO,EAAM,CAAC,CAG1D,SAAS,EACP,EACA,EACA,EACA,EACK,CACL,IAAM,EAAQ,EAAuB,IAAY,QAAU,IAAM,IAAI,CAC/D,EACJ,IAAY,c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"}
@@ -0,0 +1,2 @@
1
+ const e=e=>{let t=new Map;return n=>{let r=t.get(n);if(r!==void 0)return r;let i=e+(n.indexOf(e)===-1?n:n.replaceAll(e,e+e))+e;return t.size<4096&&t.set(n,i),i}},t=(e,t)=>`${e(t)}.`,n=(e,n,r)=>n===void 0?e(r):t(e,n)+e(r),r=(e,n)=>{if(n===void 0)return e;let r=t(e,n);return t=>r+e(t)};export{r as n,n as r,e as t};
2
+ //# sourceMappingURL=identifiers-BxOf57qy.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"identifiers-BxOf57qy.mjs","names":[],"sources":["../src/sql/identifiers.ts"],"sourcesContent":["/**\n * Identifier text primitives.\n *\n * Quoting one name for a dialect, and composing a namespace-qualified object\n * name, are string concerns with no `Sql` involvement: runtime adapters wrap the\n * result in `Sql`, migration drivers splice it into DDL text. Both pass their\n * own quoter — the two differ in escape semantics and null handling — so what is\n * shared here is the composition rule alone, and it has one owner.\n */\n\n/** Quote a single identifier for the dialect: `\"name\"` or `` `name` ``. */\nexport type IdentifierQuoter = (name: string) => string;\n\n/** Build an identifier quoter that doubles embedded quote characters to prevent SQL injection. */\nexport const createIdentifierQuoter = (\n quoteChar: '\"' | \"`\"\n): IdentifierQuoter => {\n // The names a statement quotes are its schema's and its own aliases, the\n // same few on every call: each is quoted once. Bounded, so names a caller\n // invents cannot grow it without end.\n const quoted = new Map<string, string>();\n return (name: string): string => {\n const known = quoted.get(name);\n if (known !== undefined) return known;\n const text =\n quoteChar +\n (name.indexOf(quoteChar) === -1\n ? name\n : name.replaceAll(quoteChar, quoteChar + quoteChar)) +\n quoteChar;\n if (quoted.size < 4096) quoted.set(name, text);\n return text;\n };\n};\n\n/**\n * The one qualification rule. A present namespace contributes a quoted prefix;\n * an absent one contributes nothing, which is what unbound MySQL and every\n * SQLite adapter mean.\n */\nconst qualifiedPrefix = (\n quoteIdentifier: IdentifierQuoter,\n namespace: string\n): string => `${quoteIdentifier(namespace)}.`;\n\n/**\n * Compose one namespace-qualified object name. The namespace must already be\n * normalized: this primitive validates nothing, holds nothing, and returns text\n * for exactly one object.\n */\nexport const renderQualifiedIdentifier = (\n quoteIdentifier: IdentifierQuoter,\n namespace: string | undefined,\n object: string\n): string =>\n namespace === undefined\n ? quoteIdentifier(object)\n : qualifiedPrefix(quoteIdentifier, namespace) + quoteIdentifier(object);\n\n/**\n * Bind one namespace so its prefix is quoted once per adapter rather than once\n * per rendered statement. The returned function renders exactly what\n * `renderQualifiedIdentifier` would for the same namespace.\n */\nexport const createQualifiedIdentifierRenderer = (\n quoteIdentifier: IdentifierQuoter,\n namespace: string | undefined\n): IdentifierQuoter => {\n if (namespace === undefined) {\n return quoteIdentifier;\n }\n const prefix = qualifiedPrefix(quoteIdentifier, namespace);\n return (object: string): string => prefix + quoteIdentifier(object);\n};\n"],"mappings":"AAcA,MAAa,EACX,GACqB,CAIrB,IAAM,EAAS,IAAI,IACnB,MAAQ,IAAyB,CAC/B,IAAM,EAAQ,EAAO,IAAI,EAAK,CAC9B,GAAI,IAAU,IAAA,GAAW,OAAO,EAChC,IAAM,EACJ,GACC,EAAK,QAAQ,EAAU,GAAK,GACzB,EACA,EAAK,WAAW,EAAW,EAAY,EAAU,EACrD,EAEF,OADI,EAAO,KAAO,MAAM,EAAO,IAAI,EAAM,EAAK,CACvC,IASL,GACJ,EACA,IACW,GAAG,EAAgB,EAAU,CAAC,GAO9B,GACX,EACA,EACA,IAEA,IAAc,IAAA,GACV,EAAgB,EAAO,CACvB,EAAgB,EAAiB,EAAU,CAAG,EAAgB,EAAO,CAO9D,GACX,EACA,IACqB,CACrB,GAAI,IAAc,IAAA,GAChB,OAAO,EAET,IAAM,EAAS,EAAgB,EAAiB,EAAU,CAC1D,MAAQ,IAA2B,EAAS,EAAgB,EAAO"}
@@ -0,0 +1,2 @@
1
+ import{t as e}from"./migrations-DIUltjr3.mjs";const t=2**32,n=new Int32Array(64),r=new Int32Array(8);for(let e=2,i=0;i<64;e++){let a=!0;for(let t=2;t*t<=e;t++)if(e%t===0){a=!1;break}a&&(i<8&&(r[i]=Math.floor(Math.sqrt(e)%1*t)|0),n[i]=Math.floor(Math.cbrt(e)%1*t)|0,i++)}const i=new Int32Array(8),a=new Int32Array(64),o=new Uint8Array(128),s=new DataView(o.buffer),c=(e,t)=>e>>>t|e<<32-t;function l(e,t){for(let n=0;n<16;n++)a[n]=e.getInt32(t+n*4);for(let e=16;e<64;e++){let t=a[e-15],n=a[e-2],r=c(t,7)^c(t,18)^t>>>3;a[e]=(c(n,17)^c(n,19)^n>>>10)+a[e-7]+r+a[e-16]|0}let r=i[0],o=i[1],s=i[2],l=i[3],u=i[4],d=i[5],f=i[6],p=i[7];for(let e=0;e<64;e++){let t=c(u,6)^c(u,11)^c(u,25),i=u&d^~u&f,m=p+t+i+n[e]+a[e]|0,h=c(r,2)^c(r,13)^c(r,22),g=r&o^r&s^o&s;p=f,f=d,d=u,u=l+m|0,l=s,s=o,o=r,r=m+h+g|0}i[0]=i[0]+r|0,i[1]=i[1]+o|0,i[2]=i[2]+s|0,i[3]=i[3]+l|0,i[4]=i[4]+u|0,i[5]=i[5]+d|0,i[6]=i[6]+f|0,i[7]=i[7]+p|0}function u(e){i.set(r);let n=e.length,a=new DataView(e.buffer,e.byteOffset,n),c=Math.floor(n/64);for(let e=0;e<c;e++)l(a,e*64);let u=n-c*64,d=u>55?128:64;o.fill(0,0,d),o.set(e.subarray(c*64),0),o[u]=128;let f=n*8;s.setUint32(d-8,Math.floor(f/t)),s.setUint32(d-4,f%t);for(let e=0;e<d;e+=64)l(s,e);let p=new Uint8Array(32),m=new DataView(p.buffer);for(let e=0;e<8;e++)m.setInt32(e*4,i[e]);return p}const d=`sha256`,f={vu:`viborm.migration.estate.v1`,snapshot:`viborm.migration.snapshot.v1`,wy:`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`,view:`viborm.migration.view.v1`},p=/^[0-9a-f]{64}$/,m=new TextEncoder;function h(e){return typeof e==`string`&&p.test(e)}function g(t,n){if(!h(t))throw new e(`${n} is not a lowercase 64-hex SHA-256 digest`,`V11012`);return t}function _(e){let t=``;for(let n of u(e))t+=n.toString(16).padStart(2,`0`);return t}function v(e,t){let n=m.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),_(r)}function y(e){return m.encode(e)}function b(e){return new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0}).decode(e)}export{h as a,y as c,v as i,f as n,g as o,b as r,_ as s,d as t};
2
+ //# sourceMappingURL=identity-CJlRQA-m.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"identity-CJlRQA-m.mjs","names":[],"sources":["../src/validation/primitives/sha256.ts","../src/migrations/identity.ts"],"sourcesContent":["// biome-ignore-all lint/suspicious/noBitwiseOperators: SHA-256 is 32-bit word\n// arithmetic. Every operator below is part of FIPS 180-4's definition.\n\n/**\n * SHA-256, the hash Migration V1 identity is defined over.\n *\n * FIPS 180-4: 64-byte blocks, a 64-word message schedule, 64 rounds, a 64-bit\n * big-endian bit length after the `0x80` pad. One exported function, no\n * streaming, no options: the caller hands over the complete message and\n * receives the 32-byte digest.\n *\n * It is synchronous on purpose. WebCrypto's `digest` is the platform hash on\n * every runtime, but it returns a promise, and every content-addressed parser\n * in the migration engine hashes inline; `node:crypto` is synchronous but is\n * not on an edge runtime without a compatibility flag.\n *\n * Every word is read and written through a `DataView` that names big-endian,\n * the byte order the standard is written in, so the host's byte order never\n * enters a digest; it is also the one indexed read in this codebase that is not\n * `T | undefined`, as in the SHA3-512 precedent (`./sha3`).\n *\n * The one caller is `migrations/identity`. Nothing else in VibORM may import\n * this module without its own differential proof against a reference.\n */\n\nconst BLOCK_BYTES = 64;\nconst DIGEST_BYTES = 32;\nconst ROUNDS = 64;\n/** A tail of more than this many bytes leaves no room for the pad and length. */\nconst LAST_BLOCK_ROOM = BLOCK_BYTES - 9;\nconst WORD_SPAN = 2 ** 32;\n\n/** First 32 bits of fractional cube/square roots of the first 64 / 8 primes. */\nconst ROUND_CONSTANTS = new Int32Array(ROUNDS);\nconst INITIAL_HASH = new Int32Array(8);\nfor (let n = 2, count = 0; count < ROUNDS; n++) {\n let prime = true;\n for (let d = 2; d * d <= n; d++) {\n if (n % d === 0) {\n prime = false;\n break;\n }\n }\n if (!prime) continue;\n if (count < 8) {\n INITIAL_HASH[count] = Math.floor((Math.sqrt(n) % 1) * WORD_SPAN) | 0;\n }\n ROUND_CONSTANTS[count] = Math.floor((Math.cbrt(n) % 1) * WORD_SPAN) | 0;\n count++;\n}\n\n/**\n * The running hash, message schedule, and tail padding buffer, allocated once:\n * `sha256` is synchronous from entry to return, and every entry resets the hash.\n */\nconst hash = new Int32Array(8);\nconst schedule = new Int32Array(ROUNDS);\nconst tail = new Uint8Array(2 * BLOCK_BYTES);\nconst tailView = new DataView(tail.buffer);\n\nconst rotate = (word: number, bits: number): number =>\n (word >>> bits) | (word << (32 - bits));\n\n/** The compression function over the 64 bytes of `block` at `offset`. */\nfunction compress(block: DataView, offset: number): void {\n for (let t = 0; t < 16; t++) {\n schedule[t] = block.getInt32(offset + t * 4);\n }\n for (let t = 16; t < ROUNDS; t++) {\n const early = schedule[t - 15]!;\n const late = schedule[t - 2]!;\n const sigma0 = rotate(early, 7) ^ rotate(early, 18) ^ (early >>> 3);\n const sigma1 = rotate(late, 17) ^ rotate(late, 19) ^ (late >>> 10);\n schedule[t] = (sigma1 + schedule[t - 7]! + sigma0 + schedule[t - 16]!) | 0;\n }\n\n let a = hash[0]!;\n let b = hash[1]!;\n let c = hash[2]!;\n let d = hash[3]!;\n let e = hash[4]!;\n let f = hash[5]!;\n let g = hash[6]!;\n let h = hash[7]!;\n for (let t = 0; t < ROUNDS; t++) {\n const sum1 = rotate(e, 6) ^ rotate(e, 11) ^ rotate(e, 25);\n const choose = (e & f) ^ (~e & g);\n const first = (h + sum1 + choose + ROUND_CONSTANTS[t]! + schedule[t]!) | 0;\n const sum0 = rotate(a, 2) ^ rotate(a, 13) ^ rotate(a, 22);\n const majority = (a & b) ^ (a & c) ^ (b & c);\n h = g;\n g = f;\n f = e;\n e = (d + first) | 0;\n d = c;\n c = b;\n b = a;\n a = (first + sum0 + majority) | 0;\n }\n hash[0] = (hash[0]! + a) | 0;\n hash[1] = (hash[1]! + b) | 0;\n hash[2] = (hash[2]! + c) | 0;\n hash[3] = (hash[3]! + d) | 0;\n hash[4] = (hash[4]! + e) | 0;\n hash[5] = (hash[5]! + f) | 0;\n hash[6] = (hash[6]! + g) | 0;\n hash[7] = (hash[7]! + h) | 0;\n}\n\n/**\n * The SHA-256 digest of one complete message.\n *\n * Byte-identical to `node:crypto` for every input, which a differential test\n * pins against the FIPS 180-4 known-answer vectors and 10,000 random messages\n * crossing every block and padding boundary.\n */\nexport function sha256(bytes: Uint8Array): Uint8Array {\n hash.set(INITIAL_HASH);\n\n const length = bytes.length;\n const message = new DataView(bytes.buffer, bytes.byteOffset, length);\n const wholeBlocks = Math.floor(length / BLOCK_BYTES);\n for (let block = 0; block < wholeBlocks; block++) {\n compress(message, block * BLOCK_BYTES);\n }\n\n // The tail, `0x80`, zeros, then the bit length as a 64-bit big-endian word:\n // one block, or two when the tail leaves fewer than nine bytes free.\n const tailLength = length - wholeBlocks * BLOCK_BYTES;\n const paddedLength =\n tailLength > LAST_BLOCK_ROOM ? 2 * BLOCK_BYTES : BLOCK_BYTES;\n tail.fill(0, 0, paddedLength);\n tail.set(bytes.subarray(wholeBlocks * BLOCK_BYTES), 0);\n tail[tailLength] = 0x80;\n const bits = length * 8;\n tailView.setUint32(paddedLength - 8, Math.floor(bits / WORD_SPAN));\n tailView.setUint32(paddedLength - 4, bits % WORD_SPAN);\n for (let at = 0; at < paddedLength; at += BLOCK_BYTES) {\n compress(tailView, at);\n }\n\n const out = new Uint8Array(DIGEST_BYTES);\n const outView = new DataView(out.buffer);\n for (let i = 0; i < 8; i++) outView.setInt32(i * 4, hash[i]!);\n return out;\n}\n","/**\n * Content-addressed identity for Migration V1.\n *\n * One hash owner: SHA-256 over a frozen ASCII domain label, 0x00, then the\n * exact bytes being authenticated. Filenames and stored hex digests are the\n * lowercase 64-hex form of that digest. There is no self-referential checksum\n * header and no second hasher.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { sha256 } from \"../validation/primitives/sha256\";\n\nexport type Sha256 = string;\n\nexport const HASH_ALGORITHM = \"sha256\";\n\nexport const HASH_DOMAIN = {\n estate: \"viborm.migration.estate.v1\",\n snapshot: \"viborm.migration.snapshot.v1\",\n snapshotDelta: \"viborm.migration.snapshot-delta.v1\",\n sql: \"viborm.migration.sql.v1\",\n dispatch: \"viborm.migration.dispatch.v1\",\n transition: \"viborm.migration.transition.v1\",\n state: \"viborm.migration.state.v1\",\n path: \"viborm.migration.path.v1\",\n plan: \"viborm.migration.plan.v1\",\n resetPlan: \"viborm.migration.reset-plan.v1\",\n event: \"viborm.migration.event.v1\",\n rawIndex: \"viborm.migration.raw-index.v1\",\n view: \"viborm.migration.view.v1\",\n} as const;\n\nexport type HashDomain = (typeof HASH_DOMAIN)[keyof typeof HASH_DOMAIN];\n\nconst HEX64 = /^[0-9a-f]{64}$/;\nconst UTF8 = new TextEncoder();\n\nexport function isSha256(value: unknown): value is Sha256 {\n return typeof value === \"string\" && HEX64.test(value);\n}\n\nexport function parseSha256(value: unknown, label: string): Sha256 {\n if (!isSha256(value)) {\n throw new MigrationError(\n `${label} is not a lowercase 64-hex SHA-256 digest`,\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n return value;\n}\n\nexport function sha256Hex(bytes: Uint8Array): Sha256 {\n let hex = \"\";\n for (const byte of sha256(bytes)) hex += byte.toString(16).padStart(2, \"0\");\n return hex;\n}\n\nexport function domainHash(domain: HashDomain, bytes: Uint8Array): Sha256 {\n const prefix = UTF8.encode(domain);\n const input = new Uint8Array(prefix.length + 1 + bytes.length);\n input.set(prefix, 0);\n input[prefix.length] = 0;\n input.set(bytes, prefix.length + 1);\n return sha256Hex(input);\n}\n\nexport function utf8Bytes(text: string): Uint8Array {\n return UTF8.encode(text);\n}\n\n/**\n * Exactly the characters the bytes encode — a leading U+FEFF among them.\n *\n * These bytes are a VALUE (a catalog default, a blob's text), not a document\n * with a byte-order mark: the decoder's default of swallowing a leading U+FEFF\n * would report a value its source does not hold. A caller that refuses a BOM\n * refuses it as a byte, before this (`validateSqlRanges`).\n */\nexport function decodeUtf8(bytes: Uint8Array): string {\n return new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true }).decode(\n bytes\n );\n}\n"],"mappings":"8CAyBA,MAKM,EAAY,GAAK,GAGjB,EAAkB,IAAI,WAAW,GAAO,CACxC,EAAe,IAAI,WAAW,EAAE,CACtC,IAAK,IAAI,EAAI,EAAG,EAAQ,EAAG,EAAQ,GAAQ,IAAK,CAC9C,IAAI,EAAQ,GACZ,IAAK,IAAI,EAAI,EAAG,EAAI,GAAK,EAAG,IAC1B,GAAI,EAAI,IAAM,EAAG,CACf,EAAQ,GACR,MAGC,IACD,EAAQ,IACV,EAAa,GAAS,KAAK,MAAO,KAAK,KAAK,EAAE,CAAG,EAAK,EAAU,CAAG,GAErE,EAAgB,GAAS,KAAK,MAAO,KAAK,KAAK,EAAE,CAAG,EAAK,EAAU,CAAG,EACtE,KAOF,MAAM,EAAO,IAAI,WAAW,EAAE,CACxB,EAAW,IAAI,WAAW,GAAO,CACjC,EAAO,IAAI,WAAW,IAAgB,CACtC,EAAW,IAAI,SAAS,EAAK,OAAO,CAEpC,GAAU,EAAc,IAC3B,IAAS,EAAS,GAAS,GAAK,EAGnC,SAAS,EAAS,EAAiB,EAAsB,CACvD,IAAK,IAAI,EAAI,EAAG,EAAI,GAAI,IACtB,EAAS,GAAK,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B,EAAU,EAA2B,CACnD,IAAI,EAAM,GACV,IAAK,IAAM,KAAQ,EAAO,EAAM,CAAE,GAAO,EAAK,SAAS,GAAG,CAAC,SAAS,EAAG,IAAI,CAC3E,OAAO,EAGT,SAAgB,EAAW,EAAoB,EAA2B,CACxE,IAAM,EAAS,EAAK,OAAO,EAAO,CAC5B,EAAQ,IAAI,WAAW,EAAO,OAAS,EAAI,EAAM,OAAO,CAI9D,OAHA,EAAM,IAAI,EAAQ,EAAE,CACpB,EAAM,EAAO,QAAU,EACvB,EAAM,IAAI,EAAO,EAAO,OAAS,EAAE,CAC5B,EAAU,EAAM,CAGzB,SAAgB,EAAU,EAA0B,CAClD,OAAO,EAAK,OAAO,EAAK,CAW1B,SAAgB,EAAW,EAA2B,CACpD,OAAO,IAAI,YAAY,QAAS,CAAE,MAAO,GAAM,UAAW,GAAM,CAAC,CAAC,OAChE,EACD"}
package/dist/index.d.mts CHANGED
@@ -1,3 +1,3 @@
1
- import { $ as DelegateOperationPayload, $a as QueryEngineError, $n as row, $t as VectorScalar, A as Extension, Ai as PointSchema, An as rule, Ar as WriteOutcome, At as UpdateState$1, B as StampedFields, Ba as ValidationError, Bi as InitialModelState, Bn as modelMethods, Br as SchemaValidationError, C as ArgTest, Ci as BlobScalar, Cn as run, Co as VibORMError, Cr as renderSchemaType, Ct as BigIntScalar, D as ConfiguredBy, Da as ReferentialAction, Di as VectorSchema, Dn as text, Do as toPrismaErrorCode, Dr as UnwrapPendingOperation, Dt as InitialScalarState, E as CallResult, En as table, Eo as isVibORMError, Er as PendingOperation, Et as GeneratorDefaultBrand, F as Part, Fi as isFieldRef, Fn as selecting, Fo as GeoPoint, G as UnitOutcome, Ga as ClientInitializationError, Gn as keep, H as TargetOf, Ha as isValidationError, Hi as ModelInternal, Hn as check, Hr as SchemaValidationIssue, I as Parts, Ii as AnyModel, In as target, Io as GeoPolygon, Ir as InsertValueContext, J as AddedProjectedState, Ja as ForbiddenError, Ji as NumberSchema, Jn as arg, K as Watcher, Ka as ConnectionError, Kn as lazy, L as PlacedArgument, Li as IndexDefinition, Ln as writes, Lo as DecimalDescriptor, Lr as ModelSql, M as NoArguments, Mi as FieldRef, Mn as deletes, Mr as around, N as OperationSet, Ni as ModelFieldRefs, Nn as models, No as GeoArea, Nr as call, O as EmptyFacts, Oa as RelationCardinality, Oi as StringSchema, On as unit, Oo as wrapError, Or as UnwrapPendingOperations, Ot as ScalarState, P as Outcome, Pi as createModelFieldRefs, Pn as reads, Po as GeoBounds, Q as DelegateOperationArgs, Qa as PendingOperationError, Qi as JsonValue, Qn as provided, Qt as NumericScalar, R as Run, Ri as IndexOptions, Rn as work, Ro as Decimal, Rr as validateSchema, S as AnyTarget, Si as BooleanScalar, Sn as parameters, So as PrismaErrorCode, Sr as renderOperationResultType, St as Scalar, T as CallContext, Ta as Getter, Tn as statements, To as isRetryableError, Tr as ProjectedModelOperations, U as UnitContext, Ua as InvalidTransactionInputError, Ui as ModelState, Un as facts, Ur as Severity, V as Target, Va as ValidationErrorSource, Vi as Model, Vn as key, Vr as isSchemaValidationError, Vt as VibSchema, W as UnitKind, Wa as TransactionError, Wi as UpdateState, Wn as gate, Wr as ValidationResult, X as ClientTypeState, Xa as NestedWriteError, Xi as InputJsonValue, Xn as nothing, Ya as NestedWriteAssertionError, Yn as exists, Z as DelegateConfig, Za as NotFoundError, Zi as JsonSchema, Zn as now, _a as DbNull, _i as ReferencesStage, _n as driver, _o as isValueTooLongError, _r as accepts, _t as RowsFragment, aa as ObjectSchema, an as EnumScalar, ao as isUnsupportedOperationError, ar as DisclosurePolicy, at as TransactionClient, b as AnyCallContext, ba as JsonNullSentinel, bi as DateTimeScalar, bn as notes, bo as CacheInvalidTTLError, br as oneOf, bt as VariantToManyRelation, ca as DecimalSchema, cn as getSchemas, co as CheckConstraintError, cr as omitted, ct as VibORMConfig, di as FlatSchema, dn as JoinedSource, do as UniqueConstraintError, dr as within, dt as ChainedExtensionState, en as StringScalar, eo as QueryError, er as unless, et as DelegateOperationResult, fa as BlobSchema, fi as Linked, fn as computed, fo as ValueTooLongError, fr as Codec, ft as ClientExtensionState, ga as AnyNull, gi as ModelToOneRelation, gn as correlation, go as isUniqueConstraintError, gr as watch, gt as RawOperation, ha as AnyJsonNullSentinel, hi as RelationLinks, hn as BatchMember, ho as isNotNullConstraintError, hr as via, ht as ExtensionStateConstraint, ia as IsoTimestampSchema, in as IntScalar, io as isPendingOperationError, ir as disclosed, j as Facts, ji as AnyFieldRef, jn as parts, jr as WriteKind, k as Exact, ka as RelationSlot, kn as settled, ko as DiagnosticDisclosure, kr as isPendingOperation, ln as getRowKey, lo as ForeignKeyError, lr as Database, lt as createClient, ma as BigIntSchema, mi as Links, mn as stored, mo as isForeignKeyError, mr as again, mt as ExtensionResultConsumerState, na as IsoDateSchema, ni as Schema, nn as NumberScalar, no as isClientInitializationError, nr as fields, nt as ExtendedClient, oi as ClientHiddenContext, on as DecimalScalar, oo as MigrationError, or as disclosure, ot as TransactionClientOf, pi as LinkedClientConfig, pn as joined, po as isCheckConstraintError, pr as codec, pt as EmptyClientExtensionState, q as With, qa as FeatureNotSupportedError, qi as IntegerSchema, qn as only, ra as IsoTimeSchema, rn as JsonScalar, ro as isNotFoundError, rr as extension, rt as ExtendedOperationResult, sa as EnumSchema, sn as s, so as isMigrationError, sr as defaults, st as VibORMClient, tn as PointScalar, to as UnsupportedOperationError, tr as when, ua as BooleanSchema, ui as ClientSchema, un as VIBORM_VERSION, uo as NotNullConstraintError, ur as database, ut as AddedExtensionState, va as JsonNull, vi as ModelToManyRelation, vn as failure, vo as CacheConfigurationError, vr as args, vt as ModelShape, w as BoundAccepted, wa as AnyRelation, wn as statement, wo as VibORMErrorCode, wr as validateOperationPayload, wt as AutoGenerate, x as AnyFacts, xa as isJsonNullSentinel, xi as DateScalar, xn as origin, xo as CacheOperationNotCacheableError, xr as getOperationPayloadSchema, xt as VariantToOneRelation, y as Accepted, ya as JsonNullKind, yi as TimeScalar, yn as note, yo as CacheInvalidKeyError, yr as bound, yt as ScalarKeys, z as Selection, zn as methods, zr as validateSchemaOrThrow } from "./database-adapter-BGqvjeEy.mjs";
2
- import { a as isSql, c as sqlTag, i as empty, n as Sql, o as join, r as Value, s as raw, t as RawValue } from "./sql-BVZ8QefY.mjs";
3
- export { Accepted, type AddedExtensionState, type AddedProjectedState, AnyCallContext, AnyFacts, type AnyFieldRef, type AnyJsonNullSentinel, type AnyModel, AnyNull, type AnyRelation, AnyTarget, ArgTest, type AutoGenerate, BatchMember, type BigIntScalar, type BigIntSchema, type BlobScalar, type BlobSchema, type BooleanScalar, type BooleanSchema, BoundAccepted, CacheConfigurationError, CacheInvalidKeyError, CacheInvalidTTLError, CacheOperationNotCacheableError, CallContext, CallResult, type ChainedExtensionState, CheckConstraintError, type ClientExtensionState, type ClientHiddenContext, ClientInitializationError, type ClientSchema, type ClientTypeState, Codec, type InsertValueContext as ComputedContext, ConfiguredBy, ConnectionError, Database, type DateScalar, type DateTimeScalar, DbNull, Decimal, type DecimalDescriptor, type DecimalScalar, type DecimalSchema, type DelegateConfig, type DelegateOperationArgs, type DelegateOperationPayload, type DelegateOperationResult, type DiagnosticDisclosure, DisclosurePolicy, type EmptyClientExtensionState, EmptyFacts, type EnumScalar, type EnumSchema, Exact, type ExtendedClient, type ExtendedOperationResult, Extension, type ExtensionResultConsumerState, type ExtensionStateConstraint as ExtensionState, Facts, FeatureNotSupportedError, type FieldRef, type FlatSchema, ForbiddenError, ForeignKeyError, type GeneratorDefaultBrand, type GeoArea, type GeoBounds, type GeoPoint, type GeoPolygon, type Getter, type IndexDefinition, type IndexOptions, type InitialModelState, type InitialScalarState, type InputJsonValue, type IntScalar, type IntegerSchema, InvalidTransactionInputError, type IsoDateSchema, type IsoTimeSchema, type IsoTimestampSchema, type JoinedSource, JsonNull, type JsonNullKind, JsonNullSentinel, type JsonScalar, type JsonValue, type JsonSchema as JsonValueSchema, type Linked, type LinkedClientConfig, type Links, MigrationError, type Model, type ModelFieldRefs, type ModelInternal, type ModelShape, type ModelSql, type ModelState, type ModelToManyRelation, type ModelToOneRelation, type UpdateState as ModelUpdateState, NestedWriteAssertionError, NestedWriteError, type NoArguments, NotFoundError, NotNullConstraintError, type NumberScalar, type NumberSchema, type NumericScalar, type ObjectSchema, OperationSet, Outcome, Part, Parts, PendingOperation, PendingOperationError, type PlacedArgument, type PointScalar, type PointSchema, type PrismaErrorCode, type ProjectedModelOperations, QueryEngineError, QueryError, type RawOperation, type RawValue, type ReferencesStage, type ReferentialAction, type RelationCardinality, type RelationLinks, type RelationSlot, type RowsFragment, Run, type Scalar, type ScalarKeys, type ScalarState, type UpdateState$1 as ScalarUpdateState, type Schema, SchemaValidationError, type SchemaValidationIssue, Selection, type Severity, Sql, type StampedFields, type StringScalar, type StringSchema, Target, TargetOf, type TimeScalar, type TransactionClient, type TransactionClientOf, TransactionError, UniqueConstraintError, UnitContext, UnitKind, UnitOutcome, UnsupportedOperationError, type UnwrapPendingOperation, type UnwrapPendingOperations, VIBORM_VERSION, ValidationError, type ValidationErrorSource, type ValidationResult, type Value, ValueTooLongError, type VariantToManyRelation, type VariantToOneRelation, type VectorScalar, type VectorSchema, type VibORMClient, type VibORMConfig, VibORMError, VibORMErrorCode, type VibSchema, Watcher, With, WriteKind, WriteOutcome, accepts, again, arg, args, around, bound, call, check, codec, computed, correlation, createClient, createModelFieldRefs, database, defaults, deletes, disclosed, disclosure, driver, empty, exists, extension, facts, failure, fields, gate, getOperationPayloadSchema, getRowKey, getSchemas, isCheckConstraintError, isClientInitializationError, isFieldRef, isForeignKeyError, isJsonNullSentinel, isMigrationError, isNotFoundError, isNotNullConstraintError, isPendingOperation, isPendingOperationError, isRetryableError, isSchemaValidationError, isSql, isUniqueConstraintError, isUnsupportedOperationError, isValidationError, isValueTooLongError, isVibORMError, join, joined, keep, key, lazy, methods, modelMethods, models, note, notes, nothing, now, omitted, oneOf, only, origin, parameters, parts, provided, raw, reads, renderOperationResultType, renderSchemaType, row, rule, run, s, selecting, settled, sqlTag as sql, statement, statements, stored, table, target, text, toPrismaErrorCode, unit, unless, validateOperationPayload, validateSchema, validateSchemaOrThrow, via, watch, when, within, work, wrapError, writes };
1
+ import { $ as With, $i as UpdateState, $n as extension, A as BoundAccepted, Aa as AnyJsonNullSentinel, Ai as ModelToOneRelation, An as reads, Ao as CacheConfigurationError, At as AutoGenerate, B as Outcome, Ba as Getter, Bi as AnyFieldRef, Bn as gate, Bo as wrapError, Ca as Decimal, Ci as BlobScalar, Cn as text, Co as UniqueConstraintError, Cr as UnwrapPendingOperation, Ct as RowsFragment, D as AnyFacts, Da as BlobSchema, Di as LinkedClientConfig, Dn as parts, Do as isNotNullConstraintError, Dr as WriteKind, Dt as VariantToOneRelation, E as AnyCallContext, Ei as Linked, En as rule, Eo as isForeignKeyError, Er as WriteOutcome, Et as VariantToManyRelation, F as Exact, Fa as JsonNullSentinel, Fn as methods, Fo as VibORMError, G as Selection, Gi as AnyModel, Gn as exists, Gr as Schema, H as Parts, Ha as ReferentialAction, Hi as ModelFieldRefs, Hn as lazy, I as Extension, Ia as isJsonNullSentinel, Ii as VectorSchema, In as modelMethods, Io as VibORMErrorCode, It as UpdateState$1, J as TargetOf, Jn as provided, K as StampedFields, Ki as IndexDefinition, Kn as nothing, L as Facts, Li as StringSchema, Ln as key, Lo as isRetryableError, M as CallResult, Ma as DbNull, Mi as ModelToManyRelation, Mn as target, Mo as CacheInvalidTTLError, Mr as InsertValueContext, Mt as GeneratorDefaultBrand, N as ConfiguredBy, Na as JsonNull, Nn as writes, No as CacheOperationNotCacheableError, Nr as ModelSql, Nt as InitialScalarState, O as AnyTarget, Oi as Links, On as deletes, Oo as isUniqueConstraintError, Or as around, Ot as Scalar, P as EmptyFacts, Pa as JsonNullKind, Pn as work, Po as PrismaErrorCode, Pt as ScalarState, Q as Watcher, Qi as ModelState, Qn as fields, R as NoArguments, Rn as check, Ro as isVibORMError, Sa as DecimalDescriptor, Si as BooleanScalar, Sn as table, So as NotNullConstraintError, Sr as PendingOperation, St as RawOperation, T as Accepted, Ta as BooleanSchema, Ti as FlatSchema, Tn as settled, To as isCheckConstraintError, Tr as isPendingOperation, Tt as ScalarKeys, U as PlacedArgument, Ua as RelationCardinality, Ui as createModelFieldRefs, Un as only, V as Part, Vi as FieldRef, Vn as keep, Vo as DiagnosticDisclosure, W as Run, Wa as RelationSlot, Wi as isFieldRef, Wn as arg, X as UnitKind, Xi as Model, Xn as unless, Y as UnitContext, Yi as InitialModelState, Yn as row, Yr as ClientHiddenContext, Z as UnitOutcome, Zi as ModelInternal, Zn as when, _a as GeoPolygon, _i as NumberScalar, _n as origin, _o as isUnsupportedOperationError, _r as getOperationPayloadSchema, _t as ChainedExtensionState, aa as InputJsonValue, ai as DecimalScalar, an as getRowKey, ao as FeatureNotSupportedError, ar as Database, at as DelegateOperationPayload, ba as EnumSchema, bi as DateTimeScalar, bn as statement, bo as CheckConstraintError, br as validateOperationPayload, bt as ExtensionResultConsumerState, ci as validateSchemaOrThrow, cn as computed, co as NestedWriteError, cr as Codec, ct as ExtendedClient, d as ValidationErrorSource, da as IsoDateSchema, di as SchemaValidationIssue, dn as BatchMember, do as QueryEngineError, dr as via, dt as TransactionClient, ei as NumericScalar, er as disclosed, et as AddedProjectedState, f as isValidationError, fa as IsoTimeSchema, fi as Severity, fn as correlation, fo as QueryError, fr as watch, ft as TransactionClientOf, ga as GeoPoint, gi as StringScalar, gn as notes, go as isPendingOperationError, gr as oneOf, gt as AddedExtensionState, ha as GeoBounds, hi as ViewState, hn as note, ho as isNotFoundError, hr as bound, ht as createClient, ii as EnumScalar, in as getSchemas, io as ConnectionError, ir as omitted, it as DelegateOperationArgs, j as CallContext, ja as AnyNull, ji as ReferencesStage, jn as selecting, jo as CacheInvalidKeyError, k as ArgTest, ka as BigIntSchema, ki as RelationLinks, kn as models, ko as isValueTooLongError, kr as call, kt as BigIntScalar, li as SchemaValidationError, ln as joined, lo as NotFoundError, lr as codec, lt as ExtendedOperationResult, ma as GeoArea, mn as failure, mo as isClientInitializationError, mr as args, mt as VibORMConfig, na as IntegerSchema, ni as PointScalar, no as TransactionError, nr as disclosure, nt as ClientTypeState, oa as JsonSchema, oi as s, on as VIBORM_VERSION, oo as ForbiddenError, or as database, ot as DelegateOperationResult, pa as IsoTimestampSchema, pi as ValidationResult, pn as driver, po as UnsupportedOperationError, pr as accepts, pt as VibORMClient, q as Target, qi as IndexOptions, qn as now, qt as VibSchema, ra as NumberSchema, ri as JsonScalar, ro as ClientInitializationError, rr as defaults, rt as DelegateConfig, sa as JsonValue, si as validateSchema, sn as JoinedSource, so as NestedWriteAssertionError, sr as within, ti as VectorScalar, to as InvalidTransactionInputError, tr as DisclosurePolicy, u as ValidationError, ui as isSchemaValidationError, un as stored, uo as PendingOperationError, ur as again, va as ObjectSchema, vi as IntScalar, vn as parameters, vo as MigrationError, vr as renderOperationResultType, vt as ClientExtensionState, wi as ClientSchema, wn as unit, wo as ValueTooLongError, wr as UnwrapPendingOperations, wt as ModelShape, xa as DecimalSchema, xi as DateScalar, xn as statements, xo as ForeignKeyError, xr as ProjectedModelOperations, xt as ExtensionStateConstraint, yi as TimeScalar, yn as run, yo as isMigrationError, yr as renderSchemaType, yt as EmptyClientExtensionState, z as OperationSet, za as AnyRelation, zi as PointSchema, zn as facts, zo as toPrismaErrorCode } from "./database-adapter-BMjJiBFm.mjs";
2
+ import { a as isSql, c as sqlTag, i as empty, n as Sql, o as join, r as Value, s as raw, t as RawValue } from "./sql-C4_sFNDm.mjs";
3
+ export { Accepted, type AddedExtensionState, type AddedProjectedState, AnyCallContext, AnyFacts, type AnyFieldRef, type AnyJsonNullSentinel, type AnyModel, AnyNull, type AnyRelation, AnyTarget, ArgTest, type AutoGenerate, BatchMember, type BigIntScalar, type BigIntSchema, type BlobScalar, type BlobSchema, type BooleanScalar, type BooleanSchema, BoundAccepted, CacheConfigurationError, CacheInvalidKeyError, CacheInvalidTTLError, CacheOperationNotCacheableError, CallContext, CallResult, type ChainedExtensionState, CheckConstraintError, type ClientExtensionState, type ClientHiddenContext, ClientInitializationError, type ClientSchema, type ClientTypeState, Codec, type InsertValueContext as ComputedContext, ConfiguredBy, ConnectionError, Database, type DateScalar, type DateTimeScalar, DbNull, Decimal, type DecimalDescriptor, type DecimalScalar, type DecimalSchema, type DelegateConfig, type DelegateOperationArgs, type DelegateOperationPayload, type DelegateOperationResult, type DiagnosticDisclosure, DisclosurePolicy, type EmptyClientExtensionState, EmptyFacts, type EnumScalar, type EnumSchema, Exact, type ExtendedClient, type ExtendedOperationResult, Extension, type ExtensionResultConsumerState, type ExtensionStateConstraint as ExtensionState, Facts, FeatureNotSupportedError, type FieldRef, type FlatSchema, ForbiddenError, ForeignKeyError, type GeneratorDefaultBrand, type GeoArea, type GeoBounds, type GeoPoint, type GeoPolygon, type Getter, type IndexDefinition, type IndexOptions, type InitialModelState, type InitialScalarState, type InputJsonValue, type IntScalar, type IntegerSchema, InvalidTransactionInputError, type IsoDateSchema, type IsoTimeSchema, type IsoTimestampSchema, type JoinedSource, JsonNull, type JsonNullKind, JsonNullSentinel, type JsonScalar, type JsonValue, type JsonSchema as JsonValueSchema, type Linked, type LinkedClientConfig, type Links, MigrationError, type Model, type ModelFieldRefs, type ModelInternal, type ModelShape, type ModelSql, type ModelState, type ModelToManyRelation, type ModelToOneRelation, type UpdateState as ModelUpdateState, NestedWriteAssertionError, NestedWriteError, type NoArguments, NotFoundError, NotNullConstraintError, type NumberScalar, type NumberSchema, type NumericScalar, type ObjectSchema, OperationSet, Outcome, Part, Parts, PendingOperation, PendingOperationError, type PlacedArgument, type PointScalar, type PointSchema, type PrismaErrorCode, type ProjectedModelOperations, QueryEngineError, QueryError, type RawOperation, type RawValue, type ReferencesStage, type ReferentialAction, type RelationCardinality, type RelationLinks, type RelationSlot, type RowsFragment, Run, type Scalar, type ScalarKeys, type ScalarState, type UpdateState$1 as ScalarUpdateState, type Schema, SchemaValidationError, type SchemaValidationIssue, Selection, type Severity, Sql, type StampedFields, type StringScalar, type StringSchema, Target, TargetOf, type TimeScalar, type TransactionClient, type TransactionClientOf, TransactionError, UniqueConstraintError, UnitContext, UnitKind, UnitOutcome, UnsupportedOperationError, type UnwrapPendingOperation, type UnwrapPendingOperations, VIBORM_VERSION, ValidationError, type ValidationErrorSource, type ValidationResult, type Value, ValueTooLongError, type VariantToManyRelation, type VariantToOneRelation, type VectorScalar, type VectorSchema, type VibORMClient, type VibORMConfig, VibORMError, VibORMErrorCode, type VibSchema, type ViewState, Watcher, With, WriteKind, WriteOutcome, accepts, again, arg, args, around, bound, call, check, codec, computed, correlation, createClient, createModelFieldRefs, database, defaults, deletes, disclosed, disclosure, driver, empty, exists, extension, facts, failure, fields, gate, getOperationPayloadSchema, getRowKey, getSchemas, isCheckConstraintError, isClientInitializationError, isFieldRef, isForeignKeyError, isJsonNullSentinel, isMigrationError, isNotFoundError, isNotNullConstraintError, isPendingOperation, isPendingOperationError, isRetryableError, isSchemaValidationError, isSql, isUniqueConstraintError, isUnsupportedOperationError, isValidationError, isValueTooLongError, isVibORMError, join, joined, keep, key, lazy, methods, modelMethods, models, note, notes, nothing, now, omitted, oneOf, only, origin, parameters, parts, provided, raw, reads, renderOperationResultType, renderSchemaType, row, rule, run, s, selecting, settled, sqlTag as sql, statement, statements, stored, table, target, text, toPrismaErrorCode, unit, unless, validateOperationPayload, validateSchema, validateSchemaOrThrow, via, watch, when, within, work, wrapError, writes };
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{A as t,C as n,D as r,E as i,O as a,S as o,T as s,b as c,j as l,k as u,v as d,w as f,x as p,y as m}from"./error-mapping-B1-IWkCQ.mjs";import{a as h,i as g,n as _,o as v,s as y,t as b}from"./base-z-cH5ZBI.mjs";import{n as ee,t as te}from"./migrations-BMiRjR-N.mjs";import{_ as ne,a as re,c as ie,d as ae,f as oe,g as se,h as ce,i as le,l as ue,m as de,n as fe,o as pe,p as x,r as S,t as C,u as w,v as T}from"./validation--qS7OPmg.mjs";import{n as E,t as D}from"./transaction-BNomMtme.mjs";import{a as O,i as k,n as A,o as j,r as M,t as N}from"./sql-3o4DOKm9.mjs";import{o as P}from"./value-guards-CBuxSC66.mjs";import{r as F,t as I}from"./extension-CGepsF-p.mjs";import{H as L}from"./native-types-DgjMUikz.mjs";import{J as R,Q as z,X as B,Y as me,Z as he,_ as ge,et as _e,rt as ve,v as ye}from"./scalar-BHCh7aUz.mjs";import{a as be,g as xe,i as Se}from"./validator-CZLW7aR3.mjs";import{r as Ce,t as we}from"./pending-operation-C_eOFOBE.mjs";import{a as Te,i as Ee,r as De,t as Oe}from"./client-DRpX3-vw.mjs";import{c as V,i as ke}from"./validation-CYaJ8ndO.mjs";import{i as Ae,n as je,r as Me,t as Ne}from"./schema-introspection-D0f8cti4.mjs";import{n as H,t as U}from"./methods-part-ZY0f2AV_.mjs";import{a as Pe,c as W,l as Fe,n as Ie,o as Le,r as Re}from"./on-ylYaKuRu.mjs";import{i as ze,n as G,r as Be,t as Ve}from"./args-764KdWMr.mjs";import{n as K,t as q}from"./call-Cz8XUmrl.mjs";import{i as He,n as Ue,r as We,t as Ge}from"./settled-BjyuA76m.mjs";import{n as Ke,r as qe,t as Je}from"./key-hxFFCKed.mjs";import{a as Ye,c as Xe,d as Ze,i as Qe,o as $e,r as et,s as tt,u as nt}from"./rule-words-ZIGm7cDm.mjs";import{a as rt,c as J,i as it,n as at,o as ot,r as st,s as ct}from"./judge-words-CzUyXtJ6.mjs";import{t as lt}from"./confine-DqFBTUw6.mjs";import{n as ut,t as Y}from"./defaults-DwOHWI_M.mjs";import{n as X,r as dt,t as Z}from"./unit-BhHbZyuJ.mjs";import{a as ft,c as pt,d as mt,f as ht,h as gt,i as _t,l as vt,n as yt,o as bt,r as Q,s as xt,t as St,u as Ct}from"./unit-words-CT0yeqfZ.mjs";import{n as wt,r as Tt,t as Et}from"./values-B4aj1i1f.mjs";import{t as Dt}from"./schema-CFIaebgi.mjs";import{t as Ot}from"./version-CXGIA82S.mjs";const $=`$allModels`,kt=new Set([`createMany`,`updateMany`,`deleteMany`]);function planNode(e,t,n,r){let i=e[n[`~`].names.ts]??[],a=P(r?.select)?r.select:void 0,o=P(r?.include)?r.include:void 0,s=P(r?.omit)?r.omit:void 0,c=[],l=a??o,u=l;if(l!==void 0){let r=t.get(n);for(let i of Object.keys(l)){let a=r?.get(i),o=l[i];if(!a||Ee(a)||o!==!0&&!P(o))continue;let s=Te(a,n),d=o===!0?void 0:o,f=planNode(e,t,s,d);f!==void 0&&(c.push([i,f.node]),d?.recurse!==void 0&&f.node.relations.push([i,f.node]),f.args!==d&&(u={...u,[i]:f.args}))}}let d=new Map;for(let[e,t]of i.entries())d.set(t.name,e);let kept=e=>(a?a[e]===!0:!0)&&s?.[e]!==!0,f=[],p=!1;for(let[e,t]of d)p||=(a??s)?.[e]!==void 0,kept(e)&&f.push(t);if(f.length===0&&c.length===0&&!p)return;let m=new Set,h=new Set,close=e=>{if(!m.has(e)){m.add(e);for(let t of i[e].needs)typeof t==`number`?close(t):h.add(t)}};for(let e of f)close(e);let g=new Set;for(let e of h)kept(e)||g.add(e);let _=r;if(s!==void 0){let e={...s};for(let t of d.keys())s[t]!==void 0&&!Object.hasOwn(n[`~`].state.scalars,t)&&delete e[t];for(let t of h)s[t]===!0&&(e[t]=!1);_={..._,omit:e}}if(a!==void 0){let e={...u};for(let t of d.keys())delete e[t];for(let t of h)e[t]=!0;if(!Object.values(e).some(e=>e!==!1)){let[t]=V(n);t!==void 0&&(e[t]=!0,kept(t)||g.add(t))}_={..._,select:e}}else u!==l&&(_={..._,include:u});return{args:_,node:{fields:i,outputs:f,reads:[...h],strip:[...g],relations:c}}}function finishValue(e,t){return Array.isArray(e)?e.map(e=>finishRow(e,t)):finishRow(e,t)}function finishRow(t,n){if(!P(t))return t;let r={...t};for(let[e,t]of n.relations)r[e]!==void 0&&(r[e]=finishValue(r[e],t));for(let e of n.strip)delete r[e];let i=t;for(let e of n.reads){let n=t[e];typeof n!=`object`||!n||(i===t&&(i={...t}),i[e]=detached(n))}let a=new Map,o=e(e=>{if(a.has(e))return a.get(e);let t=n.fields[e],r={};for(let e of t.needs)typeof e==`number`?r[n.fields[e].name]=o(e):r[e]=i[e];let s=t.compute(r);return a.set(e,s),s},`computed`);for(let e of n.outputs){let t=n.fields[e].name,settle=e=>(Object.defineProperty(r,t,{value:e,writable:!0,enumerable:!0,configurable:!0}),e);Object.defineProperty(r,t,{get:()=>settle(o(e)),set:settle,enumerable:!0,configurable:!0})}return r}function detached(e){if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return e.map(detached);if(e instanceof Date)return new Date(e.getTime());if(ArrayBuffer.isView(e))return Object.getPrototypeOf(Uint8Array.prototype).slice.call(e);let t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)return e;let n={};for(let t in e)n[t]=detached(e[t]);return n}function fieldsPart(e){return{join({next:t,name:n,schema:r}){for(let t of Object.keys(e))t!==$&&!Object.hasOwn(r,t)&&F(`Extension "${n}" result names unknown model "${t}".`,n);let i={...t.fields?.fields};for(let t of Object.keys(r)){let a=r[t],o=[...i[t]??[]],s=new Set(V(a));for(let r of[$,t])for(let[i,{needs:c={},compute:l}]of Object.entries(e[r]??{})){let e=`Extension "${n}" result.${r}.${i}`;(i===`_count`||Object.hasOwn(a[`~`].state.relations,i))&&F(`${e} cannot be computed: "${i}" is a relation of model "${t}".`,n);let u=Object.keys(c).filter(e=>c[e]).map(r=>{for(let e=o.length-1;e>=0;e--)if(o[e].name===r)return e;return s.has(r)?r:F(`${e} needs "${r}", which is not a readable scalar or an earlier computed field of model "${t}".`,n)});o.push({name:i,compute:l,needs:u})}o.length>0&&(i[t]=o)}t.fields={fields:i,plan:(e,t,n,r)=>{if(!(De.has(n)||kt.has(n)&&(r.select!==void 0||r.omit!==void 0)))return;let a=planNode(i,e,t,r);if(a===void 0)return;let{node:o}=a;return{args:a.args,finish:e=>finishValue(e,o)}}}}}}function fields(e){return fieldsPart(e)}function parts(){return{extension:I,call:K,around:q,target:W,unit:Z,rule:J,defaults:Y,disclosure:X,args:G,methods:U,modelMethods:H,fields}}const getSchemas=e=>ke(e).proxy;export{R as AnyNull,a as CacheConfigurationError,u as CacheInvalidKeyError,t as CacheInvalidTTLError,l as CacheOperationNotCacheableError,d as CheckConstraintError,S as ClientInitializationError,le as ConnectionError,me as DbNull,L as Decimal,re as FeatureNotSupportedError,pe as ForbiddenError,m as ForeignKeyError,D as InvalidTransactionInputError,B as JsonNull,he as JsonNullSentinel,te as MigrationError,ie as NestedWriteAssertionError,ue as NestedWriteError,w as NotFoundError,c as NotNullConstraintError,we as PendingOperation,ae as PendingOperationError,oe as QueryEngineError,x as QueryError,ge as SchemaValidationError,N as Sql,E as TransactionError,p as UniqueConstraintError,de as UnsupportedOperationError,Ot as VIBORM_VERSION,C as ValidationError,o as ValueTooLongError,b as VibORMError,_ as VibORMErrorCode,Ve as accepts,Ue as again,et as arg,G as args,q as around,Be as bound,K as call,at as check,qe as codec,Et as computed,St as correlation,Oe as createClient,_e as createModelFieldRefs,Ke as database,Y as defaults,Ie as deletes,dt as disclosed,X as disclosure,yt as driver,A as empty,Qe as exists,I as extension,st as facts,Q as failure,fields,it as gate,Ne as getOperationPayloadSchema,xe as getRowKey,getSchemas,n as isCheckConstraintError,ce as isClientInitializationError,ve as isFieldRef,f as isForeignKeyError,z as isJsonNullSentinel,ee as isMigrationError,se as isNotFoundError,s as isNotNullConstraintError,Ce as isPendingOperation,ne as isPendingOperationError,g as isRetryableError,ye as isSchemaValidationError,M as isSql,i as isUniqueConstraintError,T as isUnsupportedOperationError,fe as isValidationError,r as isValueTooLongError,h as isVibORMError,k as join,wt as joined,rt as keep,Je as key,ot as lazy,U as methods,H as modelMethods,Re as models,_t as note,ft as notes,Ye as nothing,$e as now,ut as omitted,ze as oneOf,ct as only,bt as origin,xt as parameters,parts,tt as provided,O as raw,Pe as reads,je as renderOperationResultType,Me as renderSchemaType,Xe as row,J as rule,pt as run,Dt as s,Le as selecting,Ge as settled,j as sql,vt as statement,Ct as statements,Tt as stored,mt as table,W as target,ht as text,v as toPrismaErrorCode,Z as unit,nt as unless,Ae as validateOperationPayload,Se as validateSchema,be as validateSchemaOrThrow,We as via,He as watch,Ze as when,lt as within,gt as work,y as wrapError,Fe as writes};
1
+ import{A as e,C as t,D as n,E as r,O as i,S as a,T as o,b as s,j as c,k as l,v as u,w as d,x as f,y as p}from"./error-mapping-B9rSvgG9.mjs";import{a as m,i as h,n as g,o as _,s as v,t as y}from"./base-17NSFtrA.mjs";import{n as b,t as x}from"./migrations-DIUltjr3.mjs";import{_ as S,a as ee,c as te,d as ne,f as re,g as ie,h as ae,i as oe,l as se,m as ce,n as le,o as ue,p as de,r as fe,t as pe,u as me,v as he}from"./validation-ATmgN5RE.mjs";import{n as ge,t as _e}from"./transaction-Bv5nyp-U.mjs";import{a as C,i as w,n as T,o as E,r as D,t as O}from"./sql-tegqTqGq.mjs";import{o as k}from"./value-guards-CBVIJXlI.mjs";import{r as A,t as j}from"./extension-Dh1ddrlA.mjs";import{dt as M,ft as N,ht as P,mt as F,pt as I,vt as ve,xt as ye}from"./model-Dtd37Sky.mjs";import{U as be}from"./native-types-1ewJXVks.mjs";import{a as xe}from"./keys-DZdKAd4n.mjs";import{r as Se,t as Ce}from"./pending-operation-D4gUKMxD.mjs";import{a as we,i as Te,r as Ee,t as De}from"./client-D7sWgUt2.mjs";import{a as Oe,s as ke}from"./scalar-Dm9brvAU.mjs";import{a as Ae,o as je}from"./time-step-DJaIhpAz.mjs";import{i as Me}from"./validation-BHjx13zG.mjs";import{a as Ne,i as Pe}from"./validator-DMzH5Tz0.mjs";import{i as Fe,n as Ie,r as Le,t as Re}from"./schema-introspection-Bbo4DN_d.mjs";import{n as L,t as R}from"./methods-part-BaNx3o7b.mjs";import{a as ze,c as z,l as Be,n as Ve,o as He,r as Ue}from"./on-ZkOVmE4-.mjs";import{i as We,n as B,r as Ge,t as Ke}from"./args-7WgBFd_f.mjs";import{n as V,t as H}from"./call-0bd_B9Vp.mjs";import{i as qe,n as Je,r as Ye,t as Xe}from"./settled-DYYPcaBX.mjs";import{n as Ze,r as Qe,t as $e}from"./key-BDH6oTyC.mjs";import{a as et,c as tt,d as nt,i as rt,o as it,r as at,s as ot,u as st}from"./rule-words-DMbQuvD2.mjs";import{a as ct,c as U,i as lt,n as ut,o as dt,r as ft,s as pt}from"./judge-words-k5GCc4cV.mjs";import{t as mt}from"./confine-CyI9IwjC.mjs";import{n as ht,t as W}from"./defaults-DAPb-tJ4.mjs";import{n as G,r as gt,t as K}from"./unit-DUPX5Sdd.mjs";import{a as _t,c as vt,d as yt,f as bt,h as xt,i as St,l as Ct,n as wt,o as Tt,r as Et,s as Dt,t as Ot,u as kt}from"./unit-words-BXpLpyr2.mjs";import{n as At,r as jt,t as Mt}from"./values-Ch2cTlss.mjs";import{t as q}from"./schema-DqR_Kcje.mjs";import{t as Nt}from"./version-0BDwfy7C.mjs";const J=`$allModels`,Pt=new Set([`createMany`,`updateMany`,`deleteMany`]);function Y(e,t,n,r){let i=e[n[`~`].names.ts]??[],a=k(r?.select)?r.select:void 0,o=k(r?.include)?r.include:void 0,s=k(r?.omit)?r.omit:void 0,c=[],l=a??o,u=l;if(l!==void 0){let r=t.get(n);for(let n of Object.keys(l)){let i=r?.get(n),a=l[n];if(!i||Te(i)||a!==!0&&!k(a))continue;let o=we(i),s=a===!0?void 0:a,d=Y(e,t,o,s);d!==void 0&&(c.push([n,d.node]),s?.recurse!==void 0&&d.node.relations.push([n,d.node]),d.args!==s&&(u={...u,[n]:d.args}))}}let d=new Map;for(let[e,t]of i.entries())d.set(t.name,e);let f=e=>(a?a[e]===!0:!0)&&s?.[e]!==!0,p=[],m=!1;for(let[e,t]of d)m||=(a??s)?.[e]!==void 0,f(e)&&p.push(t);if(p.length===0&&c.length===0&&!m)return;let h=new Set,g=new Set,_=e=>{if(!h.has(e)){h.add(e);for(let t of i[e].needs)typeof t==`number`?_(t):g.add(t)}};for(let e of p)_(e);let v=new Set;for(let e of g)f(e)||v.add(e);let y=r;if(s!==void 0){let e={...s};for(let t of d.keys())s[t]!==void 0&&!Object.hasOwn(n[`~`].state.scalars,t)&&delete e[t];for(let t of g)s[t]===!0&&(e[t]=!1);y={...y,omit:e}}if(a!==void 0){let e={...u};for(let t of d.keys())delete e[t];for(let t of g)e[t]=!0;if(!Object.values(e).some(e=>e!==!1)){let[t]=je(n);t!==void 0&&(e[t]=!0,f(t)||v.add(t))}y={...y,select:e}}else u!==l&&(y={...y,include:u});return{args:y,node:{fields:i,outputs:p,reads:[...g],strip:[...v],relations:c}}}function X(e,t){return Array.isArray(e)?e.map(e=>Z(e,t)):Z(e,t)}function Z(e,t){if(!k(e))return e;let n={...e};for(let[e,r]of t.relations)n[e]!==void 0&&(n[e]=X(n[e],r));for(let e of t.strip)delete n[e];let r=e;for(let n of t.reads){let t=e[n];typeof t!=`object`||!t||(r===e&&(r={...e}),r[n]=Q(t))}let i=new Map,a=e=>{if(i.has(e))return i.get(e);let n=t.fields[e],o={};for(let e of n.needs)typeof e==`number`?o[t.fields[e].name]=a(e):o[e]=r[e];let s=n.compute(o);return i.set(e,s),s};for(let e of t.outputs){let r=t.fields[e].name,i=e=>(Object.defineProperty(n,r,{value:e,writable:!0,enumerable:!0,configurable:!0}),e);Object.defineProperty(n,r,{get:()=>i(a(e)),set:i,enumerable:!0,configurable:!0})}return n}function Q(e){if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return e.map(Q);if(e instanceof Date)return new Date(e.getTime());if(ArrayBuffer.isView(e))return Object.getPrototypeOf(Uint8Array.prototype).slice.call(e);let t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)return e;let n={};for(let t in e)n[t]=Q(e[t]);return n}function Ft(e){return{join({next:t,name:n,schema:r}){for(let t of Object.keys(e))t!==J&&!Object.hasOwn(r,t)&&A(`Extension "${n}" result names unknown model "${t}".`,n);let i={...t.fields?.fields};for(let t of Object.keys(r)){let a=r[t],o=[...i[t]??[]],s=new Set(Ae(a));for(let r of[J,t])for(let[i,{needs:c={},compute:l}]of Object.entries(e[r]??{})){let e=`Extension "${n}" result.${r}.${i}`;(i===`_count`||i===`_aggregate`||Object.hasOwn(a[`~`].state.relations,i))&&A(`${e} cannot be computed: "${i}" is a relation of model "${t}" or its relation output.`,n);let u=Object.keys(c).filter(e=>c[e]).map(r=>{for(let e=o.length-1;e>=0;e--)if(o[e].name===r)return e;return s.has(r)?r:A(`${e} needs "${r}", which is not a readable scalar or an earlier computed field of model "${t}".`,n)});o.push({name:i,compute:l,needs:u})}o.length>0&&(i[t]=o)}t.fields={fields:i,plan:(e,t,n,r)=>{if(!(Ee.has(n)||Pt.has(n)&&(r.select!==void 0||r.omit!==void 0)))return;let a=Y(i,e,t,r);if(a===void 0)return;let{node:o}=a;return{args:a.args,finish:e=>X(e,o)}}}}}}function $(e){return Ft(e)}function It(){return{extension:j,call:V,around:H,target:z,unit:K,rule:U,defaults:W,disclosure:G,args:B,methods:R,modelMethods:L,fields:$}}const Lt=e=>Me(e).proxy;export{M as AnyNull,i as CacheConfigurationError,l as CacheInvalidKeyError,e as CacheInvalidTTLError,c as CacheOperationNotCacheableError,u as CheckConstraintError,fe as ClientInitializationError,oe as ConnectionError,N as DbNull,be as Decimal,ee as FeatureNotSupportedError,ue as ForbiddenError,p as ForeignKeyError,_e as InvalidTransactionInputError,I as JsonNull,F as JsonNullSentinel,x as MigrationError,te as NestedWriteAssertionError,se as NestedWriteError,me as NotFoundError,s as NotNullConstraintError,Ce as PendingOperation,ne as PendingOperationError,re as QueryEngineError,de as QueryError,Oe as SchemaValidationError,O as Sql,ge as TransactionError,f as UniqueConstraintError,ce as UnsupportedOperationError,Nt as VIBORM_VERSION,pe as ValidationError,a as ValueTooLongError,y as VibORMError,g as VibORMErrorCode,Ke as accepts,Je as again,at as arg,B as args,H as around,Ge as bound,V as call,ut as check,Qe as codec,Mt as computed,Ot as correlation,De as createClient,ve as createModelFieldRefs,Ze as database,W as defaults,Ve as deletes,gt as disclosed,G as disclosure,wt as driver,T as empty,rt as exists,j as extension,ft as facts,Et as failure,$ as fields,lt as gate,Re as getOperationPayloadSchema,xe as getRowKey,Lt as getSchemas,t as isCheckConstraintError,ae as isClientInitializationError,ye as isFieldRef,d as isForeignKeyError,P as isJsonNullSentinel,b as isMigrationError,ie as isNotFoundError,o as isNotNullConstraintError,Se as isPendingOperation,S as isPendingOperationError,h as isRetryableError,ke as isSchemaValidationError,D as isSql,r as isUniqueConstraintError,he as isUnsupportedOperationError,le as isValidationError,n as isValueTooLongError,m as isVibORMError,w as join,At as joined,ct as keep,$e as key,dt as lazy,R as methods,L as modelMethods,Ue as models,St as note,_t as notes,et as nothing,it as now,ht as omitted,We as oneOf,pt as only,Tt as origin,Dt as parameters,It as parts,ot as provided,C as raw,ze as reads,Ie as renderOperationResultType,Le as renderSchemaType,tt as row,U as rule,vt as run,q as s,He as selecting,Xe as settled,E as sql,Ct as statement,kt as statements,jt as stored,yt as table,z as target,bt as text,_ as toPrismaErrorCode,K as unit,st as unless,Fe as validateOperationPayload,Pe as validateSchema,Ne as validateSchemaOrThrow,Ye as via,qe as watch,nt as when,mt as within,xt as work,v as wrapError,Be as writes};
2
2
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["fields","args","key","target","reads","row","computed","settled","extension"],"sources":["../src/extensions/result.ts","../src/extensions/fields.ts","../src/extensions/parts.ts","../src/schema/schemas.ts"],"sourcesContent":["/**\n * `result`: fields a client computes on the rows it returns (Prisma's result\n * extensions).\n *\n * A computed field names what it reads (`needs`) and how (`compute`). It is\n * not a column: the payload is rewritten before validation so the engine reads\n * the fields it needs and never sees the computed one, and the rows are\n * finished after the operation settles — the field computed, the fields read\n * only for it removed. Both steps run only on a client whose chain declares\n * `result`; any other client builds and runs none of this.\n *\n * Which rows: every row of the model an operation returns, nested relation\n * rows included, the way a `select` or `include` reaches them. A field is\n * selected and omitted by its name, as a column is; a field may shadow a\n * scalar of the same name. A later extension's field may need an earlier\n * one's, even under the same name, and is computed after it. Filtering,\n * ordering, grouping and aggregating by a computed field stay refused: the\n * database never sees it. A variant relation's rows do not carry computed\n * fields; a recursive projection carries them at every level.\n */\n\nimport {\n directVariantCarrier,\n PROJECTING_OPERATIONS,\n slotTarget,\n} from \"@client/omit\";\nimport type { AnyModel } from \"@schema/model\";\nimport type { ResolvedRelationIndex } from \"@schema/validation/relation-resolution\";\nimport { projectableScalarNames } from \"@validation/model/core/projection\";\nimport { isRecord } from \"@validation/value-guards\";\nimport type { ExtensionPart } from \"./chain\";\nimport { extensionError } from \"./chain\";\n\ntype Row = Record<string, unknown>;\n\n/**\n * One model's computed field on the chain. Each need is a column's name, or\n * the index of the earlier computed field it reads.\n */\ninterface ResolvedComputedField {\n readonly name: string;\n readonly compute: (row: Row) => unknown;\n readonly needs: readonly (string | number)[];\n}\n\n/**\n * Per model name, every computed field the chain declares, in chain order: a\n * field's needs point only at columns and at fields before it.\n */\ntype ResolvedResultFields = Readonly<\n Record<string, readonly ResolvedComputedField[]>\n>;\n\nconst ALL_MODELS = \"$allModels\";\n\n/** A computed field as `fields(…)` is written: what it needs, and how. */\nexport interface ComputedFieldDeclaration {\n readonly needs?: Readonly<Record<string, boolean>>;\n readonly compute: (row: Row) => unknown;\n}\n\n/**\n * One projection node's work on its rows, and its relations' nodes. A\n * recursive relation's node lists itself under the repeated key, so the\n * finish follows the tree the projection repeats.\n */\ninterface ResultNode {\n /** The model's computed fields; `outputs` indexes the ones returned. */\n readonly fields: readonly ResolvedComputedField[];\n readonly outputs: readonly number[];\n /** The columns the returned fields read, through earlier fields too. */\n readonly reads: readonly string[];\n readonly strip: readonly string[];\n readonly relations: (readonly [string, ResultNode])[];\n}\n\n/** A bulk write returns rows only when it carries a projection. */\nconst BULK_OPERATIONS = new Set([\"createMany\", \"updateMany\", \"deleteMany\"]);\n\nfunction planNode(\n fields: ResolvedResultFields,\n relations: ResolvedRelationIndex,\n model: AnyModel,\n args: Row | undefined\n): { readonly args: Row | undefined; readonly node: ResultNode } | undefined {\n // A hydrated model always has its name.\n const declared = fields[model[\"~\"].names.ts!] ?? [];\n const select = isRecord(args?.select) ? args.select : undefined;\n const include = isRecord(args?.include) ? args.include : undefined;\n const omit = isRecord(args?.omit) ? args.omit : undefined;\n\n // The relations first: a node with no field of its own may still lead to\n // one that has.\n const nested: (readonly [string, ResultNode])[] = [];\n const projection = select ?? include;\n let nextProjection = projection;\n if (projection !== undefined) {\n const slots = relations.get(model);\n for (const key of Object.keys(projection)) {\n const resolved = slots?.get(key);\n const value = projection[key];\n if (\n !resolved ||\n directVariantCarrier(resolved) ||\n (value !== true && !isRecord(value))\n )\n continue;\n const target = slotTarget(resolved, model);\n const childArgs = value === true ? undefined : value;\n const child = planNode(fields, relations, target, childArgs);\n if (child === undefined) continue;\n nested.push([key, child.node]);\n if (childArgs?.recurse !== undefined)\n child.node.relations.push([key, child.node]);\n if (child.args !== childArgs)\n nextProjection = { ...nextProjection, [key]: child.args };\n }\n }\n\n // The latest declaration of each name is the visible field.\n const visible = new Map<string, number>();\n for (const [index, field] of declared.entries())\n visible.set(field.name, index);\n // A name the payload keeps: a column it returns, or a field it computes.\n const kept = (name: string) =>\n (select ? select[name] === true : true) && omit?.[name] !== true;\n const wanted: number[] = [];\n // A payload that names a field it does not want still loses that key.\n let named = false;\n for (const [name, index] of visible) {\n named ||= (select ?? omit)?.[name] !== undefined;\n if (kept(name)) wanted.push(index);\n }\n if (wanted.length === 0 && nested.length === 0 && !named) return undefined;\n\n // Every field the wanted ones read, computed first; the columns they read.\n const computing = new Set<number>();\n const reads = new Set<string>();\n const close = (index: number) => {\n if (computing.has(index)) return;\n computing.add(index);\n for (const need of declared[index]!.needs) {\n if (typeof need === \"number\") close(need);\n else reads.add(need);\n }\n };\n for (const index of wanted) close(index);\n // The columns read only for a field: removed from the rows again (a kept\n // name that is a field is computed over its column).\n const strip = new Set<string>();\n for (const field of reads) if (!kept(field)) strip.add(field);\n\n // Each key the plan changes is replaced in a copy, in its place.\n let next = args;\n // `omit` subtracts from either projection: a computed name leaves it (a\n // column it shadows stays omitted), and a column a field reads is read\n // anyway, then removed again.\n if (omit !== undefined) {\n const nextOmit = { ...omit };\n for (const name of visible.keys())\n if (\n omit[name] !== undefined &&\n !Object.hasOwn(model[\"~\"].state.scalars, name)\n )\n delete nextOmit[name];\n for (const field of reads)\n if (omit[field] === true) nextOmit[field] = false;\n next = { ...next, omit: nextOmit };\n }\n if (select !== undefined) {\n const nextSelect: Row = { ...nextProjection };\n for (const name of visible.keys()) delete nextSelect[name];\n for (const field of reads) nextSelect[field] = true;\n if (!Object.values(nextSelect).some((value) => value !== false)) {\n const [first] = projectableScalarNames(model);\n if (first !== undefined) {\n nextSelect[first] = true;\n if (!kept(first)) strip.add(first);\n }\n }\n next = { ...next, select: nextSelect };\n } else if (nextProjection !== projection) {\n next = { ...next, include: nextProjection };\n }\n\n return {\n args: next,\n node: {\n fields: declared,\n outputs: wanted,\n reads: [...reads],\n strip: [...strip],\n relations: nested,\n },\n };\n}\n\nfunction finishValue(value: unknown, node: ResultNode): unknown {\n if (Array.isArray(value)) return value.map((row) => finishRow(row, node));\n return finishRow(value, node);\n}\n\n/**\n * A copy of one row, its relations finished, the columns read only for a\n * field removed, and each field an enumerable getter, as Prisma's are: it is\n * computed on first read, once, from the values the call read (the row as\n * fetched, never the copy its caller may change: a JSON, date, list or binary\n * value a field reads is copied here, before the caller can edit it, and\n * only then), so a `compute` that throws\n * throws where the field is read and never fails the operation, nor a write\n * that already committed. A field assigned before it is read keeps the value\n * assigned.\n */\nfunction finishRow(value: unknown, node: ResultNode): unknown {\n if (!isRecord(value)) return value;\n const row: Row = { ...value };\n for (const [key, child] of node.relations) {\n if (row[key] !== undefined) row[key] = finishValue(row[key], child);\n }\n for (const key of node.strip) delete row[key];\n let fetched: Row = value;\n for (const column of node.reads) {\n const held = value[column];\n if (held === null || typeof held !== \"object\") continue;\n if (fetched === value) fetched = { ...value };\n fetched[column] = detached(held);\n }\n const values = new Map<number, unknown>();\n const computed = (index: number): unknown => {\n if (values.has(index)) return values.get(index);\n const field = node.fields[index]!;\n const input: Row = {};\n for (const need of field.needs) {\n if (typeof need === \"number\")\n input[node.fields[need]!.name] = computed(need);\n else input[need] = fetched[need];\n }\n const result = field.compute(input);\n values.set(index, result);\n return result;\n };\n for (const index of node.outputs) {\n const name = node.fields[index]!.name;\n const settle = (settled: unknown) => {\n Object.defineProperty(row, name, {\n value: settled,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n return settled;\n };\n Object.defineProperty(row, name, {\n get: () => settle(computed(index)),\n set: settle,\n enumerable: true,\n configurable: true,\n });\n }\n return row;\n}\n\n/**\n * A copy of a value the caller could edit: JSON objects and lists, dates and\n * binary or numeric arrays. A class instance (a `Decimal`) is immutable and\n * shared.\n */\nfunction detached(held: unknown): unknown {\n if (held === null || typeof held !== \"object\") return held;\n if (Array.isArray(held)) return held.map(detached);\n if (held instanceof Date) return new Date(held.getTime());\n // The typed arrays' own `slice`, read here and not at module scope: a\n // top-level read is a side effect every bundle importing viborm would keep.\n // No provider row holds a `DataView`: a view is a typed array.\n if (ArrayBuffer.isView(held))\n return (\n Object.getPrototypeOf(Uint8Array.prototype).slice as (\n this: ArrayBufferView\n ) => ArrayBufferView\n ).call(held);\n const prototype = Object.getPrototypeOf(held);\n if (prototype !== Object.prototype && prototype !== null) return held;\n const copy: Row = {};\n // A plain object past the checks above: a record of values.\n for (const key in held) copy[key] = detached((held as Row)[key]);\n return copy;\n}\n\n/**\n * A chain's computed fields, and what plans one call: the payload the engine\n * runs, and the function that finishes its value; `undefined` when nothing\n * the operation returns has a computed field.\n */\nexport interface ResultFields {\n readonly fields: ResolvedResultFields;\n readonly plan: (\n relations: ResolvedRelationIndex,\n model: AnyModel,\n operation: string,\n args: Row\n ) =>\n | { readonly args: Row; readonly finish: (value: unknown) => unknown }\n | undefined;\n}\n\n/**\n * `fields`: fields computed from each row a call returns. Joined, the\n * chain's computed fields with this extension's appended: per model,\n * `$allModels` first, then the model's own, so a model's field can replace\n * or need an `$allModels` one. Every need is resolved here, against the\n * model's readable scalars and the fields before it; a model the schema\n * does not hold is refused, as a field computed on no row would otherwise\n * be.\n */\nexport function fieldsPart(\n declared: Readonly<\n Record<string, Readonly<Record<string, ComputedFieldDeclaration>>>\n >\n): ExtensionPart {\n return {\n join({ next, name: extension, schema }) {\n for (const key of Object.keys(declared))\n if (key !== ALL_MODELS && !Object.hasOwn(schema, key))\n extensionError(\n `Extension \"${extension}\" result names unknown model \"${key}\".`,\n extension\n );\n const fields: Record<string, readonly ResolvedComputedField[]> = {\n ...next.fields?.fields,\n };\n for (const modelName of Object.keys(schema)) {\n const model = schema[modelName]!;\n const resolved = [...(fields[modelName] ?? [])];\n const readable = new Set(projectableScalarNames(model));\n for (const key of [ALL_MODELS, modelName]) {\n for (const [name, { needs = {}, compute }] of Object.entries(\n declared[key] ?? {}\n )) {\n const at = `Extension \"${extension}\" result.${key}.${name}`;\n if (\n name === \"_count\" ||\n Object.hasOwn(model[\"~\"].state.relations, name)\n )\n extensionError(\n `${at} cannot be computed: \"${name}\" is a relation of model \"${modelName}\".`,\n extension\n );\n const needed = Object.keys(needs)\n .filter((need) => needs[need])\n .map((need) => {\n for (let earlier = resolved.length - 1; earlier >= 0; earlier--)\n if (resolved[earlier]!.name === need) return earlier;\n if (readable.has(need)) return need;\n return extensionError(\n `${at} needs \"${need}\", which is not a readable scalar or an earlier computed field of model \"${modelName}\".`,\n extension\n );\n });\n resolved.push({ name, compute, needs: needed });\n }\n }\n if (resolved.length > 0) fields[modelName] = resolved;\n }\n next.fields = {\n fields,\n plan: (relations, model, operation, args) => {\n const returnsRows =\n PROJECTING_OPERATIONS.has(operation) ||\n (BULK_OPERATIONS.has(operation) &&\n (args.select !== undefined || args.omit !== undefined));\n if (!returnsRows) return undefined;\n const planned = planNode(fields, relations, model, args);\n if (planned === undefined) return undefined;\n const { node } = planned;\n return {\n // Planned from `args`, never absent: only a relation's may be.\n args: planned.args!,\n finish: (value) => finishValue(value, node),\n };\n },\n };\n },\n };\n}\n","/**\n * `fields({ [model | \"$allModels\"]: { [field]: { needs, compute } } })`:\n * fields computed from the columns each row a call returns reads. A part of\n * its own: an extension that does not import it carries none of it.\n */\nimport type {\n AnyTarget,\n Facts,\n ModelName,\n NoArguments,\n Part,\n} from \"./contract\";\nimport { type ComputedFieldDeclaration, fieldsPart } from \"./result\";\nimport type { ComputedFieldTypes, FieldsInference } from \"./result-types\";\n\ntype NoMethods = Record<never, never>;\n\n/** Fields computed from the columns each returned row reads. */\nexport function fields<\n T extends AnyTarget,\n const Declared extends object = object,\n Needs = unknown,\n>(\n fields: Declared & FieldsInference<T[\"config\"], T[\"state\"][\"fields\"], Needs>\n): Part<\n T,\n Facts<\n NoMethods,\n NoMethods,\n NoArguments,\n never,\n never,\n ComputedFieldTypes<\n Pick<Declared, Extract<keyof Declared, ModelName<T> | \"$allModels\">>\n >\n >\n>;\nexport function fields(\n declared: Readonly<\n Record<string, Readonly<Record<string, ComputedFieldDeclaration>>>\n >\n): unknown {\n return fieldsPart(declared);\n}\n","/**\n * `parts<Of>()`: the vocabulary typed against one client or one schema, for\n * an extension written apart from the `$extends` it is passed to. The same\n * builders: only their types are bound, so importing it carries every\n * builder.\n */\nimport { args } from \"./args\";\nimport { around, call } from \"./call\";\nimport type { Parts, TargetOf } from \"./contract\";\nimport { defaults } from \"./defaults\";\nimport { disclosure } from \"./disclosure\";\nimport { extension } from \"./extension\";\nimport { fields } from \"./fields\";\nimport { methods, modelMethods } from \"./methods-part\";\nimport { target } from \"./on\";\nimport { rule } from \"./rule\";\nimport { unit } from \"./unit\";\n\n/** The builders, typed against `Of`: a client's type, or a schema. */\nexport function parts<Of>(): Parts<TargetOf<Of>>;\nexport function parts(): unknown {\n return {\n extension,\n call,\n around,\n target,\n unit,\n rule,\n defaults,\n disclosure,\n args,\n methods,\n modelMethods,\n fields,\n };\n}\n","import { createSchemaRegistry, type ModelSchemas } from \"@validation\";\nimport type { AnyModel } from \"./model\";\n\ntype Schema = Record<string, AnyModel>;\n\ntype SchemaProxy<S extends Schema> = {\n [K in keyof S]: ModelSchemas<S[K]>;\n};\n\n/**\n * Creates a registry-backed proxy to access model validation schemas.\n * Usage: `getSchemas(mySchema).user.core.where` → returns the where schema for the user model\n *\n * This is REGISTRY-ONLY construction — a schema surface without a client — and\n * plan §7.3 makes it one of the three effect-capable boundaries: the operation\n * schemas it returns decide which mutation verbs a caller may spell, which is a\n * topology answer. So it hydrates and runs the structural relation-definition\n * gate once, for its own lifecycle, exactly as client construction does.\n */\nexport const getSchemas = <S extends Schema>(schema: S): SchemaProxy<S> => {\n return createSchemaRegistry(schema).proxy;\n};\n"],"mappings":"kpEAqDA,MAAM,EAAa,aAwBb,GAAkB,IAAI,IAAI,CAAC,aAAc,aAAc,aAAa,CAAC,CAE3E,SAAS,SACP,EACA,EACA,EACA,EAC2E,CAE3E,IAAM,EAAWA,EAAO,EAAM,KAAK,MAAM,KAAQ,EAAE,CAC7C,EAAS,EAASC,GAAM,OAAO,CAAGA,EAAK,OAAS,IAAA,GAChD,EAAU,EAASA,GAAM,QAAQ,CAAGA,EAAK,QAAU,IAAA,GACnD,EAAO,EAASA,GAAM,KAAK,CAAGA,EAAK,KAAO,IAAA,GAI1C,EAA4C,EAAE,CAC9C,EAAa,GAAU,EACzB,EAAiB,EACrB,GAAI,IAAe,IAAA,GAAW,CAC5B,IAAM,EAAQ,EAAU,IAAI,EAAM,CAClC,IAAK,IAAMC,KAAO,OAAO,KAAK,EAAW,CAAE,CACzC,IAAM,EAAW,GAAO,IAAIA,EAAI,CAC1B,EAAQ,EAAWA,GACzB,GACE,CAAC,GACD,GAAqB,EAAS,EAC7B,IAAU,IAAQ,CAAC,EAAS,EAAM,CAEnC,SACF,IAAMC,EAAS,GAAW,EAAU,EAAM,CACpC,EAAY,IAAU,GAAO,IAAA,GAAY,EACzC,EAAQ,SAASH,EAAQ,EAAWG,EAAQ,EAAU,CACxD,IAAU,IAAA,KACd,EAAO,KAAK,CAACD,EAAK,EAAM,KAAK,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AAU,SAASD,EAAQ,EAAW,EAAOC,EAAK,CACxD,GAAI,IAAY,IAAA,GAAW,OAC3B,GAAM,CAAE,QAAS,EACjB,MAAO,CAEL,KAAM,EAAQ,KACd,OAAS,GAAU,YAAY,EAAO,EAAK,CAC5C,EAEJ,EAEJ,CCzVH,SAAgB,OACd,EAGS,CACT,OAAO,WAAW,EAAS,CCtB7B,SAAgB,OAAiB,CAC/B,MAAO,CACL,YACA,OACA,SACA,SACA,OACA,OACA,WACA,aACA,OACA,UACA,eACA,OACD,CCfH,MAAa,WAAgC,GACpC,GAAqB,EAAO,CAAC"}
1
+ {"version":3,"file":"index.mjs","names":["fields","args","key","target","reads","row","computed","settled","extension"],"sources":["../src/extensions/result.ts","../src/extensions/fields.ts","../src/extensions/parts.ts","../src/schema/schemas.ts"],"sourcesContent":["/**\n * `result`: fields a client computes on the rows it returns (Prisma's result\n * extensions).\n *\n * A computed field names what it reads (`needs`) and how (`compute`). It is\n * not a column: the payload is rewritten before validation so the engine reads\n * the fields it needs and never sees the computed one, and the rows are\n * finished after the operation settles — the field computed, the fields read\n * only for it removed. Both steps run only on a client whose chain declares\n * `result`; any other client builds and runs none of this.\n *\n * Which rows: every row of the model an operation returns, nested relation\n * rows included, the way a `select` or `include` reaches them. A field is\n * selected and omitted by its name, as a column is; a field may shadow a\n * scalar of the same name. A later extension's field may need an earlier\n * one's, even under the same name, and is computed after it. Filtering,\n * ordering, grouping and aggregating by a computed field stay refused: the\n * database never sees it. A variant relation's rows do not carry computed\n * fields; a recursive projection carries them at every level.\n */\n\nimport {\n directVariantCarrier,\n PROJECTING_OPERATIONS,\n slotTarget,\n} from \"@client/omit\";\nimport type { AnyModel } from \"@schema/model\";\nimport type { ResolvedRelationIndex } from \"@schema/validation/relation-resolution\";\nimport {\n defaultProjectionNames,\n projectableScalarNames,\n} from \"@validation/model/core/projection\";\nimport { isRecord } from \"@validation/value-guards\";\nimport type { ExtensionPart } from \"./chain\";\nimport { extensionError } from \"./chain\";\n\ntype Row = Record<string, unknown>;\n\n/**\n * One model's computed field on the chain. Each need is a column's name, or\n * the index of the earlier computed field it reads.\n */\ninterface ResolvedComputedField {\n readonly name: string;\n readonly compute: (row: Row) => unknown;\n readonly needs: readonly (string | number)[];\n}\n\n/**\n * Per model name, every computed field the chain declares, in chain order: a\n * field's needs point only at columns and at fields before it.\n */\ntype ResolvedResultFields = Readonly<\n Record<string, readonly ResolvedComputedField[]>\n>;\n\nconst ALL_MODELS = \"$allModels\";\n\n/** A computed field as `fields(…)` is written: what it needs, and how. */\nexport interface ComputedFieldDeclaration {\n readonly needs?: Readonly<Record<string, boolean>>;\n readonly compute: (row: Row) => unknown;\n}\n\n/**\n * One projection node's work on its rows, and its relations' nodes. A\n * recursive relation's node lists itself under the repeated key, so the\n * finish follows the tree the projection repeats.\n */\ninterface ResultNode {\n /** The model's computed fields; `outputs` indexes the ones returned. */\n readonly fields: readonly ResolvedComputedField[];\n readonly outputs: readonly number[];\n /** The columns the returned fields read, through earlier fields too. */\n readonly reads: readonly string[];\n readonly strip: readonly string[];\n readonly relations: (readonly [string, ResultNode])[];\n}\n\n/** A bulk write returns rows only when it carries a projection. */\nconst BULK_OPERATIONS = new Set([\"createMany\", \"updateMany\", \"deleteMany\"]);\n\nfunction planNode(\n fields: ResolvedResultFields,\n relations: ResolvedRelationIndex,\n model: AnyModel,\n args: Row | undefined\n): { readonly args: Row | undefined; readonly node: ResultNode } | undefined {\n // A hydrated model always has its name.\n const declared = fields[model[\"~\"].names.ts!] ?? [];\n const select = isRecord(args?.select) ? args.select : undefined;\n const include = isRecord(args?.include) ? args.include : undefined;\n const omit = isRecord(args?.omit) ? args.omit : undefined;\n\n // The relations first: a node with no field of its own may still lead to\n // one that has.\n const nested: (readonly [string, ResultNode])[] = [];\n const projection = select ?? include;\n let nextProjection = projection;\n if (projection !== undefined) {\n const slots = relations.get(model);\n for (const key of Object.keys(projection)) {\n const resolved = slots?.get(key);\n const value = projection[key];\n if (\n !resolved ||\n directVariantCarrier(resolved) ||\n (value !== true && !isRecord(value))\n )\n continue;\n const target = slotTarget(resolved);\n const childArgs = value === true ? undefined : value;\n const child = planNode(fields, relations, target, childArgs);\n if (child === undefined) continue;\n nested.push([key, child.node]);\n if (childArgs?.recurse !== undefined)\n child.node.relations.push([key, child.node]);\n if (child.args !== childArgs)\n nextProjection = { ...nextProjection, [key]: child.args };\n }\n }\n\n // The latest declaration of each name is the visible field.\n const visible = new Map<string, number>();\n for (const [index, field] of declared.entries())\n visible.set(field.name, index);\n // A name the payload keeps: a column it returns, or a field it computes.\n const kept = (name: string) =>\n (select ? select[name] === true : true) && omit?.[name] !== true;\n const wanted: number[] = [];\n // A payload that names a field it does not want still loses that key.\n let named = false;\n for (const [name, index] of visible) {\n named ||= (select ?? omit)?.[name] !== undefined;\n if (kept(name)) wanted.push(index);\n }\n if (wanted.length === 0 && nested.length === 0 && !named) return undefined;\n\n // Every field the wanted ones read, computed first; the columns they read.\n const computing = new Set<number>();\n const reads = new Set<string>();\n const close = (index: number) => {\n if (computing.has(index)) return;\n computing.add(index);\n for (const need of declared[index]!.needs) {\n if (typeof need === \"number\") close(need);\n else reads.add(need);\n }\n };\n for (const index of wanted) close(index);\n // The columns read only for a field: removed from the rows again (a kept\n // name that is a field is computed over its column).\n const strip = new Set<string>();\n for (const field of reads) if (!kept(field)) strip.add(field);\n\n // Each key the plan changes is replaced in a copy, in its place.\n let next = args;\n // `omit` subtracts from either projection: a computed name leaves it (a\n // column it shadows stays omitted), and a column a field reads is read\n // anyway, then removed again.\n if (omit !== undefined) {\n const nextOmit = { ...omit };\n for (const name of visible.keys())\n if (\n omit[name] !== undefined &&\n !Object.hasOwn(model[\"~\"].state.scalars, name)\n )\n delete nextOmit[name];\n for (const field of reads)\n if (omit[field] === true) nextOmit[field] = false;\n next = { ...next, omit: nextOmit };\n }\n if (select !== undefined) {\n const nextSelect: Row = { ...nextProjection };\n for (const name of visible.keys()) delete nextSelect[name];\n for (const field of reads) nextSelect[field] = true;\n if (!Object.values(nextSelect).some((value) => value !== false)) {\n const [first] = projectableScalarNames(model);\n if (first !== undefined) {\n nextSelect[first] = true;\n if (!kept(first)) strip.add(first);\n }\n }\n next = { ...next, select: nextSelect };\n } else if (nextProjection !== projection) {\n next = { ...next, include: nextProjection };\n }\n\n return {\n args: next,\n node: {\n fields: declared,\n outputs: wanted,\n reads: [...reads],\n strip: [...strip],\n relations: nested,\n },\n };\n}\n\nfunction finishValue(value: unknown, node: ResultNode): unknown {\n if (Array.isArray(value)) return value.map((row) => finishRow(row, node));\n return finishRow(value, node);\n}\n\n/**\n * A copy of one row, its relations finished, the columns read only for a\n * field removed, and each field an enumerable getter, as Prisma's are: it is\n * computed on first read, once, from the values the call read (the row as\n * fetched, never the copy its caller may change: a JSON, date, list or binary\n * value a field reads is copied here, before the caller can edit it, and\n * only then), so a `compute` that throws\n * throws where the field is read and never fails the operation, nor a write\n * that already committed. A field assigned before it is read keeps the value\n * assigned.\n */\nfunction finishRow(value: unknown, node: ResultNode): unknown {\n if (!isRecord(value)) return value;\n const row: Row = { ...value };\n for (const [key, child] of node.relations) {\n if (row[key] !== undefined) row[key] = finishValue(row[key], child);\n }\n for (const key of node.strip) delete row[key];\n let fetched: Row = value;\n for (const column of node.reads) {\n const held = value[column];\n if (held === null || typeof held !== \"object\") continue;\n if (fetched === value) fetched = { ...value };\n fetched[column] = detached(held);\n }\n const values = new Map<number, unknown>();\n const computed = (index: number): unknown => {\n if (values.has(index)) return values.get(index);\n const field = node.fields[index]!;\n const input: Row = {};\n for (const need of field.needs) {\n if (typeof need === \"number\")\n input[node.fields[need]!.name] = computed(need);\n else input[need] = fetched[need];\n }\n const result = field.compute(input);\n values.set(index, result);\n return result;\n };\n for (const index of node.outputs) {\n const name = node.fields[index]!.name;\n const settle = (settled: unknown) => {\n Object.defineProperty(row, name, {\n value: settled,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n return settled;\n };\n Object.defineProperty(row, name, {\n get: () => settle(computed(index)),\n set: settle,\n enumerable: true,\n configurable: true,\n });\n }\n return row;\n}\n\n/**\n * A copy of a value the caller could edit: JSON objects and lists, dates and\n * binary or numeric arrays. A class instance (a `Decimal`) is immutable and\n * shared.\n */\nfunction detached(held: unknown): unknown {\n if (held === null || typeof held !== \"object\") return held;\n if (Array.isArray(held)) return held.map(detached);\n if (held instanceof Date) return new Date(held.getTime());\n // The typed arrays' own `slice`, read here and not at module scope: a\n // top-level read is a side effect every bundle importing viborm would keep.\n // No provider row holds a `DataView`: a view is a typed array.\n if (ArrayBuffer.isView(held))\n return (\n Object.getPrototypeOf(Uint8Array.prototype).slice as (\n this: ArrayBufferView\n ) => ArrayBufferView\n ).call(held);\n const prototype = Object.getPrototypeOf(held);\n if (prototype !== Object.prototype && prototype !== null) return held;\n const copy: Row = {};\n // A plain object past the checks above: a record of values.\n for (const key in held) copy[key] = detached((held as Row)[key]);\n return copy;\n}\n\n/**\n * A chain's computed fields, and what plans one call: the payload the engine\n * runs, and the function that finishes its value; `undefined` when nothing\n * the operation returns has a computed field.\n */\nexport interface ResultFields {\n readonly fields: ResolvedResultFields;\n readonly plan: (\n relations: ResolvedRelationIndex,\n model: AnyModel,\n operation: string,\n args: Row\n ) =>\n | { readonly args: Row; readonly finish: (value: unknown) => unknown }\n | undefined;\n}\n\n/**\n * `fields`: fields computed from each row a call returns. Joined, the\n * chain's computed fields with this extension's appended: per model,\n * `$allModels` first, then the model's own, so a model's field can replace\n * or need an `$allModels` one. Every need is resolved here, against what a\n * row of the model reads by default (its scalars, a view's JSON columns) and\n * the fields before it; a model the schema does not hold is refused, as a\n * field computed on no row would otherwise be.\n */\nexport function fieldsPart(\n declared: Readonly<\n Record<string, Readonly<Record<string, ComputedFieldDeclaration>>>\n >\n): ExtensionPart {\n return {\n join({ next, name: extension, schema }) {\n for (const key of Object.keys(declared))\n if (key !== ALL_MODELS && !Object.hasOwn(schema, key))\n extensionError(\n `Extension \"${extension}\" result names unknown model \"${key}\".`,\n extension\n );\n const fields: Record<string, readonly ResolvedComputedField[]> = {\n ...next.fields?.fields,\n };\n for (const modelName of Object.keys(schema)) {\n const model = schema[modelName]!;\n const resolved = [...(fields[modelName] ?? [])];\n const readable = new Set(defaultProjectionNames(model));\n for (const key of [ALL_MODELS, modelName]) {\n for (const [name, { needs = {}, compute }] of Object.entries(\n declared[key] ?? {}\n )) {\n const at = `Extension \"${extension}\" result.${key}.${name}`;\n // `_count` and `_aggregate` are the relations' own outputs (F010).\n if (\n name === \"_count\" ||\n name === \"_aggregate\" ||\n Object.hasOwn(model[\"~\"].state.relations, name)\n )\n extensionError(\n `${at} cannot be computed: \"${name}\" is a relation of model \"${modelName}\" or its relation output.`,\n extension\n );\n const needed = Object.keys(needs)\n .filter((need) => needs[need])\n .map((need) => {\n for (let earlier = resolved.length - 1; earlier >= 0; earlier--)\n if (resolved[earlier]!.name === need) return earlier;\n if (readable.has(need)) return need;\n return extensionError(\n `${at} needs \"${need}\", which is not a readable scalar or an earlier computed field of model \"${modelName}\".`,\n extension\n );\n });\n resolved.push({ name, compute, needs: needed });\n }\n }\n if (resolved.length > 0) fields[modelName] = resolved;\n }\n next.fields = {\n fields,\n plan: (relations, model, operation, args) => {\n const returnsRows =\n PROJECTING_OPERATIONS.has(operation) ||\n (BULK_OPERATIONS.has(operation) &&\n (args.select !== undefined || args.omit !== undefined));\n if (!returnsRows) return undefined;\n const planned = planNode(fields, relations, model, args);\n if (planned === undefined) return undefined;\n const { node } = planned;\n return {\n // Planned from `args`, never absent: only a relation's may be.\n args: planned.args!,\n finish: (value) => finishValue(value, node),\n };\n },\n };\n },\n };\n}\n","/**\n * `fields({ [model | \"$allModels\"]: { [field]: { needs, compute } } })`:\n * fields computed from the columns each row a call returns reads. A part of\n * its own: an extension that does not import it carries none of it.\n */\nimport type {\n AnyTarget,\n Facts,\n ModelName,\n NoArguments,\n Part,\n} from \"./contract\";\nimport { type ComputedFieldDeclaration, fieldsPart } from \"./result\";\nimport type { ComputedFieldTypes, FieldsInference } from \"./result-types\";\n\ntype NoMethods = Record<never, never>;\n\n/** Fields computed from the columns each returned row reads. */\nexport function fields<\n T extends AnyTarget,\n const Declared extends object = object,\n Needs = unknown,\n>(\n fields: Declared & FieldsInference<T[\"config\"], T[\"state\"][\"fields\"], Needs>\n): Part<\n T,\n Facts<\n NoMethods,\n NoMethods,\n NoArguments,\n never,\n never,\n ComputedFieldTypes<\n Pick<Declared, Extract<keyof Declared, ModelName<T> | \"$allModels\">>\n >\n >\n>;\nexport function fields(\n declared: Readonly<\n Record<string, Readonly<Record<string, ComputedFieldDeclaration>>>\n >\n): unknown {\n return fieldsPart(declared);\n}\n","/**\n * `parts<Of>()`: the vocabulary typed against one client or one schema, for\n * an extension written apart from the `$extends` it is passed to. The same\n * builders: only their types are bound, so importing it carries every\n * builder.\n */\nimport { args } from \"./args\";\nimport { around, call } from \"./call\";\nimport type { Parts, TargetOf } from \"./contract\";\nimport { defaults } from \"./defaults\";\nimport { disclosure } from \"./disclosure\";\nimport { extension } from \"./extension\";\nimport { fields } from \"./fields\";\nimport { methods, modelMethods } from \"./methods-part\";\nimport { target } from \"./on\";\nimport { rule } from \"./rule\";\nimport { unit } from \"./unit\";\n\n/** The builders, typed against `Of`: a client's type, or a schema. */\nexport function parts<Of>(): Parts<TargetOf<Of>>;\nexport function parts(): unknown {\n return {\n extension,\n call,\n around,\n target,\n unit,\n rule,\n defaults,\n disclosure,\n args,\n methods,\n modelMethods,\n fields,\n };\n}\n","import { createSchemaRegistry, type ModelSchemas } from \"@validation\";\nimport type { AnyModel } from \"./model\";\n\ntype Schema = Record<string, AnyModel>;\n\ntype SchemaProxy<S extends Schema> = {\n [K in keyof S]: ModelSchemas<S[K]>;\n};\n\n/**\n * Creates a registry-backed proxy to access model validation schemas.\n * Usage: `getSchemas(mySchema).user.core.where` → returns the where schema for the user model\n *\n * This is REGISTRY-ONLY construction — a schema surface without a client — and\n * plan §7.3 makes it one of the three effect-capable boundaries: the operation\n * schemas it returns decide which mutation verbs a caller may spell, which is a\n * topology answer. So it hydrates and runs the structural relation-definition\n * gate once, for its own lifecycle, exactly as client construction does.\n */\nexport const getSchemas = <S extends Schema>(schema: S): SchemaProxy<S> => {\n return createSchemaRegistry(schema).proxy;\n};\n"],"mappings":"muEAwDA,MAAM,EAAa,aAwBb,GAAkB,IAAI,IAAI,CAAC,aAAc,aAAc,aAAa,CAAC,CAE3E,SAAS,EACP,EACA,EACA,EACA,EAC2E,CAE3E,IAAM,EAAWA,EAAO,EAAM,KAAK,MAAM,KAAQ,EAAE,CAC7C,EAAS,EAASC,GAAM,OAAO,CAAGA,EAAK,OAAS,IAAA,GAChD,EAAU,EAASA,GAAM,QAAQ,CAAGA,EAAK,QAAU,IAAA,GACnD,EAAO,EAASA,GAAM,KAAK,CAAGA,EAAK,KAAO,IAAA,GAI1C,EAA4C,EAAE,CAC9C,EAAa,GAAU,EACzB,EAAiB,EACrB,GAAI,IAAe,IAAA,GAAW,CAC5B,IAAM,EAAQ,EAAU,IAAI,EAAM,CAClC,IAAK,IAAMC,KAAO,OAAO,KAAK,EAAW,CAAE,CACzC,IAAM,EAAW,GAAO,IAAIA,EAAI,CAC1B,EAAQ,EAAWA,GACzB,GACE,CAAC,GACD,GAAqB,EAAS,EAC7B,IAAU,IAAQ,CAAC,EAAS,EAAM,CAEnC,SACF,IAAMC,EAAS,GAAW,EAAS,CAC7B,EAAY,IAAU,GAAO,IAAA,GAAY,EACzC,EAAQ,EAASH,EAAQ,EAAWG,EAAQ,EAAU,CACxD,IAAU,IAAA,KACd,EAAO,KAAK,CAACD,EAAK,EAAM,KAAK,CAAC,CAC1B,GAAW,UAAY,IAAA,IACzB,EAAM,KAAK,UAAU,KAAK,CAACA,EAAK,EAAM,KAAK,CAAC,CAC1C,EAAM,OAAS,IACjB,EAAiB,CAAE,GAAG,GAAiBA,GAAM,EAAM,KAAM,IAK/D,IAAM,EAAU,IAAI,IACpB,IAAK,GAAM,CAAC,EAAO,KAAU,EAAS,SAAS,CAC7C,EAAQ,IAAI,EAAM,KAAM,EAA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L,YACA,OACA,SACA,SACA,OACA,OACA,WACA,aACA,OACA,UACA,eACA,SACD,CCfH,MAAa,GAAgC,GACpC,GAAqB,EAAO,CAAC"}
@@ -1,4 +1,4 @@
1
- import { A as Extension, Co as VibORMError, O as EmptyFacts, S as AnyTarget, ko as DiagnosticDisclosure } from "./database-adapter-BGqvjeEy.mjs";
1
+ import { Fo as VibORMError, I as Extension, O as AnyTarget, P as EmptyFacts, Vo as DiagnosticDisclosure } from "./database-adapter-BMjJiBFm.mjs";
2
2
 
3
3
  //#region src/instrumentation/types.d.ts
4
4
 
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{a as t}from"./base-z-cH5ZBI.mjs";import{t as n}from"./extension-CGepsF-p.mjs";import{n as r,r as i,t as a}from"./unit-BhHbZyuJ.mjs";import{a as o,d as s,f as c,n as l,o as u,r as d,s as f,t as p,u as m}from"./unit-words-CT0yeqfZ.mjs";import{t as h}from"./version-CXGIA82S.mjs";import{C as g,D as _,E as v,S as y,T as b,_ as x,a as S,b as C,c as w,d as T,f as E,g as D,h as O,i as k,l as A,m as j,n as M,o as N,p as P,r as F,s as I,t as L,u as R,v as z,w as B,x as V,y as H}from"./spans-XDUFeTzC.mjs";const U=new Set([`bypass`,`hit`,`miss`,`revalidate`]),W=new Set([`cache-set-failed`,`error`,`fresh`,`stale`,`start`,`success`]);function presentLogMetadata(e){let{event:t,status:n}=e;return{...U.has(t)?{event:t}:{},...W.has(n)?{status:n}:{}}}function prettyLog(e){let t=e.timestamp.toISOString(),n=e.duration===void 0?``:`${e.duration}ms`,r=e.model?[e.model,e.operation].filter(Boolean).join(`.`):e.operation??``;switch(e.level){case`query`:console.log([`[QUERY]`,t,r||`query`,n].filter(Boolean).join(` `)),e.sql&&console.log(` ${e.sql}`),e.params?.length&&console.log(` params: ${JSON.stringify(e.params)}`);break;case`cache`:console.log(`[CACHE]`,t,typeof e.meta?.event==`string`?e.meta.event:`unknown`,typeof e.meta?.status==`string`?`(${e.meta.status})`:``);break;case`error`:console.error(`[ERROR]`,t,r,n),e.error&&console.error(` ${e.error.message}`),e.sql&&console.error(` ${e.sql}`);break}}function createLogger(e){let handlerOf=t=>e[t]??e.all;return Object.freeze({log(e){try{let t=handlerOf(e.level);if(!t)return;let n={level:e.level,timestamp:e.timestamp,duration:e.duration,model:e.model,operation:e.operation,correlationId:e.correlationId,sql:e.sql,params:e.params,error:e.error,meta:e.meta},defaultLog=()=>{try{prettyLog(n)}catch{}};t===!0?defaultLog():Promise.resolve(t(n,defaultLog)).catch(()=>void 0)}catch{}},isLevelEnabled(e){return handlerOf(e)!==void 0}})}const G={SpanStatusCode:{OK:1,ERROR:2}},K=h,q=new WeakSet;function createTracerWrapper(t={}){let{tracer:n}=t,r=Object.freeze((t.ignoreSpanTypes??[]).map(e=>typeof e==`string`?e:new RegExp(e.source,e.flags)));function traces$1(e){return!r.some(t=>typeof t==`string`?t===e:new RegExp(t.source,t.flags).test(e))}e(traces$1,`traces`);let i,a,o=n===void 0?import(`@opentelemetry/api`).then(e=>{i=e},()=>{i=null}):void 0;return Object.freeze({traces:traces$1,async startActiveSpan(e,t){if(n!==void 0)return traces$1(e.name)?runOnce(t,G,t=>n.startActiveSpan(e.name,n=>(setSpanAttributes(n,e.attributes??{}),t(n)))):t();if(i===void 0&&await o,!(i&&traces$1(e.name)))return t();let r,s;try{let t={...e.attributes},n=i.SpanKind.INTERNAL,o=e.root?i.ROOT_CONTEXT:i.context.active();a??=i.trace.getTracer(`viborm`,K),r=a.startSpan(e.name,{kind:n,attributes:t},o),s=i.trace.setSpan(o,r)}catch{return t()}let c=i;return runOnce(t,c,e=>c.context.with(s,()=>e(r)),r)}})}function runOnce(e,t,n,r){let i=new Set,a,o,settle=(e,n)=>{a=e,o=n;for(let r of i)endSpan(r,e,t,n)},s,c=!1,run=n=>{if(n!==void 0&&(i.add(n),a!==void 0&&endSpan(n,a,t,o)),s)return s;if(c)return Promise.reject(createTraceError());c=!0;try{return s=new Promise((t,r)=>{try{Promise.resolve(e(n)).then(e=>{settle(!1),t(e)},e=>{settle(!0,e),r(e)})}catch(e){settle(!0,e),r(e)}}),s}finally{c=!1}};try{Promise.resolve(n(run)).catch(ignoreRejection)}catch{}return run(r)}function endSpan(e,t,n,r){if(!q.has(e)){if(q.add(e),t){let t=r instanceof Error?r:{},i=typeof t.name==`string`?t.name:`Error`,{code:a}=t,o=t.meta?.providerSqlState;setSpanAttributes(e,{"error.type":i,...typeof a==`string`&&i!==`Error`?{"viborm.error.code":a}:{},...typeof o==`string`?{"db.response.sqlstate":o}:{}}),safely(()=>e.setStatus?.({code:n.SpanStatusCode.ERROR,message:`Operation failed`}));let s=createTraceError();s.name=i,safely(()=>e.recordException?.(s))}else safely(()=>e.setStatus?.({code:n.SpanStatusCode.OK}));safely(()=>e.end())}}function setSpanAttributes(e,t){for(let[n,r]of Object.entries(t))safely(()=>e?.setAttribute(n,r))}function safely(e){try{let t=e(),n=typeof t==`object`&&t||typeof t==`function`?Reflect.get(t,`then`):void 0;typeof n==`function`&&Reflect.apply(n,t,[void 0,ignoreRejection])}catch{}}function ignoreRejection(){}function createTraceError(){let e=Error(`Operation failed`);return e.stack=void 0,e}function createInstrumentationContext({tracing:e,logging:t}){let n=Object.freeze({tracing:e===!0||e===void 0?e:snapshotTracingConfig(e),logging:t===!0||t===void 0?t:snapshotLoggingConfig(t)});return Object.freeze({config:n,tracer:n.tracing&&createTracerWrapper(n.tracing===!0?{}:n.tracing),logger:n.logging&&createLogger(n.logging===!0?{all:!0}:n.logging),logged:new WeakSet})}function snapshotTracingConfig({includeParams:e,includeSql:t,ignoreSpanTypes:n,tracer:r}){return Object.freeze({includeParams:e===!0,includeSql:t===!0,ignoreSpanTypes:n,tracer:r})}function snapshotLoggingConfig({all:e,cache:t,error:n,query:r,includeParams:i,includeSql:a}){if(e||t||n||r)return Object.freeze({includeParams:i===!0,includeSql:a===!0,all:e,cache:t,error:n,query:r})}const J=/OrThrow$/;function createDriverAttributes(e){if(e===void 0)return{};let{dialect:t,driverName:n,namespace:r}=e;return{[P]:t,[N]:n,...r===void 0?{}:{[I]:r}}}function createCorrelationAttributes(e){return e?{[x]:e}:{}}function resolvedOperation(e){return e.operation?.replace(J,``)}const noteOf=e=>typeof e==`object`&&e?e:void 0,Y=new Set([v,b,_,g,B]),tracesAs=e=>!Y.has(e.span)||e.span===v&&e.root===!0;function notedAttributes(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&!n.startsWith(`db.query.`)&&(t[n]=r);return t}function createNotedSpanOptions(e,t){return{name:t.span,attributes:notedAttributes({...createDriverAttributes(t.database),...createCorrelationAttributes(p(e)),...t.attributes}),root:t.root===!0}}function presentNoteLog(e,t,n){let{error:r}=n;return{level:t,timestamp:new Date(n.at??Date.now()),model:n.model??e.model,operation:n.operation??resolvedOperation(e),correlationId:p(e),error:r instanceof Error?i(r):void 0,meta:n.meta===void 0?void 0:presentLogMetadata(n.meta)}}function createOperationSpanOptions(e){return{name:v,attributes:createUnitAttributes(e,s(e))}}function createUnitAttributes(e,t){let{operation:n}=e;return{...createDriverAttributes(l(e)),...t?{[S]:t}:{},...n?{[w]:n}:{},...createCorrelationAttributes(p(e))}}function createStatementSpanOptions(e,t,n,r){let{includeParams:i,includeSql:a}=channelOf(e),o=createUnitAttributes(t,t.model);if(a&&n!==void 0&&(o[T]=n),i)for(let[e,t]of(r??[]).entries())o[`${A}.${e}`]=typeof t==`string`?t:String(JSON.stringify(t));return{name:b,attributes:o}}function channelOf(e){return e&&e!==!0?e:{}}function createLifecycleSpanOptions(e,t){return{name:e,attributes:createUnitAttributes(t,t.model)}}function statementIndexOf(e){let n=t(e)?e.meta.statementIndex:void 0;return typeof n==`number`?n:void 0}function createStatementLogEvent(e,t,n,r,a,o){let s=channelOf(e),l=o===void 0?void 0:statementIndexOf(o),u=l===void 0?void 0:m(t)?.[l],d=u?.sql??c(t),f=u===void 0||l===void 0?a:batchMemberParameters(a,l);return{level:o===void 0?`query`:`error`,timestamp:new Date(n+r),duration:r,model:u===void 0?t.model:u.model,operation:u===void 0?t.operation:u.operation,correlationId:u===void 0?p(t):u.correlation,sql:s.includeSql?d:void 0,params:s.includeParams?[...f??[]]:void 0,error:o===void 0?void 0:i(o,{sql:s.includeSql,parameters:s.includeParams})}}function batchMemberParameters(e,t){let n=e?.[t];return Array.isArray(n)?n:void 0}const X=`viborm.instrumentation`,ignore=()=>void 0;function instrumentation(e){let t=createInstrumentationContext(e),{logging:i,tracing:o}=t.config,{diagnostics:s={}}=e,c=r({sql:s.includeSql,parameters:s.includeParams,providerDetails:s.includeProviderDetails,callsite:s.includeCallsite});return o===void 0&&i===void 0?n(X,c):n(X,a((e,n)=>observe(t,e,n)),c)}function observe(e,t,n){let r,once=()=>(r??=n(),r);return Promise.resolve(present(e,t,once)).then(ignore,ignore).then(()=>r===void 0?once().then(ignore):void 0)}function traces(e,t){return e.tracer?.traces(t)===!0}function logs(e,t){return e.logger?.isLevelEnabled(t)===!0}function present(e,t,n){switch(t.kind){case`operation`:return presentOperation(e,t,n);case`statement`:return presentStatement(e,t,n);case`transaction`:case`savepoint`:case`connection`:return presentLifecycle(e,t,n);case`batch`:return;default:return presentNoted(e,t,n)}}function spanned(e,t,n,r,a){let settle=e=>{let t=Date.now();return r().then(r=>{if(a?.(r,t,e),r.status===`failure`&&r.recovered!==!0)throw i(d(n))})};return e.tracer&&t?e.tracer.startActiveSpan(t,settle):settle()}function presentOperation(e,t,n){return spanned(e,traces(e,v)?createOperationSpanOptions(t):void 0,t,n,(n,r)=>{for(let n of o(t)){let r=noteOf(n);r?.log===`cache`&&log(e,t,r)}let i=d(t);n.status===`failure`&&i instanceof Error&&logs(e,`error`)&&!e.logged.has(u(i))&&e.logger?.log({...presentNoteLog(t,`error`,{at:r+n.duration,error:i}),duration:n.duration})})}function presentStatement(e,t,n){let r=traces(e,b),i=logs(e,`query`),a=logs(e,`error`);if(!(r||i||a))return;let{logging:o,tracing:s}=e.config,l=(i||a)&&channelOf(o).includeParams||r&&channelOf(s).includeParams?f(t):void 0,p=Date.now();return spanned(e,r?createStatementSpanOptions(s,t,c(t),l):void 0,t,n,({duration:n,recovered:r,status:s})=>{let c=d(t),f=s===`failure`&&c instanceof Error;r===!0||!(f?a:s===`success`&&i)||(f&&e.logged.add(u(c)),e.logger?.log(createStatementLogEvent(o,t,p,n,l,f?c:void 0)))})}function presentLifecycle(e,t,n){let r=t.kind===`connection`?t.operation===`$disconnect`||t.operation===`disconnect`?B:g:_;if(traces(e,r))return spanned(e,createLifecycleSpanOptions(r,t),t,n)}function log(e,t,n){n?.log!==void 0&&logs(e,n.log)&&e.logger?.log(presentNoteLog(t,n.log,n))}function presentNoted(e,t,n){let r=o(t).length,i;for(let n of o(t)){let r=noteOf(n);i===void 0&&r?.span!==void 0&&(i={...r,span:r.span}),log(e,t,r)}return spanned(e,i!==void 0&&e.tracer!==void 0&&tracesAs(i)?createNotedSpanOptions(t,i):void 0,t,n,(n,i,a)=>{for(let n of o(t).slice(r)){let r=noteOf(n);r?.attributes!==void 0&&setSpanAttributes(a,notedAttributes(r.attributes)),log(e,t,r)}})}export{L as ATTR_CACHE_DRIVER,M as ATTR_CACHE_RESULT,F as ATTR_CACHE_TTL,k as ATTR_DB_BATCH_SIZE,S as ATTR_DB_COLLECTION,N as ATTR_DB_DRIVER,I as ATTR_DB_NAMESPACE,w as ATTR_DB_OPERATION_NAME,A as ATTR_DB_QUERY_PARAMETER_PREFIX,R as ATTR_DB_QUERY_SUMMARY,T as ATTR_DB_QUERY_TEXT,E as ATTR_DB_ROWS_RETURNED,P as ATTR_DB_SYSTEM,j as ATTR_ERROR_TYPE,O as ATTR_SERVER_ADDRESS,D as ATTR_SERVER_PORT,x as ATTR_VIBORM_CORRELATION_ID,z as SPAN_CACHE_CLEAR,H as SPAN_CACHE_DELETE,C as SPAN_CACHE_GET,V as SPAN_CACHE_INVALIDATE,y as SPAN_CACHE_SET,g as SPAN_CONNECT,B as SPAN_DISCONNECT,b as SPAN_EXECUTE,v as SPAN_OPERATION,_ as SPAN_TRANSACTION,instrumentation};
1
+ import{a as e}from"./base-17NSFtrA.mjs";import{t}from"./extension-Dh1ddrlA.mjs";import{n,r,t as i}from"./unit-DUPX5Sdd.mjs";import{a,d as o,f as s,n as c,o as l,r as u,s as d,t as f,u as p}from"./unit-words-BXpLpyr2.mjs";import{t as m}from"./version-0BDwfy7C.mjs";import{C as h,D as g,E as _,S as v,T as y,_ as b,a as x,b as S,c as C,d as w,f as ee,g as te,h as ne,i as re,l as T,m as E,n as D,o as O,p as k,r as ie,s as A,t as ae,u as oe,v as se,w as j,x as ce,y as le}from"./spans-DwDXMvyd.mjs";const ue=new Set([`bypass`,`hit`,`miss`,`revalidate`]),de=new Set([`cache-set-failed`,`error`,`fresh`,`stale`,`start`,`success`]);function fe(e){let{event:t,status:n}=e;return{...ue.has(t)?{event:t}:{},...de.has(n)?{status:n}:{}}}function pe(e){let t=e.timestamp.toISOString(),n=e.duration===void 0?``:`${e.duration}ms`,r=e.model?[e.model,e.operation].filter(Boolean).join(`.`):e.operation??``;switch(e.level){case`query`:console.log([`[QUERY]`,t,r||`query`,n].filter(Boolean).join(` `)),e.sql&&console.log(` ${e.sql}`),e.params?.length&&console.log(` params: ${JSON.stringify(e.params)}`);break;case`cache`:console.log(`[CACHE]`,t,typeof e.meta?.event==`string`?e.meta.event:`unknown`,typeof e.meta?.status==`string`?`(${e.meta.status})`:``);break;case`error`:console.error(`[ERROR]`,t,r,n),e.error&&console.error(` ${e.error.message}`),e.sql&&console.error(` ${e.sql}`);break}}function me(e){let t=t=>e[t]??e.all;return Object.freeze({log(e){try{let n=t(e.level);if(!n)return;let r={level:e.level,timestamp:e.timestamp,duration:e.duration,model:e.model,operation:e.operation,correlationId:e.correlationId,sql:e.sql,params:e.params,error:e.error,meta:e.meta},i=()=>{try{pe(r)}catch{}};n===!0?i():Promise.resolve(n(r,i)).catch(()=>void 0)}catch{}},qy(e){return t(e)!==void 0}})}const he={SpanStatusCode:{OK:1,ERROR:2}},ge=m,M=new WeakSet;function N(e={}){let{tracer:t}=e,n=Object.freeze((e.ignoreSpanTypes??[]).map(e=>typeof e==`string`?e:new RegExp(e.source,e.flags)));function r(e){return!n.some(t=>typeof t==`string`?t===e:new RegExp(t.source,t.flags).test(e))}let i,a,o=t===void 0?import(`@opentelemetry/api`).then(e=>{i=e},()=>{i=null}):void 0;return Object.freeze({traces:r,async startActiveSpan(e,n){if(t!==void 0)return r(e.name)?P(n,he,n=>t.startActiveSpan(e.name,t=>(I(t,e.attributes??{}),n(t)))):n();if(i===void 0&&await o,!(i&&r(e.name)))return n();let s,c;try{let t={...e.attributes},n=i.SpanKind.INTERNAL,r=e.root?i.ROOT_CONTEXT:i.context.active();a??=i.trace.getTracer(`viborm`,ge),s=a.startSpan(e.name,{kind:n,attributes:t},r),c=i.trace.setSpan(r,s)}catch{return n()}let l=i;return P(n,l,e=>l.context.with(c,()=>e(s)),s)}})}function P(e,t,n,r){let i=new Set,a,o,s=(e,n)=>{a=e,o=n;for(let r of i)F(r,e,t,n)},c,l=!1,u=n=>{if(n!==void 0&&(i.add(n),a!==void 0&&F(n,a,t,o)),c)return c;if(l)return Promise.reject(z());l=!0;try{return c=new Promise((t,r)=>{try{Promise.resolve(e(n)).then(e=>{s(!1),t(e)},e=>{s(!0,e),r(e)})}catch(e){s(!0,e),r(e)}}),c}finally{l=!1}};try{Promise.resolve(n(u)).catch(R)}catch{}return u(r)}function F(e,t,n,r){if(!M.has(e)){if(M.add(e),t){let t=r instanceof Error?r:{},i=typeof t.name==`string`?t.name:`Error`,{code:a}=t,o=t.meta?.providerSqlState;I(e,{"error.type":i,...typeof a==`string`&&i!==`Error`?{"viborm.error.code":a}:{},...typeof o==`string`?{"db.response.sqlstate":o}:{}}),L(()=>e.setStatus?.({code:n.SpanStatusCode.ERROR,message:`Operation failed`}));let s=z();s.name=i,L(()=>e.recordException?.(s))}else L(()=>e.setStatus?.({code:n.SpanStatusCode.OK}));L(()=>e.end())}}function I(e,t){for(let[n,r]of Object.entries(t))L(()=>e?.setAttribute(n,r))}function L(e){try{let t=e(),n=typeof t==`object`&&t||typeof t==`function`?Reflect.get(t,`then`):void 0;typeof n==`function`&&Reflect.apply(n,t,[void 0,R])}catch{}}function R(){}function z(){let e=Error(`Operation failed`);return e.stack=void 0,e}function _e({tracing:e,logging:t}){let n=Object.freeze({tracing:e===!0||e===void 0?e:ve(e),logging:t===!0||t===void 0?t:ye(t)});return Object.freeze({config:n,tracer:n.tracing&&N(n.tracing===!0?{}:n.tracing),logger:n.logging&&me(n.logging===!0?{all:!0}:n.logging),l8:new WeakSet})}function ve({includeParams:e,includeSql:t,ignoreSpanTypes:n,tracer:r}){return Object.freeze({includeParams:e===!0,includeSql:t===!0,ignoreSpanTypes:n,tracer:r})}function ye({all:e,cache:t,error:n,query:r,includeParams:i,includeSql:a}){if(e||t||n||r)return Object.freeze({includeParams:i===!0,includeSql:a===!0,all:e,cache:t,error:n,query:r})}const be=/OrThrow$/;function B(e){if(e===void 0)return{};let{dialect:t,driverName:n,namespace:r}=e;return{[k]:t,[O]:n,...r===void 0?{}:{[A]:r}}}function V(e){return e?{[b]:e}:{}}function xe(e){return e.operation?.replace(be,``)}const H=e=>typeof e==`object`&&e?e:void 0,Se=new Set([_,y,g,h,j]),Ce=e=>!Se.has(e.span)||e.span===_&&e.root===!0;function U(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&!n.startsWith(`db.query.`)&&(t[n]=r);return t}function we(e,t){return{name:t.span,attributes:U({...B(t.database),...V(f(e)),...t.attributes}),root:t.root===!0}}function W(e,t,n){let{error:i}=n;return{level:t,timestamp:new Date(n.at??Date.now()),model:n.model??e.model,operation:n.operation??xe(e),correlationId:f(e),error:i instanceof Error?r(i):void 0,meta:n.meta===void 0?void 0:fe(n.meta)}}function Te(e){return{name:_,attributes:G(e,o(e))}}function G(e,t){let{operation:n}=e;return{...B(c(e)),...t?{[x]:t}:{},...n?{[C]:n}:{},...V(f(e))}}function Ee(e,t,n,r){let{includeParams:i,includeSql:a}=K(e),o=G(t,t.model);if(a&&n!==void 0&&(o[w]=n),i)for(let[e,t]of(r??[]).entries())o[`${T}.${e}`]=typeof t==`string`?t:String(JSON.stringify(t));return{name:y,attributes:o}}function K(e){return e&&e!==!0?e:{}}function De(e,t){return{name:e,attributes:G(t,t.model)}}function Oe(t){let n=e(t)?t.meta.statementIndex:void 0;return typeof n==`number`?n:void 0}function ke(e,t,n,i,a,o){let c=K(e),l=o===void 0?void 0:Oe(o),u=l===void 0?void 0:p(t)?.[l],d=u?.sql??s(t),m=u===void 0||l===void 0?a:Ae(a,l);return{level:o===void 0?`query`:`error`,timestamp:new Date(n+i),duration:i,model:u===void 0?t.model:u.model,operation:u===void 0?t.operation:u.operation,correlationId:u===void 0?f(t):u.correlation,sql:c.includeSql?d:void 0,params:c.includeParams?[...m??[]]:void 0,error:o===void 0?void 0:r(o,{sql:c.includeSql,parameters:c.includeParams})}}function Ae(e,t){let n=e?.[t];return Array.isArray(n)?n:void 0}const q=`viborm.instrumentation`,J=()=>void 0;function je(e){let r=_e(e),{logging:a,tracing:o}=r.config,{diagnostics:s={}}=e,c=n({sql:s.includeSql,parameters:s.includeParams,providerDetails:s.includeProviderDetails,callsite:s.includeCallsite});return o===void 0&&a===void 0?t(q,c):t(q,i((e,t)=>Y(r,e,t)),c)}function Y(e,t,n){let r,i=()=>(r??=n(),r);return Promise.resolve(Me(e,t,i)).then(J,J).then(()=>r===void 0?i().then(J):void 0)}function X(e,t){return e.tracer?.traces(t)===!0}function Z(e,t){return e.logger?.qy(t)===!0}function Me(e,t,n){switch(t.kind){case`operation`:return Ne(e,t,n);case`statement`:return Pe(e,t,n);case`transaction`:case`savepoint`:case`connection`:return Fe(e,t,n);case`batch`:return;default:return Ie(e,t,n)}}function Q(e,t,n,i,a){let o=e=>{let t=Date.now();return i().then(i=>{if(a?.(i,t,e),i.status===`failure`&&i.recovered!==!0)throw r(u(n))})};return e.tracer&&t?e.tracer.startActiveSpan(t,o):o()}function Ne(e,t,n){return Q(e,X(e,_)?Te(t):void 0,t,n,(n,r)=>{for(let n of a(t)){let r=H(n);r?.log===`cache`&&$(e,t,r)}let i=u(t);n.status===`failure`&&i instanceof Error&&Z(e,`error`)&&!e.l8.has(l(i))&&e.logger?.log({...W(t,`error`,{at:r+n.duration,error:i}),duration:n.duration})})}function Pe(e,t,n){let r=X(e,y),i=Z(e,`query`),a=Z(e,`error`);if(!(r||i||a))return;let{logging:o,tracing:c}=e.config,f=(i||a)&&K(o).includeParams||r&&K(c).includeParams?d(t):void 0,p=Date.now();return Q(e,r?Ee(c,t,s(t),f):void 0,t,n,({duration:n,recovered:r,status:s})=>{let c=u(t),d=s===`failure`&&c instanceof Error;r===!0||!(d?a:s===`success`&&i)||(d&&e.l8.add(l(c)),e.logger?.log(ke(o,t,p,n,f,d?c:void 0)))})}function Fe(e,t,n){let r=t.kind===`connection`?t.operation===`$disconnect`||t.operation===`disconnect`?j:h:g;if(X(e,r))return Q(e,De(r,t),t,n)}function $(e,t,n){n?.log!==void 0&&Z(e,n.log)&&e.logger?.log(W(t,n.log,n))}function Ie(e,t,n){let r=a(t).length,i;for(let n of a(t)){let r=H(n);i===void 0&&r?.span!==void 0&&(i={...r,span:r.span}),$(e,t,r)}return Q(e,i!==void 0&&e.tracer!==void 0&&Ce(i)?we(t,i):void 0,t,n,(n,i,o)=>{for(let n of a(t).slice(r)){let r=H(n);r?.attributes!==void 0&&I(o,U(r.attributes)),$(e,t,r)}})}export{ae as ATTR_CACHE_DRIVER,D as ATTR_CACHE_RESULT,ie as ATTR_CACHE_TTL,re as ATTR_DB_BATCH_SIZE,x as ATTR_DB_COLLECTION,O as ATTR_DB_DRIVER,A as ATTR_DB_NAMESPACE,C as ATTR_DB_OPERATION_NAME,T as ATTR_DB_QUERY_PARAMETER_PREFIX,oe as ATTR_DB_QUERY_SUMMARY,w as ATTR_DB_QUERY_TEXT,ee as ATTR_DB_ROWS_RETURNED,k as ATTR_DB_SYSTEM,E as ATTR_ERROR_TYPE,ne as ATTR_SERVER_ADDRESS,te as ATTR_SERVER_PORT,b as ATTR_VIBORM_CORRELATION_ID,se as SPAN_CACHE_CLEAR,le as SPAN_CACHE_DELETE,S as SPAN_CACHE_GET,ce as SPAN_CACHE_INVALIDATE,v as SPAN_CACHE_SET,h as SPAN_CONNECT,j as SPAN_DISCONNECT,y as SPAN_EXECUTE,_ as SPAN_OPERATION,g as SPAN_TRANSACTION,je as instrumentation};
2
2
  //# sourceMappingURL=instrumentation.mjs.map