viborm 1.13.0 → 1.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (436) hide show
  1. package/README.md +6 -4
  2. package/dist/{adapter-internals-DZO1WI67.mjs → adapter-internals-DOqI8IlQ.mjs} +2 -2
  3. package/dist/adapter-internals-DOqI8IlQ.mjs.map +1 -0
  4. package/dist/adapter-namespace-DaRiTIIf.mjs +2 -0
  5. package/dist/{adapter-namespace-C9RM19_J.mjs.map → adapter-namespace-DaRiTIIf.mjs.map} +1 -1
  6. package/dist/{adapter-result-parser-Bz3WtMBa.mjs → adapter-result-parser-3WP82Cm-.mjs} +1 -1
  7. package/dist/{adapter-result-parser-Bz3WtMBa.mjs.map → adapter-result-parser-3WP82Cm-.mjs.map} +1 -1
  8. package/dist/adapters.d.mts +755 -1
  9. package/dist/adapters.mjs +1 -1
  10. package/dist/args-764KdWMr.mjs +2 -0
  11. package/dist/args-764KdWMr.mjs.map +1 -0
  12. package/dist/{array-literal-DfgmVxKI.mjs → array-literal-DHinAnVs.mjs} +1 -1
  13. package/dist/{array-literal-DfgmVxKI.mjs.map → array-literal-DHinAnVs.mjs.map} +1 -1
  14. package/dist/async-dispose-d96wFNu6.mjs +2 -0
  15. package/dist/async-dispose-d96wFNu6.mjs.map +1 -0
  16. package/dist/base-z-cH5ZBI.mjs +2 -0
  17. package/dist/base-z-cH5ZBI.mjs.map +1 -0
  18. package/dist/{batch-refs-DShoaHb7.mjs → batch-refs-C-gx7A4-.mjs} +2 -2
  19. package/dist/{batch-refs-DShoaHb7.mjs.map → batch-refs-C-gx7A4-.mjs.map} +1 -1
  20. package/dist/bind-parameter-capacity-BMD-bxMO.mjs +2 -0
  21. package/dist/bind-parameter-capacity-BMD-bxMO.mjs.map +1 -0
  22. package/dist/bun-sql.d.mts +1 -1
  23. package/dist/bun-sql.mjs +1 -1
  24. package/dist/bun-sql.mjs.map +1 -1
  25. package/dist/bun-sqlite.d.mts +1 -1
  26. package/dist/bun-sqlite.mjs +1 -1
  27. package/dist/bun-sqlite.mjs.map +1 -1
  28. package/dist/cache/cloudflare-kv.d.mts +1 -1
  29. package/dist/cache/cloudflare-kv.mjs +1 -1
  30. package/dist/cache/cloudflare-kv.mjs.map +1 -1
  31. package/dist/cache/memory.d.mts +2 -2
  32. package/dist/cache/memory.mjs +1 -1
  33. package/dist/cache/memory.mjs.map +1 -1
  34. package/dist/cache.d.mts +58 -4
  35. package/dist/cache.mjs +1 -1
  36. package/dist/cache.mjs.map +1 -1
  37. package/dist/call-Cz8XUmrl.mjs +2 -0
  38. package/dist/call-Cz8XUmrl.mjs.map +1 -0
  39. package/dist/{canonical-json-B6J5VbLv.mjs → canonical-json-Bl-fKFF_.mjs} +2 -2
  40. package/dist/{canonical-json-B6J5VbLv.mjs.map → canonical-json-Bl-fKFF_.mjs.map} +1 -1
  41. package/dist/cli.mjs +7 -5
  42. package/dist/cli.mjs.map +1 -1
  43. package/dist/{client-Dx-6NncH.d.mts → client-D1shn5AL.d.mts} +22 -3
  44. package/dist/client-DRpX3-vw.mjs +2 -0
  45. package/dist/client-DRpX3-vw.mjs.map +1 -0
  46. package/dist/client-DzXpmSNi.mjs +9 -0
  47. package/dist/client-DzXpmSNi.mjs.map +1 -0
  48. package/dist/client.d.mts +3 -2
  49. package/dist/client.mjs +2 -1
  50. package/dist/client.mjs.map +1 -0
  51. package/dist/config.d.mts +2 -2
  52. package/dist/config.mjs +1 -1
  53. package/dist/confine-DqFBTUw6.mjs +2 -0
  54. package/dist/confine-DqFBTUw6.mjs.map +1 -0
  55. package/dist/coordination-6qZHx_kl.mjs +2 -0
  56. package/dist/coordination-6qZHx_kl.mjs.map +1 -0
  57. package/dist/{current-nScH-oH5.mjs → current-DBTlPsQg.mjs} +1 -1
  58. package/dist/{current-nScH-oH5.mjs.map → current-DBTlPsQg.mjs.map} +1 -1
  59. package/dist/d1.d.mts +3 -1
  60. package/dist/d1.mjs +1 -1
  61. package/dist/d1.mjs.map +1 -1
  62. package/dist/{index-B8MMx5Al.d.mts → database-adapter-BD_htd5h.d.mts} +9039 -9523
  63. package/dist/datetime-physical-codec-Dj-APo9f.mjs +2 -0
  64. package/dist/{datetime-physical-codec-kE6fh5zZ.mjs.map → datetime-physical-codec-Dj-APo9f.mjs.map} +1 -1
  65. package/dist/defaults-DwOHWI_M.mjs +2 -0
  66. package/dist/defaults-DwOHWI_M.mjs.map +1 -0
  67. package/dist/document-rMfLKZP5.d.mts +288 -0
  68. package/dist/driver-BGVcgnIX.mjs +2 -0
  69. package/dist/driver-BGVcgnIX.mjs.map +1 -0
  70. package/dist/driver-BIXhOH2_.mjs +2 -0
  71. package/dist/driver-BIXhOH2_.mjs.map +1 -0
  72. package/dist/driver-CH9qAuft.d.mts +235 -0
  73. package/dist/driver-diagnostics-DW9NdckJ.mjs +2 -0
  74. package/dist/driver-diagnostics-DW9NdckJ.mjs.map +1 -0
  75. package/dist/driver.d.mts +2 -2
  76. package/dist/driver.mjs +1 -1
  77. package/dist/durable-object.d.mts +58 -0
  78. package/dist/durable-object.mjs +3 -0
  79. package/dist/durable-object.mjs.map +1 -0
  80. package/dist/error-mapping-B1-IWkCQ.mjs +2 -0
  81. package/dist/error-mapping-B1-IWkCQ.mjs.map +1 -0
  82. package/dist/every-KV5yuSVT.mjs +2 -0
  83. package/dist/every-KV5yuSVT.mjs.map +1 -0
  84. package/dist/execution-context-BXpcbyPe.mjs +2 -0
  85. package/dist/execution-context-BXpcbyPe.mjs.map +1 -0
  86. package/dist/exports-nYDS0SZ7.d.mts +47 -0
  87. package/dist/extension-CGepsF-p.mjs +2 -0
  88. package/dist/extension-CGepsF-p.mjs.map +1 -0
  89. package/dist/{fs-estate-Bfy9RFvT.mjs → fs-estate-D1Nsg9G1.mjs} +2 -2
  90. package/dist/{fs-estate-Bfy9RFvT.mjs.map → fs-estate-D1Nsg9G1.mjs.map} +1 -1
  91. package/dist/geo-area-codec-mHrM3b9A.mjs +2 -0
  92. package/dist/{geo-area-codec-B3QtKij8.mjs.map → geo-area-codec-mHrM3b9A.mjs.map} +1 -1
  93. package/dist/hydration-A3zffFWP.mjs +2 -0
  94. package/dist/{hydration-Dd2H4EyY.mjs.map → hydration-A3zffFWP.mjs.map} +1 -1
  95. package/dist/identifier-conversion-DHYPTgzr.mjs +2 -0
  96. package/dist/{identifier-conversion-771tvRzd.mjs.map → identifier-conversion-DHYPTgzr.mjs.map} +1 -1
  97. package/dist/{identifiers-DLcLFNim.mjs → identifiers-s00pGES8.mjs} +1 -1
  98. package/dist/{identifiers-DLcLFNim.mjs.map → identifiers-s00pGES8.mjs.map} +1 -1
  99. package/dist/identity-CtW15WlB.mjs +2 -0
  100. package/dist/identity-CtW15WlB.mjs.map +1 -0
  101. package/dist/index.d.mts +3 -3
  102. package/dist/index.mjs +1 -1
  103. package/dist/index.mjs.map +1 -1
  104. package/dist/instrumentation.d.mts +50 -18
  105. package/dist/instrumentation.mjs +1 -1
  106. package/dist/instrumentation.mjs.map +1 -1
  107. package/dist/introspect-DD_5FEl0.mjs +2 -0
  108. package/dist/introspect-DD_5FEl0.mjs.map +1 -0
  109. package/dist/json-DgMc8-GU.mjs +2 -0
  110. package/dist/json-DgMc8-GU.mjs.map +1 -0
  111. package/dist/{json-number-ChtP7ZeY.mjs → json-number-AI-SdUUn.mjs} +1 -1
  112. package/dist/{json-number-ChtP7ZeY.mjs.map → json-number-AI-SdUUn.mjs.map} +1 -1
  113. package/dist/json-parameter-oQ8nGaKr.mjs +2 -0
  114. package/dist/json-parameter-oQ8nGaKr.mjs.map +1 -0
  115. package/dist/judge-words-CzUyXtJ6.mjs +2 -0
  116. package/dist/judge-words-CzUyXtJ6.mjs.map +1 -0
  117. package/dist/key-hxFFCKed.mjs +2 -0
  118. package/dist/key-hxFFCKed.mjs.map +1 -0
  119. package/dist/keys-BQxM4c_a.mjs +2 -0
  120. package/dist/keys-BQxM4c_a.mjs.map +1 -0
  121. package/dist/libsql-DuGR904j.mjs +3 -0
  122. package/dist/libsql-DuGR904j.mjs.map +1 -0
  123. package/dist/libsql.d.mts +1 -1
  124. package/dist/libsql.mjs +1 -1
  125. package/dist/libsql.mjs.map +1 -1
  126. package/dist/light-BkJe3-yW.mjs +2 -0
  127. package/dist/light-BkJe3-yW.mjs.map +1 -0
  128. package/dist/memory-G4cSuc6A.mjs +2 -0
  129. package/dist/{memory-CsRVfZdT.mjs.map → memory-G4cSuc6A.mjs.map} +1 -1
  130. package/dist/methods-part-ZY0f2AV_.mjs +2 -0
  131. package/dist/methods-part-ZY0f2AV_.mjs.map +1 -0
  132. package/dist/migrations/mysql.d.mts +5 -5
  133. package/dist/migrations/mysql.mjs +1 -1
  134. package/dist/migrations/mysql.mjs.map +1 -1
  135. package/dist/migrations/postgres.d.mts +5 -5
  136. package/dist/migrations/postgres.mjs +1 -1
  137. package/dist/migrations/postgres.mjs.map +1 -1
  138. package/dist/migrations/snowflake.d.mts +6 -0
  139. package/dist/migrations/snowflake.mjs +2 -0
  140. package/dist/migrations/snowflake.mjs.map +1 -0
  141. package/dist/migrations/sqlite.d.mts +5 -5
  142. package/dist/migrations/sqlite.mjs +1 -1
  143. package/dist/migrations/sqlite.mjs.map +1 -1
  144. package/dist/migrations/storage/durable-object.d.mts +1 -1
  145. package/dist/migrations/storage/durable-object.mjs +1 -1
  146. package/dist/migrations/storage/fs.d.mts +1 -1
  147. package/dist/migrations/storage/fs.mjs +1 -1
  148. package/dist/migrations/storage/r2.d.mts +1 -1
  149. package/dist/migrations/storage/r2.mjs +1 -1
  150. package/dist/migrations/surrealdb.d.mts +5 -5
  151. package/dist/migrations/surrealdb.mjs +1 -1
  152. package/dist/migrations/surrealdb.mjs.map +1 -1
  153. package/dist/migrations/tenant.d.mts +3 -3
  154. package/dist/migrations/tenant.mjs +1 -1
  155. package/dist/migrations/tenant.mjs.map +1 -1
  156. package/dist/migrations-BMiRjR-N.mjs +2 -0
  157. package/dist/{migrations-OE5D32qo.mjs.map → migrations-BMiRjR-N.mjs.map} +1 -1
  158. package/dist/migrations.d.mts +5 -5
  159. package/dist/migrations.mjs +1 -1
  160. package/dist/migrations.mjs.map +1 -1
  161. package/dist/mysql-BNXWfTOo.mjs +100 -0
  162. package/dist/mysql-BNXWfTOo.mjs.map +1 -0
  163. package/dist/mysql-adapter-C69j1sKh.mjs +2 -0
  164. package/dist/mysql-adapter-C69j1sKh.mjs.map +1 -0
  165. package/dist/mysql2.d.mts +1 -1
  166. package/dist/mysql2.mjs +1 -1
  167. package/dist/mysql2.mjs.map +1 -1
  168. package/dist/native-types-DgjMUikz.mjs +2 -0
  169. package/dist/native-types-DgjMUikz.mjs.map +1 -0
  170. package/dist/neon-http.d.mts +1 -1
  171. package/dist/neon-http.mjs +1 -1
  172. package/dist/neon-http.mjs.map +1 -1
  173. package/dist/normalized-result-B8pifWS0.mjs +2 -0
  174. package/dist/normalized-result-B8pifWS0.mjs.map +1 -0
  175. package/dist/{object-store-DlGfGCb4.d.mts → object-store-0zc3XYcO.d.mts} +4 -4
  176. package/dist/{object-store-DdKoB-lN.mjs → object-store-DS0F0yZX.mjs} +2 -2
  177. package/dist/{object-store-DdKoB-lN.mjs.map → object-store-DS0F0yZX.mjs.map} +1 -1
  178. package/dist/on-ylYaKuRu.mjs +2 -0
  179. package/dist/on-ylYaKuRu.mjs.map +1 -0
  180. package/dist/on.d.mts +12 -19
  181. package/dist/on.mjs +1 -1
  182. package/dist/on.mjs.map +1 -1
  183. package/dist/ordering/keys.d.mts +37 -0
  184. package/dist/ordering/keys.mjs +1 -0
  185. package/dist/ordering.d.mts +85 -85
  186. package/dist/ordering.mjs +4 -4
  187. package/dist/ordering.mjs.map +1 -1
  188. package/dist/pending-operation-C_eOFOBE.mjs +2 -0
  189. package/dist/pending-operation-C_eOFOBE.mjs.map +1 -0
  190. package/dist/permissions.d.mts +88 -147
  191. package/dist/permissions.mjs +1 -1
  192. package/dist/permissions.mjs.map +1 -1
  193. package/dist/pg.d.mts +1 -1
  194. package/dist/pg.mjs +1 -1
  195. package/dist/pg.mjs.map +1 -1
  196. package/dist/pglite.d.mts +1 -1
  197. package/dist/pglite.mjs +1 -1
  198. package/dist/pglite.mjs.map +1 -1
  199. package/dist/physical-CeE2nYmI.mjs +2 -0
  200. package/dist/{physical-CjG29tya.mjs.map → physical-CeE2nYmI.mjs.map} +1 -1
  201. package/dist/pinned-session-DCoAZDOz.mjs +2 -0
  202. package/dist/{pinned-session-De2rDjdO.mjs.map → pinned-session-DCoAZDOz.mjs.map} +1 -1
  203. package/dist/planetscale.d.mts +1 -1
  204. package/dist/planetscale.mjs +1 -1
  205. package/dist/planetscale.mjs.map +1 -1
  206. package/dist/{planner-DUjM5jQk.d.mts → planner-uYQS0hif.d.mts} +12 -1
  207. package/dist/{postgres-V7noUFbG.mjs → postgres-CDdh5dSP.mjs} +33 -23
  208. package/dist/postgres-CDdh5dSP.mjs.map +1 -0
  209. package/dist/postgres-adapter-Dlr3ZWd7.mjs +2 -0
  210. package/dist/postgres-adapter-Dlr3ZWd7.mjs.map +1 -0
  211. package/dist/postgres-adapter-axapXX8d.mjs +2 -0
  212. package/dist/{postgres-adapter-CvLB764t.mjs.map → postgres-adapter-axapXX8d.mjs.map} +1 -1
  213. package/dist/{postgres-result-CJ8C5cck.mjs → postgres-result-DF6DmW3r.mjs} +2 -2
  214. package/dist/{postgres-result-CJ8C5cck.mjs.map → postgres-result-DF6DmW3r.mjs.map} +1 -1
  215. package/dist/postgres.d.mts +1 -1
  216. package/dist/postgres.mjs +1 -1
  217. package/dist/postgres.mjs.map +1 -1
  218. package/dist/provider-limits-Ccsb8PTb.mjs +2 -0
  219. package/dist/provider-limits-Ccsb8PTb.mjs.map +1 -0
  220. package/dist/provider-parameter-snapshot-BikrgKqI.mjs +2 -0
  221. package/dist/provider-parameter-snapshot-BikrgKqI.mjs.map +1 -0
  222. package/dist/query-BZVHfA0s.mjs +2 -0
  223. package/dist/query-BZVHfA0s.mjs.map +1 -0
  224. package/dist/query-inspection-BoG-yAln.mjs +2 -0
  225. package/dist/query-inspection-BoG-yAln.mjs.map +1 -0
  226. package/dist/raw-Dyq6Y6UX.mjs +2 -0
  227. package/dist/raw-Dyq6Y6UX.mjs.map +1 -0
  228. package/dist/{relation-bound-C02WchLT.mjs → relation-bound-ku_cMdye.mjs} +1 -1
  229. package/dist/{relation-bound-C02WchLT.mjs.map → relation-bound-ku_cMdye.mjs.map} +1 -1
  230. package/dist/{result-parsing-Bj0gVF-R.mjs → result-parsing-B0Y4KGDT.mjs} +1 -1
  231. package/dist/{result-parsing-Bj0gVF-R.mjs.map → result-parsing-B0Y4KGDT.mjs.map} +1 -1
  232. package/dist/routed-operations-wytpbYKv.mjs +2 -0
  233. package/dist/routed-operations-wytpbYKv.mjs.map +1 -0
  234. package/dist/rule-words-ZIGm7cDm.mjs +2 -0
  235. package/dist/rule-words-ZIGm7cDm.mjs.map +1 -0
  236. package/dist/scalar-BHCh7aUz.mjs +4 -0
  237. package/dist/scalar-BHCh7aUz.mjs.map +1 -0
  238. package/dist/schema/introspect.d.mts +97 -0
  239. package/dist/schema/introspect.mjs +1 -0
  240. package/dist/schema/json.d.mts +3 -278
  241. package/dist/schema/json.mjs +1 -2
  242. package/dist/schema-BYA-_bpk.mjs +2 -0
  243. package/dist/schema-BYA-_bpk.mjs.map +1 -0
  244. package/dist/schema-CFIaebgi.mjs +2 -0
  245. package/dist/{schema-DKL7GSu7.mjs.map → schema-CFIaebgi.mjs.map} +1 -1
  246. package/dist/schema-introspection-D0f8cti4.mjs +6 -0
  247. package/dist/{schema-introspection-BogU9kCO.mjs.map → schema-introspection-D0f8cti4.mjs.map} +1 -1
  248. package/dist/schema.d.mts +1 -1
  249. package/dist/schema.mjs +1 -1
  250. package/dist/{select-assembly-BL9BG6oR.mjs → select-assembly-DVI7d3tf.mjs} +2 -2
  251. package/dist/{select-assembly-BL9BG6oR.mjs.map → select-assembly-DVI7d3tf.mjs.map} +1 -1
  252. package/dist/serializer-rBq3v1xr.mjs +51 -0
  253. package/dist/serializer-rBq3v1xr.mjs.map +1 -0
  254. package/dist/settle-1cy5x_52.mjs +2 -0
  255. package/dist/settle-1cy5x_52.mjs.map +1 -0
  256. package/dist/settled-BjyuA76m.mjs +2 -0
  257. package/dist/settled-BjyuA76m.mjs.map +1 -0
  258. package/dist/snowflake-UOCC820W.mjs +2 -0
  259. package/dist/snowflake-UOCC820W.mjs.map +1 -0
  260. package/dist/snowflake.d.mts +473 -0
  261. package/dist/snowflake.mjs +3 -0
  262. package/dist/snowflake.mjs.map +1 -0
  263. package/dist/soft-delete.d.mts +27 -169
  264. package/dist/soft-delete.mjs +1 -1
  265. package/dist/soft-delete.mjs.map +1 -1
  266. package/dist/spans-XDUFeTzC.mjs +2 -0
  267. package/dist/spans-XDUFeTzC.mjs.map +1 -0
  268. package/dist/{sql-BsBoKwaf.mjs → sql-3o4DOKm9.mjs} +1 -1
  269. package/dist/{sql-BsBoKwaf.mjs.map → sql-3o4DOKm9.mjs.map} +1 -1
  270. package/dist/sql-Dl6nykFV.mjs +2 -0
  271. package/dist/sql-Dl6nykFV.mjs.map +1 -0
  272. package/dist/{sql-statement-tokens-ugBPr6SM.mjs → sql-statement-tokens-DbeMwHra.mjs} +1 -1
  273. package/dist/{sql-statement-tokens-ugBPr6SM.mjs.map → sql-statement-tokens-DbeMwHra.mjs.map} +1 -1
  274. package/dist/sql.d.mts +1 -1
  275. package/dist/sql.mjs +1 -1
  276. package/dist/sqlite-adapter-Ad0d-m2t.mjs +2 -0
  277. package/dist/sqlite-adapter-Ad0d-m2t.mjs.map +1 -0
  278. package/dist/sqlite-statement-classifier-BAHl-WXS.mjs +2 -0
  279. package/dist/sqlite-statement-classifier-BAHl-WXS.mjs.map +1 -0
  280. package/dist/sqlite-utils-BRvbmlQ1.mjs +2 -0
  281. package/dist/{sqlite-utils-B-Y47_Uz.mjs.map → sqlite-utils-BRvbmlQ1.mjs.map} +1 -1
  282. package/dist/sqlite3.d.mts +1 -1
  283. package/dist/sqlite3.mjs +1 -1
  284. package/dist/standard-sql-qLcQyCtK.mjs +6 -0
  285. package/dist/standard-sql-qLcQyCtK.mjs.map +1 -0
  286. package/dist/{suppressed-failure-DO0ej03b.mjs → suppressed-failure-CQkQsMVS.mjs} +1 -1
  287. package/dist/{suppressed-failure-DO0ej03b.mjs.map → suppressed-failure-CQkQsMVS.mjs.map} +1 -1
  288. package/dist/surrealdb.d.mts +36 -6
  289. package/dist/surrealdb.mjs +1 -1
  290. package/dist/surrealdb.mjs.map +1 -1
  291. package/dist/surrealql-DpipDgMB.mjs +2 -0
  292. package/dist/surrealql-DpipDgMB.mjs.map +1 -0
  293. package/dist/to-many-BybuKQM1.mjs +2 -0
  294. package/dist/to-many-BybuKQM1.mjs.map +1 -0
  295. package/dist/transaction-BNomMtme.mjs +2 -0
  296. package/dist/transaction-BNomMtme.mjs.map +1 -0
  297. package/dist/{transaction-operation-Km-Gr-a3.mjs → transaction-operation-CVVJxQ19.mjs} +2 -2
  298. package/dist/transaction-operation-CVVJxQ19.mjs.map +1 -0
  299. package/dist/{types-C4v6iAmY.mjs → types-DtDnXhwa.mjs} +1 -1
  300. package/dist/{types-C4v6iAmY.mjs.map → types-DtDnXhwa.mjs.map} +1 -1
  301. package/dist/unit-BhHbZyuJ.mjs +2 -0
  302. package/dist/unit-BhHbZyuJ.mjs.map +1 -0
  303. package/dist/unit-words-CT0yeqfZ.mjs +2 -0
  304. package/dist/unit-words-CT0yeqfZ.mjs.map +1 -0
  305. package/dist/utils-CpAojrCj.mjs +26 -0
  306. package/dist/{utils-CuQHO2NF.mjs.map → utils-CpAojrCj.mjs.map} +1 -1
  307. package/dist/validation--qS7OPmg.mjs +2 -0
  308. package/dist/validation--qS7OPmg.mjs.map +1 -0
  309. package/dist/validation-CYaJ8ndO.mjs +2 -0
  310. package/dist/validation-CYaJ8ndO.mjs.map +1 -0
  311. package/dist/validation.d.mts +1 -1
  312. package/dist/validation.mjs +1 -1
  313. package/dist/validator-CZLW7aR3.mjs +2 -0
  314. package/dist/validator-CZLW7aR3.mjs.map +1 -0
  315. package/dist/{value-guards-CK9guf2Z.mjs → value-guards-CBuxSC66.mjs} +1 -1
  316. package/dist/{value-guards-CK9guf2Z.mjs.map → value-guards-CBuxSC66.mjs.map} +1 -1
  317. package/dist/values-B4aj1i1f.mjs +2 -0
  318. package/dist/values-B4aj1i1f.mjs.map +1 -0
  319. package/dist/version-DRfmNoR1.mjs +2 -0
  320. package/dist/{version-Ce4zn8qc.mjs.map → version-DRfmNoR1.mjs.map} +1 -1
  321. package/dist/write-sinks-3IKCDF-S.mjs +2 -0
  322. package/dist/write-sinks-3IKCDF-S.mjs.map +1 -0
  323. package/package.json +92 -36
  324. package/dist/adapter-internals-DZO1WI67.mjs.map +0 -1
  325. package/dist/adapter-namespace-C9RM19_J.mjs +0 -2
  326. package/dist/base-wlv81COV.mjs +0 -2
  327. package/dist/base-wlv81COV.mjs.map +0 -1
  328. package/dist/bind-parameter-capacity-Bjgx1lMC.mjs +0 -2
  329. package/dist/bind-parameter-capacity-Bjgx1lMC.mjs.map +0 -1
  330. package/dist/builder-yLL4r6JS.mjs +0 -2
  331. package/dist/builder-yLL4r6JS.mjs.map +0 -1
  332. package/dist/chain-3bgO2RX3.mjs +0 -2
  333. package/dist/chain-3bgO2RX3.mjs.map +0 -1
  334. package/dist/client-Bbke7iRo.mjs +0 -50
  335. package/dist/client-Bbke7iRo.mjs.map +0 -1
  336. package/dist/client-nkU6M5bV.mjs +0 -2
  337. package/dist/client-nkU6M5bV.mjs.map +0 -1
  338. package/dist/clock-DXbsDHLj.mjs +0 -2
  339. package/dist/clock-DXbsDHLj.mjs.map +0 -1
  340. package/dist/datetime-physical-codec-kE6fh5zZ.mjs +0 -2
  341. package/dist/driver-BRYL6K0W.mjs +0 -2
  342. package/dist/driver-BRYL6K0W.mjs.map +0 -1
  343. package/dist/driver-CcEhJcsE.mjs +0 -2
  344. package/dist/driver-CcEhJcsE.mjs.map +0 -1
  345. package/dist/error-mapping-DW7TYOyA.mjs +0 -2
  346. package/dist/error-mapping-DW7TYOyA.mjs.map +0 -1
  347. package/dist/every-hDecAr5k.mjs +0 -2
  348. package/dist/every-hDecAr5k.mjs.map +0 -1
  349. package/dist/execution-context-_oajgBi4.mjs +0 -2
  350. package/dist/execution-context-_oajgBi4.mjs.map +0 -1
  351. package/dist/geo-area-codec-B3QtKij8.mjs +0 -2
  352. package/dist/geo-point-codec-Ggv29hSH.mjs +0 -2
  353. package/dist/geo-point-codec-Ggv29hSH.mjs.map +0 -1
  354. package/dist/hydration-Dd2H4EyY.mjs +0 -2
  355. package/dist/identifier-conversion-771tvRzd.mjs +0 -2
  356. package/dist/identity-b2N94bh1.mjs +0 -2
  357. package/dist/identity-b2N94bh1.mjs.map +0 -1
  358. package/dist/invariant-CKZrz_S2.mjs +0 -2
  359. package/dist/invariant-CKZrz_S2.mjs.map +0 -1
  360. package/dist/key-B4B1etH3.mjs +0 -2
  361. package/dist/key-B4B1etH3.mjs.map +0 -1
  362. package/dist/keys-BcQgRjMB.mjs +0 -2
  363. package/dist/keys-BcQgRjMB.mjs.map +0 -1
  364. package/dist/keys-M0pWraMM.mjs +0 -2
  365. package/dist/keys-M0pWraMM.mjs.map +0 -1
  366. package/dist/libsql-lOqKLyZA.mjs +0 -11
  367. package/dist/libsql-lOqKLyZA.mjs.map +0 -1
  368. package/dist/memory-CsRVfZdT.mjs +0 -2
  369. package/dist/migrations-OE5D32qo.mjs +0 -2
  370. package/dist/model-DK9BhhNF.mjs +0 -2
  371. package/dist/model-DK9BhhNF.mjs.map +0 -1
  372. package/dist/mysql-CIdv4h7j.mjs +0 -100
  373. package/dist/mysql-CIdv4h7j.mjs.map +0 -1
  374. package/dist/mysql-adapter-C3d-TdaO.mjs +0 -2
  375. package/dist/mysql-adapter-C3d-TdaO.mjs.map +0 -1
  376. package/dist/native-types-CQH05hcr.mjs +0 -2
  377. package/dist/native-types-CQH05hcr.mjs.map +0 -1
  378. package/dist/normalized-result-ByvlIQqa.mjs +0 -2
  379. package/dist/normalized-result-ByvlIQqa.mjs.map +0 -1
  380. package/dist/observation-BcT8Cs3d.mjs +0 -2
  381. package/dist/observation-BcT8Cs3d.mjs.map +0 -1
  382. package/dist/physical-CjG29tya.mjs +0 -2
  383. package/dist/pinned-session-De2rDjdO.mjs +0 -2
  384. package/dist/postgres-V7noUFbG.mjs.map +0 -1
  385. package/dist/postgres-adapter-CvLB764t.mjs +0 -2
  386. package/dist/postgres-adapter-D53hxZM4.mjs +0 -2
  387. package/dist/postgres-adapter-D53hxZM4.mjs.map +0 -1
  388. package/dist/provider-limits-DolYOv3_.mjs +0 -2
  389. package/dist/provider-limits-DolYOv3_.mjs.map +0 -1
  390. package/dist/query-CTna5P9o.mjs +0 -2
  391. package/dist/query-CTna5P9o.mjs.map +0 -1
  392. package/dist/result-shape-D5gZFVps.mjs +0 -2
  393. package/dist/result-shape-D5gZFVps.mjs.map +0 -1
  394. package/dist/rows-B1SG8qg9.mjs +0 -2
  395. package/dist/rows-B1SG8qg9.mjs.map +0 -1
  396. package/dist/rows-of-qH0_KyL6.mjs +0 -2
  397. package/dist/rows-of-qH0_KyL6.mjs.map +0 -1
  398. package/dist/scalar-DNshDNz3.mjs +0 -4
  399. package/dist/scalar-DNshDNz3.mjs.map +0 -1
  400. package/dist/schema/json.mjs.map +0 -1
  401. package/dist/schema-DKL7GSu7.mjs +0 -2
  402. package/dist/schema-introspection-BogU9kCO.mjs +0 -6
  403. package/dist/settle-v6QhvFkm.mjs +0 -2
  404. package/dist/settle-v6QhvFkm.mjs.map +0 -1
  405. package/dist/sha256-D_fCV62w.mjs +0 -2
  406. package/dist/sha256-D_fCV62w.mjs.map +0 -1
  407. package/dist/sqlite-adapter-CVKv1u4i.mjs +0 -2
  408. package/dist/sqlite-adapter-CVKv1u4i.mjs.map +0 -1
  409. package/dist/sqlite-utils-B-Y47_Uz.mjs +0 -2
  410. package/dist/standard-sql-BHpLmLeM.mjs +0 -6
  411. package/dist/standard-sql-BHpLmLeM.mjs.map +0 -1
  412. package/dist/surrealql-Bnu3BzHE.mjs +0 -2
  413. package/dist/surrealql-Bnu3BzHE.mjs.map +0 -1
  414. package/dist/to-many-Dd1m0XqX.mjs +0 -2
  415. package/dist/to-many-Dd1m0XqX.mjs.map +0 -1
  416. package/dist/transaction-D5LHYn-r.mjs +0 -2
  417. package/dist/transaction-D5LHYn-r.mjs.map +0 -1
  418. package/dist/transaction-operation-Km-Gr-a3.mjs.map +0 -1
  419. package/dist/utils-CuQHO2NF.mjs +0 -26
  420. package/dist/utils-QZGdBir8.mjs +0 -2
  421. package/dist/utils-QZGdBir8.mjs.map +0 -1
  422. package/dist/v-CWY9ntMb.mjs +0 -2
  423. package/dist/v-CWY9ntMb.mjs.map +0 -1
  424. package/dist/validation-mTttU3Fk.mjs +0 -2
  425. package/dist/validation-mTttU3Fk.mjs.map +0 -1
  426. package/dist/validation-pfpKPPZ_.mjs +0 -2
  427. package/dist/validation-pfpKPPZ_.mjs.map +0 -1
  428. package/dist/validator-BjNxS3uX.mjs +0 -2
  429. package/dist/validator-BjNxS3uX.mjs.map +0 -1
  430. package/dist/version-Ce4zn8qc.mjs +0 -2
  431. package/dist/write-sinks-Bean5xf5.mjs +0 -2
  432. package/dist/write-sinks-Bean5xf5.mjs.map +0 -1
  433. package/dist/writes-BX5fLiw5.mjs +0 -2
  434. package/dist/writes-BX5fLiw5.mjs.map +0 -1
  435. /package/dist/{contract-BOwMGvl2.d.mts → contract-CrIB-3ZJ.d.mts} +0 -0
  436. /package/dist/{sql-BbLhTqDH.d.mts → sql-BVZ8QefY.d.mts} +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"bun-sqlite.mjs","names":[],"sources":["../src/drivers/bun-sqlite/index.ts"],"sourcesContent":["import { physicalConnectionQueue } from \"../connection-scope\";\nimport { refuseUnknownDriverConfigKeys } from \"../shared/driver-options\";\nimport {\n LOCAL_SQLITE_TRANSACTION_SUPPORT,\n normalizeSQLiteRawRows,\n runLocalSQLiteTransaction,\n} from \"../shared/sqlite-utils\";\n/**\n * Bun SQLite Driver\n *\n * Driver implementation for Bun's built-in SQLite (bun:sqlite).\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport { SQLiteAdapter } from \"@adapters/databases/sqlite/sqlite-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport { ClientInitializationError, FeatureNotSupportedError } from \"@errors\";\nimport {\n Driver,\n type DriverResultParser,\n type QueryExecutionContext,\n SQLITE_MIGRATION_CAPABILITY,\n} from \"../driver\";\nimport {\n convertValueForSQLite,\n isSQLiteBinaryValue,\n sqliteBinaryToUint8Array,\n sqliteResultParser,\n type TransactionOptionSupport,\n} from \"../shared\";\nimport type { QueryResult } from \"../types\";\n\n// ============================================================\n// TYPE DECLARATIONS FOR BUN:SQLITE\n// ============================================================\n\n// Bun's Database type - we define inline to avoid requiring bun types at compile time\ninterface BunSQLiteDatabase {\n query<T = unknown>(sql: string): BunSQLiteStatement<T>;\n prepare<T = unknown>(sql: string): BunSQLiteStatement<T>;\n run(sql: string, ...params: unknown[]): void;\n exec(sql: string): void;\n readonly inTransaction: boolean;\n close(): void;\n transaction<T>(fn: () => T): () => T;\n}\n\ninterface BunSQLiteStatement<T = unknown> {\n readonly columnNames: string[];\n all(...params: unknown[]): T[];\n get(...params: unknown[]): T | null;\n run(...params: unknown[]): {\n changes: number;\n lastInsertRowid: number | bigint;\n };\n /**\n * Reads INTEGER columns as BigInt instead of lossy JS numbers. Present on\n * `bun:sqlite` statements since Bun 1.1.14; the driver refuses to read\n * rather than return corrupted values when it is missing.\n */\n safeIntegers(safe: boolean): BunSQLiteStatement<T>;\n values(...params: unknown[]): unknown[][];\n}\n\n/**\n * `safeIntegers()` is what keeps an INTEGER past 2^53 from being rounded on\n * the way out of SQLite. A `bun:sqlite` old enough to lack it cannot answer\n * the query truthfully, so the read is refused instead of silently returning\n * a corrupted number — the one outcome that must never ship.\n */\nfunction requireSafeIntegers<T>(\n stmt: BunSQLiteStatement<T>\n): BunSQLiteStatement<T> {\n if (typeof stmt.safeIntegers !== \"function\") {\n throw new FeatureNotSupportedError(\n \"bun:sqlite\",\n \"Statement.safeIntegers\",\n \"This Bun build cannot read INTEGER columns as BigInt, so any value past 2^53 would come back silently rounded. Upgrade to Bun 1.1.14 or newer.\"\n );\n }\n return stmt;\n}\n\n/**\n * Typed statements come from `bun:sqlite`'s own bounded statement cache\n * (`query`), which dies with the database: `close()` finalizes it, and a closed\n * database refuses instead of answering. The cache is reused only while\n * `prepare` is the one `bun:sqlite` defines at the base of the class chain; a\n * database whose `prepare` was replaced or overridden sees every call.\n */\nfunction reusesStatements(db: BunSQLiteDatabase): boolean {\n let stock: unknown;\n for (\n let proto = Object.getPrototypeOf(db);\n proto;\n proto = Object.getPrototypeOf(proto)\n )\n if (Object.hasOwn(proto, \"prepare\")) stock = proto.prepare;\n return db.prepare === stock;\n}\n\nconst UNPAIRED_SURROGATE_PATTERN =\n /[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?<![\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]/u;\n\nfunction convertValuesForBunSQLite(values: unknown[]): unknown[] {\n return values.map((parameter) => {\n const value = convertValueForSQLite(parameter);\n if (typeof value === \"string\" && UNPAIRED_SURROGATE_PATTERN.test(value)) {\n throw new TypeError(\n \"bun:sqlite cannot preserve unpaired UTF-16 surrogates; the parameter was refused before dispatch.\"\n );\n }\n if (value instanceof Uint8Array || !isSQLiteBinaryValue(value)) {\n return value;\n }\n return sqliteBinaryToUint8Array(value);\n });\n}\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport interface BunSQLiteOptions {\n readonly?: boolean;\n create?: boolean;\n readwrite?: boolean;\n strict?: boolean;\n /**\n * Busy timeout in milliseconds, applied as `PRAGMA busy_timeout`. A VibORM\n * option: `bun:sqlite` has none of its own. Defaults to 5000.\n */\n timeout?: number;\n}\n\nexport interface BunSQLiteDriverOptions {\n client?: BunSQLiteDatabase;\n dataDir?: string;\n options?: BunSQLiteOptions;\n}\n\nexport type BunSQLiteClientConfig<C extends DriverConfig> =\n BunSQLiteDriverOptions & C;\n\nconst BUN_SQLITE_CONFIG_KEYS: Record<keyof BunSQLiteDriverOptions, true> = {\n client: true,\n dataDir: true,\n options: true,\n};\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class BunSQLiteDriver extends Driver<\n BunSQLiteDatabase,\n BunSQLiteDatabase\n> {\n readonly adapter: DatabaseAdapter = new SQLiteAdapter();\n readonly maxBindParametersPerStatement: number | undefined = 32_766;\n readonly result: DriverResultParser = sqliteResultParser;\n readonly sqliteMigrationCapability = SQLITE_MIGRATION_CAPABILITY;\n protected override readonly serializeTransactions = true;\n\n private readonly driverOptions: BunSQLiteDriverOptions;\n private readonly suppliedClient: BunSQLiteDatabase | undefined;\n /** Interpolated into a PRAGMA, so it is admitted here as an integer. */\n private readonly busyTimeout: number;\n\n constructor(options: BunSQLiteDriverOptions = {}) {\n super(\"sqlite\", \"bun-sqlite\");\n this.driverOptions = options;\n this.busyTimeout = options.options?.timeout ?? 5000;\n if (!Number.isSafeInteger(this.busyTimeout) || this.busyTimeout < 0) {\n throw new ClientInitializationError(\n 'The bun-sqlite \"timeout\" option must be a non-negative integer number of milliseconds.',\n { meta: { driver: \"bun-sqlite\", operation: \"configuration\" } }\n );\n }\n\n this.suppliedClient = options.client;\n if (this.suppliedClient) {\n const enabled = this.suppliedClient.query(\"PRAGMA foreign_keys\").get();\n if (\n !enabled ||\n typeof enabled !== \"object\" ||\n Reflect.get(enabled, \"foreign_keys\") !== 1\n ) {\n throw new ClientInitializationError(\n \"A supplied bun:sqlite Database must enable PRAGMA foreign_keys = ON before wrapping.\",\n { meta: { driver: \"bun-sqlite\" } }\n );\n }\n this.client = this.suppliedClient;\n Object.defineProperty(this, \"connectionQueue\", {\n value: physicalConnectionQueue(this.suppliedClient),\n });\n }\n }\n\n protected async initClient(): Promise<BunSQLiteDatabase> {\n if (this.suppliedClient) return this.suppliedClient;\n // Dynamic import for bun:sqlite\n const { Database } = await import(\"bun:sqlite\");\n\n const dataDir = this.driverOptions.dataDir ?? \":memory:\";\n // `timeout` is VibORM's own key, not one of bun:sqlite's open flags.\n const { timeout: _timeout, ...openFlags } =\n this.driverOptions.options ?? {};\n\n // bun:sqlite derives its open flags from this object and rejects one that\n // names no access mode: `new Database(path, {})` throws SQLITE_MISUSE\n // (\"flags must include SQLITE_OPEN_READONLY or SQLITE_OPEN_READWRITE\").\n // An options bag that says nothing must mean nothing, so the argument is\n // omitted entirely and Bun applies its own default (readwrite + create).\n const db = (Object.keys(openFlags).length === 0\n ? new Database(dataDir)\n : new Database(dataDir, openFlags)) as unknown as BunSQLiteDatabase;\n\n // bun:sqlite leaves SQLite's foreign_keys default (OFF), which would let a\n // dangling FK write report success while sqlite3 and libsql refuse it.\n // Enforcement is a viborm guarantee, not an inherited library default.\n db.exec(\"PRAGMA foreign_keys = ON\");\n db.exec(`PRAGMA busy_timeout = ${this.busyTimeout}`);\n\n return db;\n }\n\n protected async closeClient(db: BunSQLiteDatabase): Promise<void> {\n if (db !== this.suppliedClient) db.close();\n }\n\n protected async execute<T>(\n client: BunSQLiteDatabase,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const values = convertValuesForBunSQLite(params);\n return this.runStatement<T>(client, sql, values, context?.model !== \"$raw\");\n }\n\n protected async executeRaw<T>(\n client: BunSQLiteDatabase,\n sql: string,\n params?: unknown[]\n ): Promise<QueryResult<T>> {\n const values = params ? convertValuesForBunSQLite(params) : undefined;\n return this.runStatement<T>(client, sql, values, false);\n }\n\n private runStatement<T>(\n db: BunSQLiteDatabase,\n sql: string,\n values: unknown[] | undefined,\n typed: boolean\n ): QueryResult<T> {\n const stmt =\n typed && reusesStatements(db) ? db.query(sql) : db.prepare(sql);\n\n if (stmt.columnNames.length > 0) {\n // Read once without precision loss, including unsafe raw queries.\n requireSafeIntegers(stmt).safeIntegers(true);\n const rows = (values ? stmt.all(...values) : stmt.all()) as T[];\n return {\n rows: typed ? rows : normalizeSQLiteRawRows(rows),\n rowCount: rows.length,\n };\n }\n\n const result = values ? stmt.run(...values) : stmt.run();\n return { rows: [] as T[], rowCount: result.changes };\n }\n\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return LOCAL_SQLITE_TRANSACTION_SUPPORT;\n }\n\n protected async transaction<T>(\n client: BunSQLiteDatabase,\n fn: (tx: BunSQLiteDatabase) => Promise<T>,\n context?: QueryExecutionContext\n ): Promise<T> {\n return runLocalSQLiteTransaction(client, fn, context);\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: BunSQLiteClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, BunSQLiteDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: BunSQLiteDriver }\n >]: LinkedClientConfig<C & { driver: BunSQLiteDriver }>[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"bun-sqlite\", BUN_SQLITE_CONFIG_KEYS, {\n databaseUrl: \"pass the database file as dataDir\",\n });\n const { client, dataDir, options } = config;\n\n const driver = new BunSQLiteDriver({ client, dataDir, options });\n\n return createClientFromDriverConfig<S, C, BunSQLiteDriver>(config, driver);\n}\n"],"mappings":"yUA6EA,SAAS,oBACP,EACuB,CACvB,GAAI,OAAO,EAAK,cAAiB,WAC/B,MAAM,IAAI,EACR,aACA,yBACA,iJACD,CAEH,OAAO,EAUT,SAAS,iBAAiB,EAAgC,CACxD,IAAI,EACJ,IACE,IAAI,EAAQ,OAAO,eAAe,EAAG,CACrC,EACA,EAAQ,OAAO,eAAe,EAAM,CAEhC,OAAO,OAAO,EAAO,UAAU,GAAE,EAAQ,EAAM,SACrD,OAAO,EAAG,UAAY,EAGxB,MAAM,EACJ,0EAEF,SAAS,0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S,CAAC,CAEU"}
1
+ {"version":3,"file":"bun-sqlite.mjs","names":[],"sources":["../src/drivers/bun-sqlite/index.ts"],"sourcesContent":["import { physicalConnectionQueue } from \"../connection-scope\";\nimport { refuseUnknownDriverConfigKeys } from \"../shared/driver-options\";\nimport {\n LOCAL_SQLITE_TRANSACTION_SUPPORT,\n normalizeSQLiteRawRows,\n runLocalSQLiteTransaction,\n} from \"../shared/sqlite-utils\";\n/**\n * Bun SQLite Driver\n *\n * Driver implementation for Bun's built-in SQLite (bun:sqlite).\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport { SQLiteAdapter } from \"@adapters/databases/sqlite/sqlite-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport { ClientInitializationError, FeatureNotSupportedError } from \"@errors\";\nimport {\n Driver,\n type DriverResultParser,\n type QueryExecutionContext,\n SQLITE_MIGRATION_CAPABILITY,\n} from \"../driver\";\nimport {\n convertValueForSQLite,\n isSQLiteBinaryValue,\n sqliteBinaryToUint8Array,\n sqliteResultParser,\n type TransactionOptionSupport,\n} from \"../shared\";\nimport type { QueryResult } from \"../types\";\n\n// ============================================================\n// TYPE DECLARATIONS FOR BUN:SQLITE\n// ============================================================\n\n// Bun's Database type - we define inline to avoid requiring bun types at compile time\ninterface BunSQLiteDatabase {\n query<T = unknown>(sql: string): BunSQLiteStatement<T>;\n prepare<T = unknown>(sql: string): BunSQLiteStatement<T>;\n run(sql: string, ...params: unknown[]): void;\n exec(sql: string): void;\n readonly inTransaction: boolean;\n close(): void;\n transaction<T>(fn: () => T): () => T;\n}\n\ninterface BunSQLiteStatement<T = unknown> {\n readonly columnNames: string[];\n all(...params: unknown[]): T[];\n get(...params: unknown[]): T | null;\n run(...params: unknown[]): {\n changes: number;\n lastInsertRowid: number | bigint;\n };\n /**\n * Reads INTEGER columns as BigInt instead of lossy JS numbers. Present on\n * `bun:sqlite` statements since Bun 1.1.14; the driver refuses to read\n * rather than return corrupted values when it is missing.\n */\n safeIntegers(safe: boolean): BunSQLiteStatement<T>;\n values(...params: unknown[]): unknown[][];\n}\n\n/**\n * `safeIntegers()` is what keeps an INTEGER past 2^53 from being rounded on\n * the way out of SQLite. A `bun:sqlite` old enough to lack it cannot answer\n * the query truthfully, so the read is refused instead of silently returning\n * a corrupted number — the one outcome that must never ship.\n */\nfunction requireSafeIntegers<T>(\n stmt: BunSQLiteStatement<T>\n): BunSQLiteStatement<T> {\n if (typeof stmt.safeIntegers !== \"function\") {\n throw new FeatureNotSupportedError(\n \"bun:sqlite\",\n \"Statement.safeIntegers\",\n \"This Bun build cannot read INTEGER columns as BigInt, so any value past 2^53 would come back silently rounded. Upgrade to Bun 1.1.14 or newer.\"\n );\n }\n return stmt;\n}\n\n/**\n * Typed statements come from `bun:sqlite`'s own bounded statement cache\n * (`query`), which dies with the database: `close()` finalizes it, and a closed\n * database refuses instead of answering. The cache is reused only while\n * `prepare` is the one `bun:sqlite` defines at the base of the class chain; a\n * database whose `prepare` was replaced or overridden sees every call.\n */\nfunction reusesStatements(db: BunSQLiteDatabase): boolean {\n let stock: unknown;\n for (\n let proto = Object.getPrototypeOf(db);\n proto;\n proto = Object.getPrototypeOf(proto)\n )\n if (Object.hasOwn(proto, \"prepare\")) stock = proto.prepare;\n return db.prepare === stock;\n}\n\nconst UNPAIRED_SURROGATE_PATTERN =\n /[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?<![\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]/u;\n\nfunction convertValuesForBunSQLite(values: unknown[]): unknown[] {\n return values.map((parameter) => {\n const value = convertValueForSQLite(parameter);\n if (typeof value === \"string\" && UNPAIRED_SURROGATE_PATTERN.test(value)) {\n throw new TypeError(\n \"bun:sqlite cannot preserve unpaired UTF-16 surrogates; the parameter was refused before dispatch.\"\n );\n }\n if (value instanceof Uint8Array || !isSQLiteBinaryValue(value)) {\n return value;\n }\n return sqliteBinaryToUint8Array(value);\n });\n}\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport interface BunSQLiteOptions {\n readonly?: boolean;\n create?: boolean;\n readwrite?: boolean;\n strict?: boolean;\n /**\n * Busy timeout in milliseconds, applied as `PRAGMA busy_timeout`. A VibORM\n * option: `bun:sqlite` has none of its own. Defaults to 5000.\n */\n timeout?: number;\n}\n\nexport interface BunSQLiteDriverOptions {\n client?: BunSQLiteDatabase;\n dataDir?: string;\n options?: BunSQLiteOptions;\n}\n\nexport type BunSQLiteClientConfig<C extends DriverConfig> =\n BunSQLiteDriverOptions & C;\n\nconst BUN_SQLITE_CONFIG_KEYS: Record<keyof BunSQLiteDriverOptions, true> = {\n client: true,\n dataDir: true,\n options: true,\n};\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class BunSQLiteDriver extends Driver<\n BunSQLiteDatabase,\n BunSQLiteDatabase\n> {\n readonly adapter: DatabaseAdapter = new SQLiteAdapter();\n readonly maxBindParametersPerStatement: number | undefined = 32_766;\n readonly result: DriverResultParser = sqliteResultParser;\n readonly sqliteMigrationCapability = SQLITE_MIGRATION_CAPABILITY;\n protected override readonly serializeTransactions = true;\n\n private readonly driverOptions: BunSQLiteDriverOptions;\n private readonly suppliedClient: BunSQLiteDatabase | undefined;\n /** Interpolated into a PRAGMA, so it is admitted here as an integer. */\n private readonly busyTimeout: number;\n\n constructor(options: BunSQLiteDriverOptions = {}) {\n super(\"sqlite\", \"bun-sqlite\");\n this.driverOptions = options;\n this.busyTimeout = options.options?.timeout ?? 5000;\n if (!Number.isSafeInteger(this.busyTimeout) || this.busyTimeout < 0) {\n throw new ClientInitializationError(\n 'The bun-sqlite \"timeout\" option must be a non-negative integer number of milliseconds.',\n { meta: { driver: \"bun-sqlite\", operation: \"configuration\" } }\n );\n }\n\n this.suppliedClient = options.client;\n if (this.suppliedClient) {\n const enabled = this.suppliedClient.query(\"PRAGMA foreign_keys\").get();\n if (\n !enabled ||\n typeof enabled !== \"object\" ||\n Reflect.get(enabled, \"foreign_keys\") !== 1\n ) {\n throw new ClientInitializationError(\n \"A supplied bun:sqlite Database must enable PRAGMA foreign_keys = ON before wrapping.\",\n { meta: { driver: \"bun-sqlite\" } }\n );\n }\n this.client = this.suppliedClient;\n Object.defineProperty(this, \"connectionQueue\", {\n value: physicalConnectionQueue(this.suppliedClient),\n });\n }\n }\n\n protected async initClient(): Promise<BunSQLiteDatabase> {\n if (this.suppliedClient) return this.suppliedClient;\n // Dynamic import for bun:sqlite\n const { Database } = await import(\"bun:sqlite\");\n\n const dataDir = this.driverOptions.dataDir ?? \":memory:\";\n // `timeout` is VibORM's own key, not one of bun:sqlite's open flags.\n const { timeout: _timeout, ...openFlags } =\n this.driverOptions.options ?? {};\n\n // bun:sqlite derives its open flags from this object and rejects one that\n // names no access mode: `new Database(path, {})` throws SQLITE_MISUSE\n // (\"flags must include SQLITE_OPEN_READONLY or SQLITE_OPEN_READWRITE\").\n // An options bag that says nothing must mean nothing, so the argument is\n // omitted entirely and Bun applies its own default (readwrite + create).\n const db = (Object.keys(openFlags).length === 0\n ? new Database(dataDir)\n : new Database(dataDir, openFlags)) as unknown as BunSQLiteDatabase;\n\n // bun:sqlite leaves SQLite's foreign_keys default (OFF), which would let a\n // dangling FK write report success while sqlite3 and libsql refuse it.\n // Enforcement is a viborm guarantee, not an inherited library default.\n db.exec(\"PRAGMA foreign_keys = ON\");\n db.exec(`PRAGMA busy_timeout = ${this.busyTimeout}`);\n\n return db;\n }\n\n protected async closeClient(db: BunSQLiteDatabase): Promise<void> {\n if (db !== this.suppliedClient) db.close();\n }\n\n protected async execute<T>(\n client: BunSQLiteDatabase,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const values = convertValuesForBunSQLite(params);\n return this.runStatement<T>(client, sql, values, context?.model !== \"$raw\");\n }\n\n protected async executeRaw<T>(\n client: BunSQLiteDatabase,\n sql: string,\n params?: unknown[]\n ): Promise<QueryResult<T>> {\n const values = params ? convertValuesForBunSQLite(params) : undefined;\n return this.runStatement<T>(client, sql, values, false);\n }\n\n private runStatement<T>(\n db: BunSQLiteDatabase,\n sql: string,\n values: unknown[] | undefined,\n typed: boolean\n ): QueryResult<T> {\n const stmt =\n typed && reusesStatements(db) ? db.query(sql) : db.prepare(sql);\n\n if (stmt.columnNames.length > 0) {\n // Read once without precision loss, including unsafe raw queries.\n requireSafeIntegers(stmt).safeIntegers(true);\n const rows = (values ? stmt.all(...values) : stmt.all()) as T[];\n return {\n rows: typed ? rows : normalizeSQLiteRawRows(rows),\n rowCount: rows.length,\n };\n }\n\n const result = values ? stmt.run(...values) : stmt.run();\n return { rows: [] as T[], rowCount: result.changes };\n }\n\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return LOCAL_SQLITE_TRANSACTION_SUPPORT;\n }\n\n protected async transaction<T>(\n client: BunSQLiteDatabase,\n fn: (tx: BunSQLiteDatabase) => Promise<T>,\n context?: QueryExecutionContext\n ): Promise<T> {\n return runLocalSQLiteTransaction(client, fn, context);\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: BunSQLiteClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, BunSQLiteDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: BunSQLiteDriver }\n >]: LinkedClientConfig<C & { driver: BunSQLiteDriver }>[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"bun-sqlite\", BUN_SQLITE_CONFIG_KEYS, {\n databaseUrl: \"pass the database file as dataDir\",\n });\n const { client, dataDir, options } = config;\n\n const driver = new BunSQLiteDriver({ client, dataDir, options });\n\n return createClientFromDriverConfig<S, C, BunSQLiteDriver>(config, driver);\n}\n"],"mappings":"mVA6EA,SAAS,oBACP,EACuB,CACvB,GAAI,OAAO,EAA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AAS,CAGtD,0BAAwE,CACtE,OAAO,EAGT,MAAgB,YACd,EACA,EACA,EACY,CACZ,OAAO,EAA0B,EAAQ,EAAI,EAAQ,GAQzD,SAAgB,aACd,EAOC,CACD,EAA8B,EAAQ,aAAc,EAAwB,CAC1E,YAAa,oCACd,CAAC,CACF,GAAM,CAAE,SAAQ,UAAS,WAAY,EAIrC,OAAO,EAAoD,EAF5C,IAAI,gBAAgB,CAAE,SAAQ,UAAS,UAAS,CAAC,CAEU"}
@@ -1,4 +1,4 @@
1
- import { Fn as CacheEntry, Pn as CacheDriver } from "../index-B8MMx5Al.mjs";
1
+ import { n as CacheEntry, t as CacheDriver } from "../driver-CH9qAuft.mjs";
2
2
  import { KVNamespace } from "@cloudflare/workers-types";
3
3
 
4
4
  //#region src/cache/drivers/cloudflare-kv.d.ts
@@ -1,2 +1,2 @@
1
- import{n as e}from"../chunk-BuuaeEvq.mjs";import{t}from"../driver-CcEhJcsE.mjs";var CloudflareKVCache=class extends t{#e;constructor(e){super(`cloudflare-kv`),this.#e=e}async get(e){return await this.#e.get(e,`json`)||null}async set(e,t,n){let r=Math.max(60,Math.ceil(t/1e3));await this.#e.put(e,JSON.stringify(n),{expirationTtl:r})}async delete(e){await Promise.all(e.map(e=>this.#e.delete(e)))}async clear(e){let t;do{let n=await this.#e.list({prefix:e,cursor:t});await Promise.all(n.keys.map(e=>this.#e.delete(e.name))),t=n.list_complete?void 0:n.cursor}while(t)}};export{CloudflareKVCache};
1
+ import{n as e}from"../chunk-BuuaeEvq.mjs";import{n as t}from"../driver-BGVcgnIX.mjs";var CloudflareKVCache=class extends t{#e;constructor(e){super(`cloudflare-kv`),this.#e=e}async get(e){return await this.#e.get(e,`json`)||null}async set(e,t,n){let r=Math.max(60,Math.ceil(t/1e3));await this.#e.put(e,JSON.stringify(n),{expirationTtl:r})}async delete(e){await Promise.all(e.map(e=>this.#e.delete(e)))}async clear(e){let t;do{let n=await this.#e.list({prefix:e,cursor:t});await Promise.all(n.keys.map(e=>this.#e.delete(e.name))),t=n.list_complete?void 0:n.cursor}while(t)}};export{CloudflareKVCache};
2
2
  //# sourceMappingURL=cloudflare-kv.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"cloudflare-kv.mjs","names":["#kv"],"sources":["../../src/cache/drivers/cloudflare-kv.ts"],"sourcesContent":["/**\n * Cloudflare KV Cache\n *\n * Cache implementation using Cloudflare Workers KV.\n */\n\nimport type { KVNamespace } from \"@cloudflare/workers-types\";\nimport { CacheDriver, type CacheEntry } from \"../driver\";\n\n/**\n * Cloudflare KV cache implementation\n */\nexport class CloudflareKVCache extends CacheDriver {\n readonly #kv: KVNamespace;\n\n constructor(kv: KVNamespace) {\n super(\"cloudflare-kv\");\n this.#kv = kv;\n }\n\n protected async get<T>(key: string): Promise<CacheEntry<T> | null> {\n const data = await this.#kv.get<CacheEntry<T>>(key, \"json\");\n if (!data) return null;\n return data;\n }\n\n protected async set<T>(\n key: string,\n storageTtl: number,\n entry: CacheEntry<T>\n ): Promise<void> {\n // KV TTL is in seconds\n const kvTtlSeconds = Math.max(60, Math.ceil(storageTtl / 1000));\n\n await this.#kv.put(key, JSON.stringify(entry), {\n expirationTtl: kvTtlSeconds,\n });\n }\n\n protected async delete(keys: string[]): Promise<void> {\n await Promise.all(keys.map((key) => this.#kv.delete(key)));\n }\n\n protected async clear(prefix: string): Promise<void> {\n let cursor: string | undefined;\n do {\n const result = await this.#kv.list({ prefix, cursor });\n await Promise.all(result.keys.map((k) => this.#kv.delete(k.name)));\n cursor = result.list_complete ? undefined : result.cursor;\n } while (cursor);\n }\n}\n"],"mappings":"gFAYA,IAAa,kBAAb,cAAuC,CAAY,CACjD,GAEA,YAAY,EAAiB,CAC3B,MAAM,gBAAgB,CACtB,MAAA,EAAW,EAGb,MAAgB,IAAO,EAA4C,CAGjE,OAFa,MAAM,MAAA,EAAS,IAAmB,EAAK,OAAO,EACzC,KAIpB,MAAgB,IACd,EACA,EACA,EACe,CAEf,IAAM,EAAe,KAAK,IAAI,GAAI,KAAK,KAAK,EAAa,IAAK,CAAC,CAE/D,MAAM,MAAA,EAAS,IAAI,EAAK,KAAK,UAAU,EAAM,CAAE,CAC7C,cAAe,EAChB,CAAC,CAGJ,MAAgB,OAAO,EAA+B,CACpD,MAAM,QAAQ,IAAI,EAAK,IAAK,GAAQ,MAAA,EAAS,OAAO,EAAI,CAAC,CAAC,CAG5D,MAAgB,MAAM,EAA+B,CACnD,IAAI,EACJ,EAAG,CACD,IAAM,EAAS,MAAM,MAAA,EAAS,KAAK,CAAE,SAAQ,SAAQ,CAAC,CACtD,MAAM,QAAQ,IAAI,EAAO,KAAK,IAAK,GAAM,MAAA,EAAS,OAAO,EAAE,KAAK,CAAC,CAAC,CAClE,EAAS,EAAO,cAAgB,IAAA,GAAY,EAAO,aAC5C"}
1
+ {"version":3,"file":"cloudflare-kv.mjs","names":["#kv"],"sources":["../../src/cache/drivers/cloudflare-kv.ts"],"sourcesContent":["/**\n * Cloudflare KV Cache\n *\n * Cache implementation using Cloudflare Workers KV.\n */\n\nimport type { KVNamespace } from \"@cloudflare/workers-types\";\nimport { CacheDriver, type CacheEntry } from \"../driver\";\n\n/**\n * Cloudflare KV cache implementation\n */\nexport class CloudflareKVCache extends CacheDriver {\n readonly #kv: KVNamespace;\n\n constructor(kv: KVNamespace) {\n super(\"cloudflare-kv\");\n this.#kv = kv;\n }\n\n protected async get<T>(key: string): Promise<CacheEntry<T> | null> {\n const data = await this.#kv.get<CacheEntry<T>>(key, \"json\");\n if (!data) return null;\n return data;\n }\n\n protected async set<T>(\n key: string,\n storageTtl: number,\n entry: CacheEntry<T>\n ): Promise<void> {\n // KV TTL is in seconds\n const kvTtlSeconds = Math.max(60, Math.ceil(storageTtl / 1000));\n\n await this.#kv.put(key, JSON.stringify(entry), {\n expirationTtl: kvTtlSeconds,\n });\n }\n\n protected async delete(keys: string[]): Promise<void> {\n await Promise.all(keys.map((key) => this.#kv.delete(key)));\n }\n\n protected async clear(prefix: string): Promise<void> {\n let cursor: string | undefined;\n do {\n const result = await this.#kv.list({ prefix, cursor });\n await Promise.all(result.keys.map((k) => this.#kv.delete(k.name)));\n cursor = result.list_complete ? undefined : result.cursor;\n } while (cursor);\n }\n}\n"],"mappings":"qFAYA,IAAa,kBAAb,cAAuC,CAAY,CACjD,GAEA,YAAY,EAAiB,CAC3B,MAAM,gBAAgB,CACtB,MAAA,EAAW,EAGb,MAAgB,IAAO,EAA4C,CAGjE,OAFa,MAAM,MAAA,EAAS,IAAmB,EAAK,OAAO,EACzC,KAIpB,MAAgB,IACd,EACA,EACA,EACe,CAEf,IAAM,EAAe,KAAK,IAAI,GAAI,KAAK,KAAK,EAAa,IAAK,CAAC,CAE/D,MAAM,MAAA,EAAS,IAAI,EAAK,KAAK,UAAU,EAAM,CAAE,CAC7C,cAAe,EAChB,CAAC,CAGJ,MAAgB,OAAO,EAA+B,CACpD,MAAM,QAAQ,IAAI,EAAK,IAAK,GAAQ,MAAA,EAAS,OAAO,EAAI,CAAC,CAAC,CAG5D,MAAgB,MAAM,EAA+B,CACnD,IAAI,EACJ,EAAG,CACD,IAAM,EAAS,MAAM,MAAA,EAAS,KAAK,CAAE,SAAQ,SAAQ,CAAC,CACtD,MAAM,QAAQ,IAAI,EAAO,KAAK,IAAK,GAAM,MAAA,EAAS,OAAO,EAAE,KAAK,CAAC,CAAC,CAClE,EAAS,EAAO,cAAgB,IAAA,GAAY,EAAO,aAC5C"}
@@ -1,4 +1,4 @@
1
- import { Fn as CacheEntry, Pn as CacheDriver } from "../index-B8MMx5Al.mjs";
1
+ import { n as CacheEntry, t as CacheDriver } from "../driver-CH9qAuft.mjs";
2
2
 
3
3
  //#region src/cache/drivers/memory.d.ts
4
4
  interface MemoryCacheOptions {
@@ -6,7 +6,7 @@ interface MemoryCacheOptions {
6
6
  }
7
7
  declare class MemoryCache<const Options extends MemoryCacheOptions = MemoryCacheOptions> extends CacheDriver {
8
8
  #private;
9
- constructor(options?: Options & Record<Exclude<keyof Options, keyof MemoryCacheOptions>, never>, ...extra: never[]);
9
+ constructor(options?: Options & Record<Exclude<keyof Options, keyof MemoryCacheOptions>, never>);
10
10
  protected get<T>(key: string): Promise<CacheEntry<T> | null>;
11
11
  protected set<T>(key: string, storageTtl: number, entry: CacheEntry<T>): Promise<void>;
12
12
  protected delete(keys: string[]): Promise<void>;
@@ -1,2 +1,2 @@
1
- import{n as e}from"../chunk-BuuaeEvq.mjs";import{p as t}from"../observation-BcT8Cs3d.mjs";import{t as n}from"../driver-CcEhJcsE.mjs";var MemoryCache=class extends n{#e=new Map;#t;#n;constructor(e,...n){if(super(`memory`),n.length)throw new t(`MemoryCache received extra construction arguments.`);let r=1024;if(e!==void 0){let n;try{n=Object.getOwnPropertyDescriptors(e)}catch{throw new t(`MemoryCache options could not be inspected.`)}let i=n.maxEntries,a=i&&`value`in i?i.value:void 0;if(Reflect.ownKeys(n).length!==1||!i||!(`value`in i)||typeof a!=`number`||!Number.isSafeInteger(a)||a<1)throw new t(`MemoryCache options must contain a positive safe-integer maxEntries only.`);r=a}this.#t=r}async get(e){let t=this.#e.get(e);return t?(this.#e.delete(e),this.clock.now()>=t.expiresAt?(this.#r(),null):(this.#e.set(e,t),t.entry)):null}async set(e,t,n){for(this.#e.delete(e),this.#e.set(e,{entry:n,expiresAt:this.clock.now()+t});this.#e.size>this.#t;){let e=this.#e.keys().next().value;e!==void 0&&this.#e.delete(e)}this.#i(t)}async delete(e){for(let t of e)this.#e.delete(t);this.#r()}async clear(e){for(let t of this.#e.keys())t.startsWith(e)&&this.#e.delete(t);this.#r()}#r(){this.#e.size||(this.#n?.cancel(),this.#n=void 0)}#i(e=6e4){this.#n||!this.#e.size||(this.#n=this.clock.setTimeout(()=>{this.#n=void 0;let e=this.clock.now();for(let[t,n]of this.#e)e>=n.expiresAt&&this.#e.delete(t);this.#i()},Math.min(e,6e4)),this.#n.unref?.())}async disconnect(){this.#e.clear(),this.#r()}};export{MemoryCache};
1
+ import{n as e}from"../chunk-BuuaeEvq.mjs";import{O as t}from"../error-mapping-B1-IWkCQ.mjs";import{n}from"../driver-BGVcgnIX.mjs";var MemoryCache=class extends n{#e=new Map;#t;#n;constructor(e){super(`memory`);let n=e?.maxEntries??1024;if(!Number.isSafeInteger(n)||n<1||Object.keys(e??{}).some(e=>e!==`maxEntries`))throw new t(`MemoryCache options must contain a positive safe-integer maxEntries only.`);this.#t=n}async get(e){let t=this.#e.get(e);return t?(this.#e.delete(e),this.clock.now()>=t.expiresAt?(this.#r(),null):(this.#e.set(e,t),t.entry)):null}async set(e,t,n){for(this.#e.delete(e),this.#e.set(e,{entry:n,expiresAt:this.clock.now()+t});this.#e.size>this.#t;)this.#e.delete(this.#e.keys().next().value);this.#i(t)}async delete(e){for(let t of e)this.#e.delete(t);this.#r()}async clear(e){for(let t of this.#e.keys())t.startsWith(e)&&this.#e.delete(t);this.#r()}#r(){this.#e.size||(this.#n?.cancel(),this.#n=void 0)}#i(e=6e4){this.#n||!this.#e.size||(this.#n=this.clock.setTimeout(()=>{this.#n=void 0;let e=this.clock.now();for(let[t,n]of this.#e)e>=n.expiresAt&&this.#e.delete(t);this.#i()},Math.min(e,6e4)),this.#n.unref?.())}async disconnect(){this.#e.clear(),this.#r()}};export{MemoryCache};
2
2
  //# sourceMappingURL=memory.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"memory.mjs","names":["#store","#maxEntries","#idle","#schedule","#timer"],"sources":["../../src/cache/drivers/memory.ts"],"sourcesContent":["/** In-memory LRU cache with a bounded entry count and one expiry sweep. */\nimport type { ClockTimer } from \"../../clock\";\nimport { CacheConfigurationError } from \"../../errors\";\nimport { CacheDriver, type CacheEntry } from \"../driver\";\n\nexport interface MemoryCacheOptions {\n readonly maxEntries: number;\n}\n\nexport class MemoryCache<\n const Options extends MemoryCacheOptions = MemoryCacheOptions,\n> extends CacheDriver {\n readonly #store = new Map<string, { entry: CacheEntry; expiresAt: number }>();\n readonly #maxEntries: number;\n #timer?: ClockTimer;\n\n constructor(\n options?: Options &\n Record<Exclude<keyof Options, keyof MemoryCacheOptions>, never>,\n ...extra: never[]\n ) {\n super(\"memory\");\n if (extra.length)\n throw new CacheConfigurationError(\n \"MemoryCache received extra construction arguments.\"\n );\n let maxEntries = 1024;\n if (options !== undefined) {\n let descriptors: PropertyDescriptorMap;\n try {\n descriptors = Object.getOwnPropertyDescriptors(options);\n } catch {\n throw new CacheConfigurationError(\n \"MemoryCache options could not be inspected.\"\n );\n }\n const limit = descriptors.maxEntries;\n const supplied: unknown =\n limit && \"value\" in limit ? limit.value : undefined;\n if (\n Reflect.ownKeys(descriptors).length !== 1 ||\n !limit ||\n !(\"value\" in limit) ||\n typeof supplied !== \"number\" ||\n !Number.isSafeInteger(supplied) ||\n supplied < 1\n )\n throw new CacheConfigurationError(\n \"MemoryCache options must contain a positive safe-integer maxEntries only.\"\n );\n maxEntries = supplied;\n }\n this.#maxEntries = maxEntries;\n }\n\n protected async get<T>(key: string): Promise<CacheEntry<T> | null> {\n const stored = this.#store.get(key);\n if (!stored) return null;\n this.#store.delete(key);\n if (this.clock.now() >= stored.expiresAt) {\n this.#idle();\n return null;\n }\n this.#store.set(key, stored);\n return stored.entry as CacheEntry<T>;\n }\n\n protected async set<T>(\n key: string,\n storageTtl: number,\n entry: CacheEntry<T>\n ): Promise<void> {\n this.#store.delete(key);\n this.#store.set(key, { entry, expiresAt: this.clock.now() + storageTtl });\n while (this.#store.size > this.#maxEntries) {\n const oldest = this.#store.keys().next().value;\n if (oldest !== undefined) this.#store.delete(oldest);\n }\n this.#schedule(storageTtl);\n }\n\n protected async delete(keys: string[]): Promise<void> {\n for (const key of keys) this.#store.delete(key);\n this.#idle();\n }\n\n protected async clear(prefix: string): Promise<void> {\n for (const key of this.#store.keys())\n if (key.startsWith(prefix)) this.#store.delete(key);\n this.#idle();\n }\n\n #idle(): void {\n if (this.#store.size) return;\n this.#timer?.cancel();\n this.#timer = undefined;\n }\n\n #schedule(delay = 60_000): void {\n if (this.#timer || !this.#store.size) return;\n this.#timer = this.clock.setTimeout(\n () => {\n this.#timer = undefined;\n const now = this.clock.now();\n for (const [key, stored] of this.#store)\n if (now >= stored.expiresAt) this.#store.delete(key);\n this.#schedule();\n },\n Math.min(delay, 60_000)\n );\n this.#timer.unref?.();\n }\n\n override async disconnect(): Promise<void> {\n this.#store.clear();\n this.#idle();\n }\n}\n"],"mappings":"qIASA,IAAa,YAAb,cAEU,CAAY,CACpB,GAAkB,IAAI,IACtB,GACA,GAEA,YACE,EAEA,GAAG,EACH,CAEA,GADA,MAAM,SAAS,CACX,EAAM,OACR,MAAM,IAAI,EACR,qDACD,CACH,IAAI,EAAa,KACjB,GAAI,IAAY,IAAA,GAAW,CACzB,IAAI,EACJ,GAAI,CACF,EAAc,OAAO,0BAA0B,EAAQ,MACjD,CACN,MAAM,IAAI,EACR,8CACD,CAEH,IAAM,EAAQ,EAAY,WACpB,EACJ,GAAS,UAAW,EAAQ,EAAM,MAAQ,IAAA,GAC5C,GACE,QAAQ,QAAQ,EAAY,CAAC,SAAW,GACxC,CAAC,GACD,EAAE,UAAW,IACb,OAAO,GAAa,UACpB,CAAC,OAAO,cAAc,EAAS,EAC/B,EAAW,EAEX,MAAM,IAAI,EACR,4EACD,CACH,EAAa,EAEf,MAAA,EAAmB,EAGrB,MAAgB,IAAO,EAA4C,CACjE,IAAM,EAAS,MAAA,EAAY,IAAI,EAAI,CAQnC,OAPK,GACL,MAAA,EAAY,OAAO,EAAI,CACnB,KAAK,MAAM,KAAK,EAAI,EAAO,WAC7B,MAAA,GAAY,CACL,OAET,MAAA,EAAY,IAAI,EAAK,EAAO,CACrB,EAAO,QAPM,KAUtB,MAAgB,IACd,EACA,EACA,EACe,CAGf,IAFA,MAAA,EAAY,OAAO,EAAI,CACvB,MAAA,EAAY,IAAI,EAAK,CAAE,QAAO,UAAW,KAAK,MAAM,KAAK,CAAG,EAAY,CAAC,CAClE,MAAA,EAAY,KAAO,MAAA,GAAkB,CAC1C,IAAM,EAAS,MAAA,EAAY,MAAM,CAAC,MAAM,CAAC,MACrC,IAAW,IAAA,IAAW,MAAA,EAAY,OAAO,EAAO,CAEtD,MAAA,EAAe,EAAW,CAG5B,MAAgB,OAAO,EAA+B,CACpD,IAAK,IAAM,KAAO,EAAM,MAAA,EAAY,OAAO,EAAI,CAC/C,MAAA,GAAY,CAGd,MAAgB,MAAM,EAA+B,CACnD,IAAK,IAAM,KAAO,MAAA,EAAY,MAAM,CAC9B,EAAI,WAAW,EAAO,EAAE,MAAA,EAAY,OAAO,EAAI,CACrD,MAAA,GAAY,CAGd,IAAc,CACR,MAAA,EAAY,OAChB,MAAA,GAAa,QAAQ,CACrB,MAAA,EAAc,IAAA,IAGhB,GAAU,EAAQ,IAAc,CAC1B,MAAA,GAAe,CAAC,MAAA,EAAY,OAChC,MAAA,EAAc,KAAK,MAAM,eACjB,CACJ,MAAA,EAAc,IAAA,GACd,IAAM,EAAM,KAAK,MAAM,KAAK,CAC5B,IAAK,GAAM,CAAC,EAAK,KAAW,MAAA,EACtB,GAAO,EAAO,WAAW,MAAA,EAAY,OAAO,EAAI,CACtD,MAAA,GAAgB,EAElB,KAAK,IAAI,EAAO,IAAO,CACxB,CACD,MAAA,EAAY,SAAS,EAGvB,MAAe,YAA4B,CACzC,MAAA,EAAY,OAAO,CACnB,MAAA,GAAY"}
1
+ {"version":3,"file":"memory.mjs","names":["#store","#maxEntries","#idle","#schedule","#timer"],"sources":["../../src/cache/drivers/memory.ts"],"sourcesContent":["/** In-memory LRU cache with a bounded entry count and one expiry sweep. */\nimport { CacheConfigurationError } from \"../../errors\";\nimport { CacheDriver, type CacheEntry, type CacheTimer } from \"../driver\";\n\nexport interface MemoryCacheOptions {\n readonly maxEntries: number;\n}\n\nexport class MemoryCache<\n const Options extends MemoryCacheOptions = MemoryCacheOptions,\n> extends CacheDriver {\n readonly #store = new Map<string, { entry: CacheEntry; expiresAt: number }>();\n readonly #maxEntries: number;\n #timer?: CacheTimer;\n\n constructor(\n options?: Options &\n Record<Exclude<keyof Options, keyof MemoryCacheOptions>, never>\n ) {\n super(\"memory\");\n const maxEntries = options?.maxEntries ?? 1024;\n // A misspelled or retired option is refused, not ignored.\n if (\n !Number.isSafeInteger(maxEntries) ||\n maxEntries < 1 ||\n Object.keys(options ?? {}).some((key) => key !== \"maxEntries\")\n )\n throw new CacheConfigurationError(\n \"MemoryCache options must contain a positive safe-integer maxEntries only.\"\n );\n this.#maxEntries = maxEntries;\n }\n\n protected async get<T>(key: string): Promise<CacheEntry<T> | null> {\n const stored = this.#store.get(key);\n if (!stored) return null;\n this.#store.delete(key);\n if (this.clock.now() >= stored.expiresAt) {\n this.#idle();\n return null;\n }\n this.#store.set(key, stored);\n // The entry `set` stored under this key, for the type the caller reads it as.\n return stored.entry as CacheEntry<T>;\n }\n\n protected async set<T>(\n key: string,\n storageTtl: number,\n entry: CacheEntry<T>\n ): Promise<void> {\n this.#store.delete(key);\n this.#store.set(key, { entry, expiresAt: this.clock.now() + storageTtl });\n // Past the bound the store holds an entry: the oldest is the first key.\n while (this.#store.size > this.#maxEntries)\n this.#store.delete(this.#store.keys().next().value!);\n this.#schedule(storageTtl);\n }\n\n protected async delete(keys: string[]): Promise<void> {\n for (const key of keys) this.#store.delete(key);\n this.#idle();\n }\n\n protected async clear(prefix: string): Promise<void> {\n for (const key of this.#store.keys())\n if (key.startsWith(prefix)) this.#store.delete(key);\n this.#idle();\n }\n\n #idle(): void {\n if (this.#store.size) return;\n this.#timer?.cancel();\n this.#timer = undefined;\n }\n\n #schedule(delay = 60_000): void {\n if (this.#timer || !this.#store.size) return;\n this.#timer = this.clock.setTimeout(\n () => {\n this.#timer = undefined;\n const now = this.clock.now();\n for (const [key, stored] of this.#store)\n if (now >= stored.expiresAt) this.#store.delete(key);\n this.#schedule();\n },\n Math.min(delay, 60_000)\n );\n this.#timer.unref?.();\n }\n\n override async disconnect(): Promise<void> {\n this.#store.clear();\n this.#idle();\n }\n}\n"],"mappings":"kIAQA,IAAa,YAAb,cAEU,CAAY,CACpB,GAAkB,IAAI,IAC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AC,EAAK,KAAW,MAAA,EACtB,GAAO,EAAO,WAAW,MAAA,EAAY,OAAO,EAAI,CACtD,MAAA,GAAgB,EAElB,KAAK,IAAI,EAAO,IAAO,CACxB,CACD,MAAA,EAAY,SAAS,EAGvB,MAAe,YAA4B,CACzC,MAAA,EAAY,OAAO,CACnB,MAAA,GAAY"}
package/dist/cache.d.mts CHANGED
@@ -1,14 +1,68 @@
1
- import { Fn as CacheEntry, In as CacheSetOptions, Jt as OfficialCacheExtension, Ln as WaitUntilFn, Pn as CacheDriver, Rn as CacheInvalidationOptions, zn as WithCacheOptions } from "./index-B8MMx5Al.mjs";
1
+ import { A as Extension, L as PlacedArgument, S as AnyTarget, Xr as MutationOperations, Y as CachedClientOf, j as Facts } from "./database-adapter-BD_htd5h.mjs";
2
+ import { a as WaitUntilFn, i as Revalidate, n as CacheEntry, o as CacheInvalidationOptions, r as CacheSetOptions, s as WithCacheOptions, t as CacheDriver } from "./driver-CH9qAuft.mjs";
2
3
 
3
4
  //#region src/cache/extension.d.ts
4
5
  interface CacheExtensionConfig {
5
6
  readonly driver: CacheDriver;
6
7
  readonly version?: string | number;
7
8
  readonly waitUntil?: WaitUntilFn;
9
+ /**
10
+ * `staleWhileRevalidate`, imported from `viborm/cache`: what lets a view's
11
+ * `swr` option serve a stale entry and refresh it in the background.
12
+ */
13
+ readonly swr?: Revalidate;
8
14
  }
9
15
  type ConfigKeys<Config> = Config extends unknown ? keyof Config : never;
10
16
  type ExactCacheExtensionConfig<Config> = Record<Exclude<ConfigKeys<Config>, keyof CacheExtensionConfig>, never>;
11
- /** Create VibORM's fixed-name cache extension. */
12
- declare function cache<const Config>(config: Config & NoInfer<CacheExtensionConfig & ExactCacheExtensionConfig<Config>>): OfficialCacheExtension;
17
+ /** `Self` is a client, not a transaction nor a view: what the cache's methods are called on. */
18
+ type OnClient<Self> = [CachedClientOf<Self>] extends [never] ? never : unknown;
19
+ /**
20
+ * The client methods the cache adds, typed through `this` from the client
21
+ * they are called on, whatever the chain added after the cache.
22
+ */
23
+ interface CacheMethods {
24
+ /** A view whose reads the cache serves: read operations only. */
25
+ $withCache<Self>(this: Self & OnClient<Self>, options?: WithCacheOptions): CachedClientOf<Self>;
26
+ /** Invalidate entries by keys or patterns (a `*` suffix matches a prefix). */
27
+ $invalidate<Self>(this: Self & OnClient<Self>, ...keys: string[]): Promise<void>;
28
+ }
29
+ /** What the cache adds to a client: its `cache` argument on writes, `$withCache`, `$invalidate`. */
30
+ type CacheFacts = Facts<CacheMethods, Record<never, never>, {
31
+ readonly cache: PlacedArgument<CacheInvalidationOptions, PropertyKey, MutationOperations>;
32
+ }, never, never, Record<never, never>, Record<never, never>, false>;
33
+ /**
34
+ * VibORM's fixed-name cache extension: `client.$extends(cache({ driver }))`.
35
+ */
36
+ declare function cache<T extends AnyTarget, const Config>(config: Config & NoInfer<CacheExtensionConfig & ExactCacheExtensionConfig<Config>>): Extension<T, CacheFacts>;
37
+ //#endregion
38
+ //#region src/cache/revalidate.d.ts
39
+ /**
40
+ * A stale entry within its window is served, and refreshed in the
41
+ * background: claim the backend's marker (best effort; another request
42
+ * holding it skips), replay the read's core keeping its rows, store them,
43
+ * and always clear the marker. Nothing here rejects: its `revalidate` unit
44
+ * presents a failure, the replay's primary over the cleanup's, both
45
+ * retained.
46
+ */
47
+ declare const staleWhileRevalidate: Revalidate;
48
+ //#endregion
49
+ //#region src/cache/storage.d.ts
50
+ /** The entry stored under `key`, or `null`. */
51
+ declare function getEntry<T>(driver: CacheDriver, key: string, origin?: object): Promise<CacheEntry<T> | null>;
52
+ /** Store `value` under `key` for `options.ttl` milliseconds. */
53
+ declare function setEntry<T>(driver: CacheDriver, key: string, value: T, options: CacheSetOptions, origin?: object): Promise<void>;
54
+ /** Delete the entry under `key` and its revalidation marker. */
55
+ declare function deleteEntry(driver: CacheDriver, key: string, origin?: object): Promise<void>;
56
+ /** Clear every entry under `prefix`; every unscoped entry without one. */
57
+ declare function clearEntries(driver: CacheDriver, prefix?: string, origin?: object): Promise<void>;
58
+ /**
59
+ * Invalidate `model`'s entries (`autoInvalidate`, the default) and the keys
60
+ * or `*` prefixes `options.invalidate` names, validated whole first.
61
+ */
62
+ declare function invalidateEntries(driver: CacheDriver, model: string, options?: CacheInvalidationOptions, origin?: object): Promise<void>;
63
+ /** Claim the refresh of `key`: whether this caller performs it. */
64
+ declare function markRevalidating(driver: CacheDriver, key: string): Promise<boolean>;
65
+ /** Release the claim on the refresh of `key`. */
66
+ declare function clearRevalidating(driver: CacheDriver, key: string): Promise<void>;
13
67
  //#endregion
14
- export { CacheDriver, type CacheEntry, type CacheExtensionConfig, type CacheInvalidationOptions, type CacheSetOptions, type WaitUntilFn, type WithCacheOptions, cache };
68
+ export { CacheDriver, type CacheEntry, type CacheExtensionConfig, type CacheInvalidationOptions, type CacheMethods, type CacheSetOptions, type MutationOperations, type WaitUntilFn, type WithCacheOptions, cache, clearEntries, clearRevalidating, deleteEntry, getEntry, invalidateEntries, markRevalidating, setEntry, staleWhileRevalidate };
package/dist/cache.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{a as t,i as n,o as r,s as i}from"./value-guards-CK9guf2Z.mjs";import{A as a,F as o,I as s,M as c,O as l,T as u,a as d,c as f,l as p,t as m,v as h,w as g}from"./rows-B1SG8qg9.mjs";import{b as _}from"./base-wlv81COV.mjs";import{g as v,p as y}from"./observation-BcT8Cs3d.mjs";import{F as b,T as x,X as S,_ as C,r as w,x as T}from"./geo-point-codec-Ggv29hSH.mjs";import{i as E,o as D}from"./key-B4B1etH3.mjs";import{i as O}from"./builder-yLL4r6JS.mjs";import{t as k}from"./validation-mTttU3Fk.mjs";import{t as A}from"./invariant-CKZrz_S2.mjs";import{t as j}from"./sha256-D_fCV62w.mjs";import{a as M,i as N,n as P,o as F,r as I,s as L,t as R}from"./driver-CcEhJcsE.mjs";const z=new Set([`findFirst`,`findMany`,`findUnique`,`findUniqueOrThrow`,`findFirstOrThrow`,`count`,`aggregate`,`groupBy`,`exist`]),B=new WeakMap;function admitMutationCacheOptions(e){let t=k(F,e);if(t.issues)throw new y(`Invalid mutation cache options: ${t.issues.map(e=>e.message).join(`, `)}`,{cause:S(t)});let n=t.value.invalidate===void 0?void 0:[...t.value.invalidate];n&&Object.freeze(n);let r=Object.freeze({autoInvalidate:t.value.autoInvalidate,...n===void 0?{}:{invalidate:n}});return B.set(r,r),r}function readMutationCacheOptions(e){let t=e?.cache;return r(t)?B.get(t):void 0}function cacheKeyOf(e,t,n,r){if(r!==void 0){let i=cacheKeyOf(e,t,n);return i===void 0?void 0:[`order`,i,r]}if(t===void 0)return e;if(Object.values(t).every(h)){if(n===void 0)return[e,t];try{return[e,t,n.map(rowsIdentity)]}catch{return}}}function prepareMutationCacheWriteOutcome(e,t,n,r,i,a){if(g(n))return Object.freeze({extension:`viborm.cache`,failurePolicy:`boundary-owned`,listener:async o=>{try{await N(e,t,r,i,a)}catch(e){throw new y(`Cache invalidation failed after mutation '${n}' on model '${t}'.`,{cause:_(e),meta:{method:`invalidate`,model:t,operation:n,commitCertainty:o.certainty}})}}})}function validateCacheableOperation(e){if(!z.has(e))throw new v(e,[...z])}function createCacheExecutionOptions(e,t,n){let r=k(L,e);if(r.issues)throw new y(`Invalid cache options: ${r.issues.map(e=>e.message).join(`, `)}`,{cause:S(r)});let{bypass:i,key:a,ttl:o,swr:s}=r.value;return{ttlMs:o,swr:resolveSwr(s,o),bypass:i,key:a,waitUntil:t,driverIdentity:n}}function executeCachedResultOperation(e,t,n,r,i,a,o,s){return I(e,t,n,r,i,a,o,s)}async function invalidateManualCache(e,t,n,r){let i=[...t];await N(e,`manual`,Object.freeze({invalidate:i}),n,r)}function resolveSwr(e,t){return e===void 0||e===!1?!1:e===!0?t*2:t+e}const V=new WeakMap;function settledRows(e){let t=Object.values(e.verbs??{}).some(e=>typeof e!=`function`&&typeof e.acyclic==`object`&&!Array.isArray(e.acyclic));if(!(d(e)||t))return e;let n=V.get(e);if(n)return n;let r=Object.fromEntries(Object.entries(e.verbs).map(([e,t])=>{let n=typeof t==`function`?t():t,r=n.acyclic;return[e,r===void 0||Array.isArray(r)?n:Object.freeze({...n,acyclic:r.resolve()})]})),i=Object.fromEntries(Object.entries(e.models).map(([e,t])=>[e,Object.fromEntries(Object.entries(t).map(([e,t])=>[e,Object.fromEntries(Object.entries(t).map(([e,t])=>[e,typeof t==`function`?t():t]))]))])),a=Object.freeze({...e,models:i,verbs:r});return V.set(e,a),a}const H=new WeakMap;function rowsIdentity(e){let t=m(e),n=H.get(t);if(n!==void 0)return n;let r=settledRows(t);if(!(f(t)&&Object.values(r.verbs??{}).every(e=>p(e))))return r;let i=j(new TextEncoder().encode(D(r))),a=Array.from(i,e=>e.toString(16).padStart(2,`0`)).join(``);return H.set(t,a),a}var CacheSnapshotFailure=class extends Error{};function failCacheSnapshot(){throw new CacheSnapshotFailure}function readSnapshotArray(e){if(!Array.isArray(e)||Object.getPrototypeOf(e)!==Array.prototype)return failCacheSnapshot();let t=Reflect.ownKeys(e),n=Reflect.getOwnPropertyDescriptor(e,`length`)?.value;if(typeof n!=`number`||!Number.isSafeInteger(n)||n<0||t.length!==n+1||t[n]!==`length`)return failCacheSnapshot();let r=Array(n);for(let i=0;i<n;i+=1){let n=String(i);if(t[i]!==n)return failCacheSnapshot();let a=Reflect.getOwnPropertyDescriptor(e,n);if(!(a&&`value`in a&&a.enumerable))return failCacheSnapshot();r[i]=a.value}return r}function readSnapshotRecord(e,t=!1){if(typeof e!=`object`||!e||Array.isArray(e))return failCacheSnapshot();let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&!(t&&n===null))return failCacheSnapshot();let r=Reflect.ownKeys(e),i=Array(r.length);for(let t=0;t<r.length;t+=1){let n=r[t];if(typeof n!=`string`)return failCacheSnapshot();let a=Reflect.getOwnPropertyDescriptor(e,n);if(!(a&&`value`in a&&a.enumerable))return failCacheSnapshot();i[t]=[n,a.value]}return i}function defineSnapshotProperty(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!0,value:n,writable:!0})}function enterSnapshotObject(e,t){e.has(t)&&failCacheSnapshot(),e.add(t)}function withSnapshotObject(e,t,n){enterSnapshotObject(e,t);try{return n()}finally{e.delete(t)}}function encodeSnapshotNumber(e){return typeof e!=`number`||!Number.isFinite(e)?failCacheSnapshot():Object.is(e,-0)?`-0`:String(e)}function decodeSnapshotNumber(e){if(typeof e!=`string`)return failCacheSnapshot();let t=Number(e);return!Number.isFinite(t)||encodeSnapshotNumber(t)!==e?failCacheSnapshot():t}function encodeSnapshotCount(e){return typeof e!=`number`||!Number.isSafeInteger(e)||e<0?failCacheSnapshot():String(e)}function decodeSnapshotCount(e){let t=decodeSnapshotNumber(e);return!Number.isSafeInteger(t)||t<0?failCacheSnapshot():t}const U=`null`,W=`string`,G=`boolean`,K=`number`,q=`array`,J=`object`;function snapshotJsonValue(e,t){return e===null?[U]:typeof e==`string`?[W,e]:typeof e==`boolean`?[G,e]:typeof e==`number`?[K,encodeSnapshotNumber(e)]:Array.isArray(e)?withSnapshotObject(t,e,()=>[q,readSnapshotArray(e).map(e=>snapshotJsonValue(e,t))]):typeof e==`object`&&e?withSnapshotObject(t,e,()=>[J,readSnapshotRecord(e,!0).map(([e,n])=>[e,snapshotJsonValue(n,t)])]):failCacheSnapshot()}function materializeJsonValue(e,t){return typeof e!=`object`||!e?failCacheSnapshot():withSnapshotObject(t,e,()=>{let n=readSnapshotArray(e),r=n[0];return r===U&&n.length===1?null:r===W&&n.length===2&&typeof n[1]==`string`||r===G&&n.length===2&&typeof n[1]==`boolean`?n[1]:r===K&&n.length===2?decodeSnapshotNumber(n[1]):r===q&&n.length===2?materializeJsonArray(n[1],t):r===J&&n.length===2?materializeJsonObject(n[1],t):failCacheSnapshot()})}function materializeJsonArray(e,t){return typeof e!=`object`||!e?failCacheSnapshot():withSnapshotObject(t,e,()=>readSnapshotArray(e).map(e=>materializeJsonValue(e,t)))}function materializeJsonObject(e,t){return typeof e!=`object`||!e?failCacheSnapshot():withSnapshotObject(t,e,()=>{let n=readSnapshotArray(e),r={},i=new Set;for(let e of n){if(typeof e!=`object`||!e)return failCacheSnapshot();let n=withSnapshotObject(t,e,()=>readSnapshotArray(e)),a=n[0];if(n.length!==2||typeof a!=`string`||i.has(a))return failCacheSnapshot();i.add(a),defineSnapshotProperty(r,a,materializeJsonValue(n[1],t))}return r})}const Y=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d{1,3})?$/;function compileScalarCodec(e,t=!0){let n;if(`enumValues`in e)n=enumCodec(new Set(e.enumValues));else{let t=e[`~`].state;switch(t.type){case`string`:n=stringCodec();break;case`time`:n=timeCodec();break;case`int`:n=integerCodec();break;case`number`:n=numberCodec();break;case`decimal`:n=decimalCodec(t.decimal);break;case`boolean`:n=booleanCodec();break;case`bigint`:n=bigintCodec();break;case`datetime`:n=dateCodec(!1);break;case`date`:n=dateCodec(!0);break;case`json`:n=jsonCodec();break;case`vector`:n=vectorCodec(t.dimension);break;case`blob`:n=bytesCodec();break;case`point`:n=pointCodec();break}}let r=e[`~`].state,i=r.array?arrayCodec(n):n;return t&&r.nullable?nullableCodec(i):i}function taggedRelationCodec(e){return{snapshot(t,n){return typeof t!=`object`||!t?failCacheSnapshot():withSnapshotObject(n,t,()=>{let r=readSnapshotRecord(t);if(r.length!==2)return failCacheSnapshot();let i,a;for(let[e,t]of r)if(e===`type`&&typeof t==`string`)i=t;else if(e===`data`)a=t;else return failCacheSnapshot();let o=i===void 0?void 0:e.get(i);return!o||a==null?failCacheSnapshot():r.map(([e,t])=>[e,e===`type`?i:o.snapshot(t,n)])})},materialize(t,n){return materializeArray(t,n,t=>{if(t.length!==2)return failCacheSnapshot();let r=readEncodedEntries(t,n),i,a;for(let[e,t]of r)if(e===`type`&&typeof t==`string`)i=t;else if(e===`data`)a=t;else return failCacheSnapshot();let o=i===void 0?void 0:e.get(i);if(!o||a==null)return failCacheSnapshot();let s={};for(let[e]of r)defineSnapshotProperty(s,e,e===`type`?i:o.materialize(a,n));return s})}}}function recordCodec(e){return{snapshot(t,n){return typeof t!=`object`||!t?failCacheSnapshot():withSnapshotObject(n,t,()=>{let r=readSnapshotRecord(t);if(r.length!==e.size)return failCacheSnapshot();let i=new Set;return r.map(([t,r])=>{let a=e.get(t);return!a||i.has(t)?failCacheSnapshot():(i.add(t),[t,a.snapshot(r,n)])})})},materialize(t,n){return materializeArray(t,n,t=>{if(t.length!==e.size)return failCacheSnapshot();let r=readEncodedEntries(t,n),i=new Set,a={};for(let[t,o]of r){let r=e.get(t);if(!r||i.has(t))return failCacheSnapshot();i.add(t),defineSnapshotProperty(a,t,r.materialize(o,n))}return a})}}}function arrayCodec(e){return{snapshot(t,n){return Array.isArray(t)?withSnapshotObject(n,t,()=>readSnapshotArray(t).map(t=>e.snapshot(t,n))):failCacheSnapshot()},materialize(t,n){return materializeArray(t,n,t=>t.map(t=>e.materialize(t,n)))}}}function nullableCodec(e){return{snapshot(t,n){return t===null?null:e.snapshot(t,n)},materialize(t,n){return t===null?null:e.materialize(t,n)}}}function recursiveRelationCodec(e,t){return{snapshot:(n,r)=>walkRecursiveSlot(n,r,e,{read(n){let i={},a=[];for(let[t,r]of readSnapshotRecord(n))t===e.relation?a.push(r):defineSnapshotProperty(i,t,r);return[t.snapshot(i,r),a]},write:(e,t)=>[e,...t]}),materialize:(n,r)=>walkRecursiveSlot(n,r,e,{read(e){let[n,...i]=readSnapshotArray(e);return[t.materialize(n,r),i]},write(t,n){return n.length>0&&defineSnapshotProperty(t,e.relation,n[0]),t}})}}function walkRecursiveSlot(e,t,n,r){let open=(e,t,r,i)=>{let a;return a=n.many?readSnapshotArray(e):e===null?n.optional?[]:failCacheSnapshot():[e],{level:t,occurrences:a,outputs:[],owner:r,node:i,next:0}},i=[open(e,1)],a;for(;i.length>0;){let e=i.at(-1);if(e.next<e.occurrences.length){let a=e.occurrences[e.next];if(e.next+=1,typeof a!=`object`||!a)return failCacheSnapshot();enterSnapshotObject(t,a);let o=O(n.depth,e.level),[s,c]=r.read(a);if(c.length!==(o?1:0))return failCacheSnapshot();if(o){i.push(open(c[0],e.level+1,a,s));continue}t.delete(a),e.outputs.push(r.write(s,c));continue}i.pop();let o=n.many?e.outputs:e.outputs[0]??null;if(e.owner===void 0){a=o;continue}let s=i.at(-1);t.delete(e.owner),s.outputs.push(r.write(e.node,[o]))}return a}function booleanCodec(){return primitiveCodec(e=>typeof e==`boolean`?e:failCacheSnapshot(),e=>typeof e==`boolean`?e:failCacheSnapshot())}function numberCodec(){return primitiveCodec(encodeSnapshotNumber,decodeSnapshotNumber)}function countCodec(){return primitiveCodec(encodeSnapshotCount,decodeSnapshotCount)}function readEncodedEntries(e,t){let n=Array(e.length);for(let r=0;r<e.length;r+=1)n[r]=materializeArray(e[r],t,e=>e.length!==2||typeof e[0]!=`string`?failCacheSnapshot():[e[0],e[1]]);return n}function stringCodec(){return primitiveCodec(e=>typeof e==`string`?e:failCacheSnapshot(),e=>typeof e==`string`?e:failCacheSnapshot())}function timeCodec(){return primitiveCodec(e=>typeof e==`string`&&Y.test(e)?e:failCacheSnapshot(),e=>typeof e==`string`&&Y.test(e)?e:failCacheSnapshot())}function enumCodec(e){return primitiveCodec(t=>typeof t==`string`&&e.has(t)?t:failCacheSnapshot(),t=>typeof t==`string`&&e.has(t)?t:failCacheSnapshot())}function integerCodec(){return primitiveCodec(e=>typeof e!=`number`||!Number.isSafeInteger(e)?failCacheSnapshot():encodeSnapshotNumber(e),e=>{let t=decodeSnapshotNumber(e);return Number.isSafeInteger(t)?t:failCacheSnapshot()})}function decimalCodec(e){return primitiveCodec(t=>e?T(C(t),e)??failCacheSnapshot():failCacheSnapshot(),t=>{if(!e)return failCacheSnapshot();let n=T(t,e);return n!==void 0&&n===t?b(n):failCacheSnapshot()})}const X=new Map([[`Infinity`,1/0],[`-Infinity`,-1/0]]);function compileWidenedSumCodec(e){let{type:t}=e[`~`].state;if(t===`bigint`)return bigintCodec();if(t===`number`||t===`int`)return primitiveCodec(e=>e===1/0||e===-1/0?String(e):encodeSnapshotNumber(e),e=>X.get(e)??decodeSnapshotNumber(e));let n=e[`~`].state.decimal;return primitiveCodec(e=>n?x(C(e),n.scale)??failCacheSnapshot():failCacheSnapshot(),e=>{if(!n)return failCacheSnapshot();let t=x(e,n.scale);return t!==void 0&&t===e?b(t):failCacheSnapshot()})}function bigintCodec(){return primitiveCodec(e=>typeof e==`bigint`?e.toString():failCacheSnapshot(),e=>{if(typeof e!=`string`)return failCacheSnapshot();try{let t=BigInt(e);return t.toString()===e?t:failCacheSnapshot()}catch{return failCacheSnapshot()}})}function dateCodec(e){return primitiveCodec(t=>{if(!(t instanceof Date)||Object.getPrototypeOf(t)!==Date.prototype||Reflect.ownKeys(t).length!==0)return failCacheSnapshot();let n=Date.prototype.getTime.call(t);if(!Number.isFinite(n))return failCacheSnapshot();let r=Date.prototype.toISOString.call(t);return e&&!r.endsWith(`T00:00:00.000Z`)?failCacheSnapshot():r},t=>{if(typeof t!=`string`)return failCacheSnapshot();let n=new Date(t);return!Number.isFinite(n.getTime())||n.toISOString()!==t||e&&!t.endsWith(`T00:00:00.000Z`)?failCacheSnapshot():n})}function jsonCodec(){return{snapshot:snapshotJsonValue,materialize:materializeJsonValue}}function vectorCodec(e){return{snapshot(t,n){return Array.isArray(t)?withSnapshotObject(n,t,()=>{let n=readSnapshotArray(t);return e!==void 0&&n.length!==e?failCacheSnapshot():n.map(encodeSnapshotNumber)}):failCacheSnapshot()},materialize(t,n){return materializeArray(t,n,t=>e!==void 0&&t.length!==e?failCacheSnapshot():t.map(decodeSnapshotNumber))}}}function bytesCodec(){return{snapshot(e){if(!(e instanceof Uint8Array)||Object.getPrototypeOf(e)!==Uint8Array.prototype||Reflect.ownKeys(e).length!==e.byteLength)return failCacheSnapshot();let t=Array(e.byteLength);for(let n=0;n<e.byteLength;n+=1)t[n]=e[n];return t},materialize(e){let t=readSnapshotArray(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e+=1){let r=t[e];if(typeof r!=`number`||!Number.isInteger(r)||r<0||r>255)return failCacheSnapshot();n[e]=r}return n}}}function pointCodec(){let e=recordCodec(new Map([[`longitude`,numberCodec()],[`latitude`,numberCodec()]]));return{snapshot(t,n){let r=w(t);return r.issues?failCacheSnapshot():e.snapshot(r.value,n)},materialize(t,n){let r=w(e.materialize(t,n));return r.issues?failCacheSnapshot():r.value}}}function primitiveCodec(e,t){return{snapshot:e,materialize:t}}function materializeArray(e,t,n){return typeof e!=`object`||!e?failCacheSnapshot():withSnapshotObject(t,e,()=>n(readSnapshotArray(e)))}function cacheCodec(e,t){let n=shapeCodec(e.value,t),r=e.empty===null?nullableCodec(n):n;return Object.freeze({snapshot(e){try{return r.snapshot(e,new WeakSet)}catch(e){throw new y(`The operation result cannot be represented by the cache result codec.`,{cause:e instanceof Error?e:void 0,meta:{method:`snapshot`,operation:t}})}},materialize(e){try{return r.materialize(e,new WeakSet)}catch(e){throw new y(`The cached result snapshot is malformed.`,{cause:e instanceof Error?e:void 0,meta:{method:`materialize`,operation:t}})}}})}function shapeCodec(e,t){switch(e.kind){case`scalar`:return leafCodec(e,t);case`object`:{let n=new Map;for(let[r,i]of Object.entries(e.fields))n.set(r,shapeCodec(i,t));let r=recordCodec(n);return e.nullable===!1?r:nullableCodec(r)}case`collection`:return arrayCodec(shapeCodec(e.row,t));case`variants`:{let n=new Map;for(let[r,i]of Object.entries(e.arms))n.set(r,shapeCodec(e.many&&i.kind===`collection`?i.row:i,t));let r=taggedRelationCodec(n);return e.many?arrayCodec(r):nullableCodec(r)}case`recursive`:return recursiveRelationCodec({relation:e.relation,many:e.many,optional:e.optional,depth:e.recurrence.depth},shapeCodec(e.row,t))}}function leafCodec(e,t){let n=e.scalar,r;if(n)r=e.widened?compileWidenedSumCodec(n):compileScalarCodec(n,!1);else if(e.type===`boolean`)r=booleanCodec();else if(e.type===`int`)r=countCodec();else if(e.type===`number`)r=numberCodec();else throw new A(`Cannot cache a '${e.type}' result for '${t}': its scalar declaration is missing.`);return e.nullable?nullableCodec(r):r}function bindChain(e,t){let n=l(e);n!==void 0&&s(e,Object.freeze({driver:n.driver,version:n.version,waitUntil:n.waitUntil,scope:P(E({version:n.version,dialect:t.dialect,namespace:t.adapter.namespace}))}))}const Z=Object.freeze({admitMutationCacheOptions,bindChain,cacheCodec,cacheKeyOf,createCacheExecutionOptions,executeCachedResultOperation,invalidateManualCache,prepareMutationCacheWriteOutcome,readCacheExecutionOutcomes:M,readMutationCacheOptions,validateCacheableOperation});a(Z);function configurationError(e,t){throw new y(e,{cause:t===void 0?void 0:_(t)})}function isCacheDriver(e){try{return e instanceof R}catch(e){configurationError(`Cache extension driver capability could not be inspected.`,e)}}function snapshotConfig(e){r(e)||configurationError(`Cache extension configuration must be an object.`);let a;try{a=Reflect.ownKeys(e)}catch(e){configurationError(`Cache extension configuration could not be inspected.`,e)}for(let e of a)(typeof e!=`string`||e!==`driver`&&e!==`version`&&e!==`waitUntil`)&&configurationError(`Cache extension configuration has unknown member "${String(e)}".`);let read=t=>{if(a.includes(t))try{return e[t]}catch(e){configurationError(`Cache extension configuration member "${t}" could not be read.`,e)}},o=read(`driver`),s=read(`version`),c=read(`waitUntil`);return isCacheDriver(o)||configurationError(`Cache extension configuration requires a CacheDriver instance.`),s!==void 0&&!(i(s)||t(s)&&Number.isFinite(s))&&configurationError(`Cache extension configuration "version" must be a string or finite number.`),c!==void 0&&!n(c)&&configurationError(`Cache extension configuration "waitUntil" must be a function.`),Object.freeze({driver:o,version:s,waitUntil:c})}function cache(e){let t=snapshotConfig(e),query=({proceed:e})=>e();return o(query,t,Z),Object.freeze({name:u,query,controls:c})}export{R as CacheDriver,cache};
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{O as t,j as n,k as r}from"./error-mapping-B1-IWkCQ.mjs";import{t as i}from"./base-z-cH5ZBI.mjs";import{t as a}from"./extension-CGepsF-p.mjs";import{t as o}from"./methods-part-ZY0f2AV_.mjs";import{a as s,c,l}from"./on-ylYaKuRu.mjs";import{n as u,r as d,t as f}from"./args-764KdWMr.mjs";import{n as p,t as m}from"./call-Cz8XUmrl.mjs";import{t as h}from"./settled-BjyuA76m.mjs";import{n as g,r as _,t as v}from"./key-hxFFCKed.mjs";import{h as y,i as b}from"./unit-words-CT0yeqfZ.mjs";import{_ as x,a as S,c as C,d as w,f as T,g as E,h as D,i as O,l as k,m as A,n as j,o as M,p as N,r as P,s as F,t as I,u as L,v as R,y as z}from"./driver-BGVcgnIX.mjs";function step(e,n,r,i){try{return i()}catch(i){throw new t(r,{cause:i instanceof Error?i:void 0,meta:{method:e,operation:n}})}}function cacheCodec(e,t){return{run:()=>e.run(),snapshot:()=>step(`snapshot`,t,`The operation result cannot be represented by the cache result codec.`,()=>e.snapshot()),materialize:n=>step(`materialize`,t,`The cached result snapshot is malformed.`,()=>e.materialize(n))}}const validator=e=>({"~standard":{version:1,vendor:`viborm.cache`,validate:t=>({value:e(t)})}});function configurationError(e){throw new t(e)}function cache(e){let{driver:r,version:y,waitUntil:b,swr:E}=e;r instanceof j||configurationError(`Cache extension configuration requires a CacheDriver instance.`),y!==void 0&&!(typeof y==`string`||Number.isFinite(y))&&configurationError(`Cache extension configuration "version" must be a string or finite number.`),b!==void 0&&typeof b!=`function`&&configurationError(`Cache extension configuration "waitUntil" must be a function.`);let namespaceOf=({dialect:e,namespace:t})=>x({version:y,dialect:e,namespace:t}),invalidate=async(e,n,a)=>{try{let t=namespaceOf(g(e));await r[S](``,n,e,e=>C(t,e))}catch(e){throw a===void 0&&e instanceof i?e:new t(a?`Cache invalidation failed after mutation '${a.operation}' on model '${a.model}'.`:`Cache invalidation failed.`,{cause:e instanceof Error?e:void 0,meta:{method:`invalidate`,...a}})}};return a(`viborm.cache`,u({cache:f(validator(T)).on(l),cacheRead:d(validator(e=>{let t=N(e);return t.swr!==!1&&E===void 0&&configurationError(`A view's "swr" option needs the cache configured with it: cache({ driver, swr: staleWhileRevalidate }).`),t}))}),p(e=>{let t=e.values;if(t.cacheRead!==void 0)throw new n(e.operation,[...w]);let r=t.cache;A(r)&&h(e,({certainty:t})=>invalidate(e,r,{model:e.model,operation:e.operation,commitCertainty:t}))},c(l)),m(e=>{let t=e.values.cacheRead;if(t===void 0)return;let n=e.model;return i=>{if(i.mode!==`direct`)return i();let a=v(i);if(a===void 0)return i();let o=g(i);return r[M]({id:a,codec:cacheCodec(_(i),e.operation),read:t,namespace:namespaceOf(o),waitUntil:b,model:n,operation:e.operation,origin:i,database:o,revalidate:E})}},c(s),{inner:!0}),o(e=>({$withCache:t=>e.$bind({cacheRead:t}),$invalidate:(...t)=>h(e,()=>invalidate(e,{invalidate:t}))})))}const staleWhileRevalidate=e=>{let{request:t,entry:n,now:r}=e,i=t.read.swr;return i===!1||r-n.createdAt>=i||r>=n.expiresAt?!1:(z(refreshed(e),t.waitUntil),b(t.origin,k(`hit`,`stale`)),!0)};async function refreshed({request:e,key:t,backend:n,store:r}){try{if(!await R(n,t,!0))return}catch{return}let{codec:i}=e;await y(e.origin,{kind:`cache`,operation:`revalidate`,note:L(e,e.database)},async a=>{let o=!1,s,c;try{await i.run(),await r(i.snapshot()),c=k(`revalidate`,`success`,void 0,e)}catch(t){o=!0,s=t,c=k(`revalidate`,`error`,t,e)}try{await R(n,t,!1)}catch(e){s=o?AggregateError([s,e],`Cache revalidation work and cleanup both failed.`,{cause:s}):e,o=!0}if(b(a,c),o)throw s})}function unscoped(e){let t=e.startsWith(`${D}:`)?e:e?`${D}:${e}`:D;if(t===E||t.startsWith(`${E}:`))throw new r(`The official cache namespace is the cache extension's own: the public storage functions cannot address a key under it.`);return t}async function getEntry(e,t,n){return e[O](unscoped(t),n)}async function setEntry(e,t,n,r,i){return e[F](unscoped(t),n,r,i)}async function deleteEntry(e,t,n){return e[P](`delete`,unscoped(t),n)}async function clearEntries(e,t,n){return e[P](`clear`,unscoped(t??``),n)}async function invalidateEntries(e,t,n,r){return e[S](`${t}:`,n,r,unscoped)}async function markRevalidating(e,t){return R(e[I](),unscoped(t),!0)}async function clearRevalidating(e,t){await R(e[I](),unscoped(t),!1)}export{j as CacheDriver,cache,clearEntries,clearRevalidating,deleteEntry,getEntry,invalidateEntries,markRevalidating,setEntry,staleWhileRevalidate};
2
2
  //# sourceMappingURL=cache.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"cache.mjs","names":["cache","settled","state"],"sources":["../src/query-engine/cache-flow.ts","../src/query-engine/result/cache-snapshot-structure.ts","../src/query-engine/result/cache-json-codec.ts","../src/query-engine/result/cache-value-codecs.ts","../src/query-engine/raptor3/route/cache-codec.ts","../src/cache/runtime.ts","../src/cache/extension.ts"],"sourcesContent":["import type { CacheDriver, CacheExecutionOptions } from \"@cache/driver\";\nimport {\n type DetachedCacheResultCodec,\n executeCachedWithResultCodec,\n invalidateOfficialCache,\n type WaitUntilFn,\n} from \"@cache/driver\";\nimport { stableStringify } from \"@cache/key\";\nimport {\n type CacheInvalidationOptions,\n cacheInvalidationSchema,\n type WithCacheOptions,\n withCacheSchema,\n} from \"@cache/schema\";\nimport type { DriverIdentity } from \"@drivers/driver-identity\";\nimport type { QueryExecutionContext } from \"@drivers/exports\";\nimport {\n CacheConfigurationError,\n CacheOperationNotCacheableError,\n} from \"@errors\";\nimport { isAdmittedRows, isImmutableRowData } from \"@extensions/admission\";\nimport type { ResolvedExtensionChain } from \"@extensions/chain\";\nimport type { RowsContribution } from \"@extensions/controls\";\nimport {\n type AdmittedControls,\n isStableControlValue,\n} from \"@extensions/controls\";\nimport type { WriteOutcomeRegistration } from \"@extensions/query\";\nimport { admittedRowsOf, isLazy } from \"@extensions/rows\";\nimport type { LazyRelations } from \"@query-engine/raptor3/shared/row-scope\";\nimport type { Input } from \"@query-engine/raptor3/shared/schema\";\nimport { parse } from \"@validation\";\nimport { readValidationFailureCause } from \"@validation/parse-failure\";\nimport { sha256 } from \"@validation/primitives/sha256\";\nimport { isRecord } from \"@validation/value-guards\";\nimport { errorCause } from \"../errors/diagnostic-safety\";\nimport { isWriteOperation } from \"./routed-operations\";\n\nconst CACHEABLE_OPERATIONS: Set<string> = new Set([\n \"findFirst\",\n \"findMany\",\n \"findUnique\",\n \"findUniqueOrThrow\",\n \"findFirstOrThrow\",\n \"count\",\n \"aggregate\",\n \"groupBy\",\n \"exist\",\n]);\n\n/** Every option object the cache's control admitted, for its typed read. */\nconst admittedMutationOptions = new WeakMap<object, CacheInvalidationOptions>();\n\n/**\n * The cache's own parser, run by core's control admission (the declaration is\n * `officialCacheControls` in `@cache/capability`). `parse` returns a thrown\n * validator as issues, so every refusal here is one `CacheConfigurationError`.\n */\nexport function admitMutationCacheOptions(\n cache: unknown\n): CacheInvalidationOptions {\n const parsed = parse(cacheInvalidationSchema, cache);\n if (parsed.issues) {\n throw new CacheConfigurationError(\n `Invalid mutation cache options: ${parsed.issues.map((issue) => issue.message).join(\", \")}`,\n { cause: readValidationFailureCause(parsed) }\n );\n }\n const invalidate =\n parsed.value.invalidate === undefined\n ? undefined\n : [...parsed.value.invalidate];\n // Deeply frozen: admission keeps an immutable value as it is, so this\n // object stays the one the WeakMap below finds.\n if (invalidate) Object.freeze(invalidate);\n const options: CacheInvalidationOptions = Object.freeze({\n autoInvalidate: parsed.value.autoInvalidate,\n ...(invalidate === undefined ? {} : { invalidate }),\n });\n admittedMutationOptions.set(options, options);\n return options;\n}\n\n/** The mutation options a call's `cache` control admitted, if it gave one. */\nexport function readMutationCacheOptions(\n controls: AdmittedControls | undefined\n): CacheInvalidationOptions | undefined {\n const admitted = controls?.cache;\n return isRecord(admitted) ? admittedMutationOptions.get(admitted) : undefined;\n}\n\n/**\n * What one cached read is keyed on. A read that admitted no control keeps\n * today's key, the prepared arguments byte for byte; otherwise the key is the\n * pair of those arguments and the admitted controls, which no base key can\n * spell (its arguments are always an object), and, on a chain with `rows`,\n * those declarations themselves, since the same control value selects\n * different rows under different declarations; on a chain with `order`, the\n * triple of a tag, that key and the orders. A control value that is not\n * plain data has no canonical form: `undefined` bypasses the cache.\n */\nexport function cacheKeyOf(\n args: Record<string, unknown>,\n controls: AdmittedControls | undefined,\n rows: ResolvedExtensionChain[\"rows\"],\n order?: ResolvedExtensionChain[\"order\"]\n): unknown {\n // A chain's default orders decide which rows a read returns and in what\n // order, for its root model and every model it projects: they key every\n // entry, so two chains that order differently never share one.\n if (order !== undefined) {\n const key = cacheKeyOf(args, controls, rows);\n return key === undefined ? undefined : [\"order\", key, order];\n }\n if (controls === undefined) return args;\n // Only values admission fixed key a cache entry: the rows the read's SQL\n // binds were bound from those same values (`snapshotControlValue` in controls.ts).\n if (!Object.values(controls).every(isStableControlValue)) return undefined;\n if (rows === undefined) return [args, controls];\n try {\n return [args, controls, rows.map(rowsIdentity)];\n } catch {\n // A rows member compiled on first use could not settle (a model it\n // refuses): the read goes uncached, and fails only if it needs that\n // model itself.\n return undefined;\n }\n}\n\nexport { isCacheManagedExecution } from \"@cache/capability\";\n\n/** Prepare the cache listener consumed by the shared write-outcome rail. */\nexport function prepareMutationCacheWriteOutcome(\n cache: CacheDriver,\n modelName: string,\n operation: string,\n options: CacheInvalidationOptions | undefined,\n context: QueryExecutionContext,\n officialScope: object\n): WriteOutcomeRegistration | undefined {\n if (!isWriteOperation(operation)) return undefined;\n\n return Object.freeze({\n extension: \"viborm.cache\",\n failurePolicy: \"boundary-owned\",\n listener: async (outcome) => {\n try {\n await invalidateOfficialCache(\n cache,\n modelName,\n options,\n context,\n officialScope\n );\n } catch (error) {\n throw new CacheConfigurationError(\n `Cache invalidation failed after mutation '${operation}' on model '${modelName}'.`,\n {\n cause: errorCause(error),\n meta: {\n method: \"invalidate\",\n model: modelName,\n operation,\n commitCertainty: outcome.certainty,\n },\n }\n );\n }\n },\n });\n}\n\nexport function validateCacheableOperation(operation: string): void {\n if (CACHEABLE_OPERATIONS.has(operation)) {\n return;\n }\n\n throw new CacheOperationNotCacheableError(operation, [\n ...CACHEABLE_OPERATIONS,\n ]);\n}\n\nexport function createCacheExecutionOptions(\n config: WithCacheOptions | undefined,\n waitUntil: WaitUntilFn | undefined,\n driverIdentity: DriverIdentity | undefined\n): CacheExecutionOptions {\n const parsed = parse(withCacheSchema, config);\n if (parsed.issues) {\n throw new CacheConfigurationError(\n `Invalid cache options: ${parsed.issues.map((issue) => issue.message).join(\", \")}`,\n { cause: readValidationFailureCause(parsed) }\n );\n }\n\n const { bypass, key, ttl, swr } = parsed.value;\n\n return {\n ttlMs: ttl,\n swr: resolveSwr(swr, ttl),\n bypass,\n key,\n waitUntil,\n driverIdentity,\n };\n}\n\n/**\n * The detached cache representation of one read result: the cache driver's\n * own contract, read here at the boundary that hands the Raptor 3 route's\n * `cacheCodec` to it.\n */\nexport type CacheResultCodec = DetachedCacheResultCodec<unknown>;\n\n/** Execute an official read through the detached result representation. */\nexport function executeCachedResultOperation(\n cache: CacheDriver,\n modelName: string,\n operation: string,\n args: unknown,\n executor: () => Promise<unknown>,\n options: CacheExecutionOptions,\n codec: CacheResultCodec,\n officialScope: object\n): Promise<unknown> {\n return executeCachedWithResultCodec(\n cache,\n modelName,\n operation,\n args,\n executor,\n options,\n codec,\n officialScope\n );\n}\n\nexport async function invalidateManualCache(\n cache: CacheDriver,\n keys: string[],\n context: QueryExecutionContext | undefined,\n officialScope: object\n): Promise<void> {\n const invalidate = [...keys];\n const options = Object.freeze({ invalidate });\n await invalidateOfficialCache(\n cache,\n \"manual\",\n options,\n context,\n officialScope\n );\n}\n\nfunction resolveSwr(\n swr: boolean | number | undefined,\n ttlMs: number\n): number | false {\n if (swr === undefined || swr === false) {\n return false;\n }\n if (swr === true) {\n return ttlMs * 2;\n }\n return ttlMs + swr;\n}\n\n/** What admission leaves in place of a lazy entry's predicate: its resolver. */\ntype Lazy<T> = () => T;\n\n/**\n * `rows` with every lazy entry resolved, for what reads the definition as a\n * whole (a cache key): the same object when it names none. Resolving one\n * compiles it, so this is never on a call's own path.\n */\nconst settled = new WeakMap<RowsContribution, RowsContribution>();\nfunction settledRows(rows: RowsContribution): RowsContribution {\n const lazyCycles = Object.values(rows.verbs ?? {}).some(\n (entry) =>\n typeof entry !== \"function\" &&\n typeof entry.acyclic === \"object\" &&\n !Array.isArray(entry.acyclic)\n );\n if (!(isLazy(rows) || lazyCycles)) return rows;\n const known = settled.get(rows);\n if (known) return known;\n const verbs = Object.fromEntries(\n Object.entries(rows.verbs!).map(([model, entry]) => {\n const resolved = typeof entry === \"function\" ? entry() : entry;\n const acyclic = resolved.acyclic as\n | readonly string[]\n | LazyRelations\n | undefined;\n return [\n model,\n acyclic === undefined || Array.isArray(acyclic)\n ? resolved\n : Object.freeze({\n ...resolved,\n acyclic: (acyclic as LazyRelations).resolve(),\n }),\n ];\n })\n );\n const models = Object.fromEntries(\n Object.entries(rows.models).map(([model, modes]) => [\n model,\n Object.fromEntries(\n Object.entries(modes).map(([mode, purposes]) => [\n mode,\n Object.fromEntries(\n Object.entries(purposes).map(([purpose, where]) => [\n purpose,\n typeof where === \"function\" ? (where as Lazy<Input>)() : where,\n ])\n ),\n ])\n ),\n ])\n );\n const result = Object.freeze({ ...rows, models, verbs });\n settled.set(rows, result);\n return result;\n}\n\n/**\n * A `rows` member as a cache key holds it: everything it says, every lazy\n * entry resolved (a cache shared across isolates must tell two policies apart\n * by content). For rows admission owns and nobody can change, a SHA-256\n * digest computed once; other rows are keyed by their content, read afresh.\n */\nconst identities = new WeakMap<RowsContribution, string>();\nfunction rowsIdentity(chained: RowsContribution): unknown {\n const rows = admittedRowsOf(chained);\n const known = identities.get(rows);\n if (known !== undefined) return known;\n const settled = settledRows(rows);\n // Memoised only where nothing it says can change: rows admission owns, and\n // every entry they resolved to deeply frozen.\n if (\n !(\n isAdmittedRows(rows) &&\n Object.values(settled.verbs ?? {}).every((entry) =>\n isImmutableRowData(entry)\n )\n )\n )\n return settled;\n const digest = sha256(new TextEncoder().encode(stableStringify(settled)));\n const identity = Array.from(digest, (byte) =>\n byte.toString(16).padStart(2, \"0\")\n ).join(\"\");\n identities.set(rows, identity);\n return identity;\n}\n","export class CacheSnapshotFailure extends Error {}\n\nexport function failCacheSnapshot(): never {\n throw new CacheSnapshotFailure();\n}\n\nexport function readSnapshotArray(value: unknown): readonly unknown[] {\n if (\n !Array.isArray(value) ||\n Object.getPrototypeOf(value) !== Array.prototype\n ) {\n return failCacheSnapshot();\n }\n const keys = Reflect.ownKeys(value);\n const lengthDescriptor = Reflect.getOwnPropertyDescriptor(value, \"length\");\n const length = lengthDescriptor?.value;\n if (\n typeof length !== \"number\" ||\n !Number.isSafeInteger(length) ||\n length < 0 ||\n keys.length !== length + 1 ||\n keys[length] !== \"length\"\n ) {\n return failCacheSnapshot();\n }\n const items = new Array<unknown>(length);\n for (let index = 0; index < length; index += 1) {\n const key = String(index);\n if (keys[index] !== key) return failCacheSnapshot();\n const descriptor = Reflect.getOwnPropertyDescriptor(value, key);\n if (!(descriptor && \"value\" in descriptor && descriptor.enumerable)) {\n return failCacheSnapshot();\n }\n items[index] = descriptor.value;\n }\n return items;\n}\n\nexport function readSnapshotRecord(\n value: unknown,\n allowNullPrototype = false\n): readonly (readonly [string, unknown])[] {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return failCacheSnapshot();\n }\n const prototype = Object.getPrototypeOf(value);\n if (\n prototype !== Object.prototype &&\n !(allowNullPrototype && prototype === null)\n ) {\n return failCacheSnapshot();\n }\n const keys = Reflect.ownKeys(value);\n const entries: (readonly [string, unknown])[] = new Array(keys.length);\n for (let index = 0; index < keys.length; index += 1) {\n const key = keys[index];\n if (typeof key !== \"string\") return failCacheSnapshot();\n const descriptor = Reflect.getOwnPropertyDescriptor(value, key);\n if (!(descriptor && \"value\" in descriptor && descriptor.enumerable)) {\n return failCacheSnapshot();\n }\n entries[index] = [key, descriptor.value];\n }\n return entries;\n}\n\nexport function defineSnapshotProperty(\n target: Record<string, unknown>,\n key: string,\n value: unknown\n): void {\n Object.defineProperty(target, key, {\n configurable: true,\n enumerable: true,\n value,\n writable: true,\n });\n}\n\n/**\n * Enter an object on the active path, refusing one already on it: the rule a\n * cyclic value or snapshot meets at its first re-entry. An iterative walk,\n * whose path no callback scope can span, leaves the object itself.\n */\nexport function enterSnapshotObject(\n active: WeakSet<object>,\n value: object\n): void {\n if (active.has(value)) failCacheSnapshot();\n active.add(value);\n}\n\nexport function withSnapshotObject<T>(\n active: WeakSet<object>,\n value: object,\n read: () => T\n): T {\n enterSnapshotObject(active, value);\n try {\n return read();\n } finally {\n active.delete(value);\n }\n}\n\nexport function encodeSnapshotNumber(value: unknown): string {\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n return failCacheSnapshot();\n }\n return Object.is(value, -0) ? \"-0\" : String(value);\n}\n\nexport function decodeSnapshotNumber(value: unknown): number {\n if (typeof value !== \"string\") return failCacheSnapshot();\n const parsed = Number(value);\n if (!Number.isFinite(parsed) || encodeSnapshotNumber(parsed) !== value) {\n return failCacheSnapshot();\n }\n return parsed;\n}\n\nexport function encodeSnapshotCount(value: unknown): string {\n if (typeof value !== \"number\" || !Number.isSafeInteger(value) || value < 0) {\n return failCacheSnapshot();\n }\n return String(value);\n}\n\nexport function decodeSnapshotCount(value: unknown): number {\n const parsed = decodeSnapshotNumber(value);\n if (!Number.isSafeInteger(parsed) || parsed < 0) {\n return failCacheSnapshot();\n }\n return parsed;\n}\n","import {\n decodeSnapshotNumber,\n defineSnapshotProperty,\n encodeSnapshotNumber,\n failCacheSnapshot,\n readSnapshotArray,\n readSnapshotRecord,\n withSnapshotObject,\n} from \"./cache-snapshot-structure\";\n\nconst JSON_NULL = \"null\";\nconst JSON_STRING = \"string\";\nconst JSON_BOOLEAN = \"boolean\";\nconst JSON_NUMBER = \"number\";\nconst JSON_ARRAY = \"array\";\nconst JSON_OBJECT = \"object\";\n\nexport function snapshotJsonValue(\n value: unknown,\n active: WeakSet<object>\n): unknown {\n if (value === null) return [JSON_NULL];\n if (typeof value === \"string\") return [JSON_STRING, value];\n if (typeof value === \"boolean\") return [JSON_BOOLEAN, value];\n if (typeof value === \"number\") {\n return [JSON_NUMBER, encodeSnapshotNumber(value)];\n }\n if (Array.isArray(value)) {\n return withSnapshotObject(active, value, () => [\n JSON_ARRAY,\n readSnapshotArray(value).map((item) => snapshotJsonValue(item, active)),\n ]);\n }\n if (typeof value === \"object\" && value !== null) {\n return withSnapshotObject(active, value, () => [\n JSON_OBJECT,\n readSnapshotRecord(value, true).map(([key, item]) => [\n key,\n snapshotJsonValue(item, active),\n ]),\n ]);\n }\n return failCacheSnapshot();\n}\n\nexport function materializeJsonValue(\n snapshot: unknown,\n active: WeakSet<object>\n): unknown {\n if (typeof snapshot !== \"object\" || snapshot === null) {\n return failCacheSnapshot();\n }\n return withSnapshotObject(active, snapshot, () => {\n const node = readSnapshotArray(snapshot);\n const tag = node[0];\n if (tag === JSON_NULL && node.length === 1) return null;\n if (\n tag === JSON_STRING &&\n node.length === 2 &&\n typeof node[1] === \"string\"\n ) {\n return node[1];\n }\n if (\n tag === JSON_BOOLEAN &&\n node.length === 2 &&\n typeof node[1] === \"boolean\"\n ) {\n return node[1];\n }\n if (tag === JSON_NUMBER && node.length === 2) {\n return decodeSnapshotNumber(node[1]);\n }\n if (tag === JSON_ARRAY && node.length === 2) {\n return materializeJsonArray(node[1], active);\n }\n if (tag === JSON_OBJECT && node.length === 2) {\n return materializeJsonObject(node[1], active);\n }\n return failCacheSnapshot();\n });\n}\n\nfunction materializeJsonArray(\n snapshot: unknown,\n active: WeakSet<object>\n): unknown[] {\n if (typeof snapshot !== \"object\" || snapshot === null) {\n return failCacheSnapshot();\n }\n return withSnapshotObject(active, snapshot, () =>\n readSnapshotArray(snapshot).map((item) =>\n materializeJsonValue(item, active)\n )\n );\n}\n\nfunction materializeJsonObject(\n snapshot: unknown,\n active: WeakSet<object>\n): Record<string, unknown> {\n if (typeof snapshot !== \"object\" || snapshot === null) {\n return failCacheSnapshot();\n }\n return withSnapshotObject(active, snapshot, () => {\n const entries = readSnapshotArray(snapshot);\n const result: Record<string, unknown> = {};\n const seen = new Set<string>();\n for (const entry of entries) {\n if (typeof entry !== \"object\" || entry === null) {\n return failCacheSnapshot();\n }\n const pair = withSnapshotObject(active, entry, () =>\n readSnapshotArray(entry)\n );\n const key = pair[0];\n if (pair.length !== 2 || typeof key !== \"string\" || seen.has(key)) {\n return failCacheSnapshot();\n }\n seen.add(key);\n defineSnapshotProperty(\n result,\n key,\n materializeJsonValue(pair[1], active)\n );\n }\n return result;\n });\n}\n","import type { Scalar } from \"@schema/scalars\";\nimport {\n canonicalizeMaterializedDecimal,\n type DecimalDescriptor,\n decodeFieldScalar,\n decodeWidenedSum,\n toDecimal,\n} from \"@validation/primitives/decimal-codec\";\nimport { validateGeoPoint } from \"@validation/primitives/geo-point-codec\";\nimport { carriesRepeatedKey } from \"@validation/relations/recurrence\";\nimport { materializeJsonValue, snapshotJsonValue } from \"./cache-json-codec\";\nimport {\n decodeSnapshotCount,\n decodeSnapshotNumber,\n defineSnapshotProperty,\n encodeSnapshotCount,\n encodeSnapshotNumber,\n enterSnapshotObject,\n failCacheSnapshot,\n readSnapshotArray,\n readSnapshotRecord,\n withSnapshotObject,\n} from \"./cache-snapshot-structure\";\n\nconst NORMALIZED_TIME = /^(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d{1,3})?$/;\n\nexport interface ValueCodec {\n snapshot(value: unknown, active: WeakSet<object>): unknown;\n materialize(snapshot: unknown, active: WeakSet<object>): unknown;\n}\n\nexport function compileScalarCodec(\n scalar: Scalar,\n useDeclaredNullability = true\n): ValueCodec {\n let item: ValueCodec;\n if (\"enumValues\" in scalar) {\n item = enumCodec(new Set(scalar.enumValues));\n } else {\n const state = scalar[\"~\"].state;\n // biome-ignore lint/style/useDefaultSwitchClause: the scalar state union is exhaustive; a default would be dead code.\n switch (state.type) {\n case \"string\":\n item = stringCodec();\n break;\n case \"time\":\n item = timeCodec();\n break;\n case \"int\":\n item = integerCodec();\n break;\n case \"number\":\n item = numberCodec();\n break;\n case \"decimal\":\n item = decimalCodec(state.decimal);\n break;\n case \"boolean\":\n item = booleanCodec();\n break;\n case \"bigint\":\n item = bigintCodec();\n break;\n case \"datetime\":\n item = dateCodec(false);\n break;\n case \"date\":\n item = dateCodec(true);\n break;\n case \"json\":\n item = jsonCodec();\n break;\n case \"vector\":\n item = vectorCodec(state.dimension);\n break;\n case \"blob\":\n item = bytesCodec();\n break;\n case \"point\":\n item = pointCodec();\n break;\n }\n }\n const state = scalar[\"~\"].state;\n const value = state.array ? arrayCodec(item) : item;\n return useDeclaredNullability && state.nullable\n ? nullableCodec(value)\n : value;\n}\n\nexport function taggedRelationCodec(\n variants: ReadonlyMap<string, ValueCodec>\n): ValueCodec {\n return {\n snapshot(value, active) {\n if (typeof value !== \"object\" || value === null) {\n return failCacheSnapshot();\n }\n return withSnapshotObject(active, value, () => {\n const entries = readSnapshotRecord(value);\n if (entries.length !== 2) return failCacheSnapshot();\n let type: string | undefined;\n let data: unknown;\n for (const [key, item] of entries) {\n if (key === \"type\" && typeof item === \"string\") type = item;\n else if (key === \"data\") data = item;\n else return failCacheSnapshot();\n }\n const target = type === undefined ? undefined : variants.get(type);\n if (!target || data === undefined || data === null)\n return failCacheSnapshot();\n return entries.map(([key, item]) => [\n key,\n key === \"type\" ? type : target.snapshot(item, active),\n ]);\n });\n },\n materialize(snapshot, active) {\n return materializeArray(snapshot, active, (entries) => {\n if (entries.length !== 2) return failCacheSnapshot();\n const decoded = readEncodedEntries(entries, active);\n let type: string | undefined;\n let dataSnapshot: unknown;\n for (const [key, item] of decoded) {\n if (key === \"type\" && typeof item === \"string\") type = item;\n else if (key === \"data\") dataSnapshot = item;\n else return failCacheSnapshot();\n }\n const target = type === undefined ? undefined : variants.get(type);\n if (!target || dataSnapshot === undefined || dataSnapshot === null)\n return failCacheSnapshot();\n const result: Record<string, unknown> = {};\n for (const [key] of decoded) {\n defineSnapshotProperty(\n result,\n key,\n key === \"type\" ? type : target.materialize(dataSnapshot, active)\n );\n }\n return result;\n });\n },\n };\n}\n\nexport function recordCodec(\n fields: ReadonlyMap<string, ValueCodec>\n): ValueCodec {\n return {\n snapshot(value, active) {\n if (typeof value !== \"object\" || value === null) {\n return failCacheSnapshot();\n }\n return withSnapshotObject(active, value, () => {\n const entries = readSnapshotRecord(value);\n if (entries.length !== fields.size) return failCacheSnapshot();\n const seen = new Set<string>();\n return entries.map(([key, item]) => {\n const field = fields.get(key);\n if (!field || seen.has(key)) return failCacheSnapshot();\n seen.add(key);\n return [key, field.snapshot(item, active)];\n });\n });\n },\n materialize(snapshot, active) {\n return materializeArray(snapshot, active, (entries) => {\n if (entries.length !== fields.size) return failCacheSnapshot();\n const decoded = readEncodedEntries(entries, active);\n const seen = new Set<string>();\n const result: Record<string, unknown> = {};\n for (const [key, item] of decoded) {\n const field = fields.get(key);\n if (!field || seen.has(key)) return failCacheSnapshot();\n seen.add(key);\n defineSnapshotProperty(result, key, field.materialize(item, active));\n }\n return result;\n });\n },\n };\n}\n\nexport function arrayCodec(item: ValueCodec): ValueCodec {\n return {\n snapshot(value, active) {\n if (!Array.isArray(value)) return failCacheSnapshot();\n return withSnapshotObject(active, value, () =>\n readSnapshotArray(value).map((entry) => item.snapshot(entry, active))\n );\n },\n materialize(snapshot, active) {\n return materializeArray(snapshot, active, (entries) =>\n entries.map((entry) => item.materialize(entry, active))\n );\n },\n };\n}\n\nexport function nullableCodec(value: ValueCodec): ValueCodec {\n return {\n snapshot(input, active) {\n return input === null ? null : value.snapshot(input, active);\n },\n materialize(snapshot, active) {\n return snapshot === null ? null : value.materialize(snapshot, active);\n },\n };\n}\n\n/** The prepared facts of one recursive relation slot a cache entry keeps. */\ninterface RecursiveRelationSlot {\n /** The asking relation: the key every continued occurrence repeats. */\n readonly relation: string;\n /** An array of occurrences, or one occurrence. */\n readonly many: boolean;\n /** Whether a singular slot may end in `null`; a collection ends in `[]`. */\n readonly optional: boolean;\n /** The numeric cutoff level, or `false` for an exhaustive traversal. */\n readonly depth: number | false;\n}\n\n/**\n * One recursive relation slot, stored and restored exactly as it was published.\n *\n * The decoder already answered every traversal question — which rows, which\n * paths, which cycles to refuse or prune — so this codec asks none of them and\n * never reads an identity. The slot's own occurrences are level 1; an\n * occurrence at level `L` carries the repeated key exactly when\n * `depth === false || L < depth`, holding the level `L + 1` slot, and at the\n * numeric cutoff the key is ABSENT. Its snapshot is a tuple stating the same\n * fact — `[node]` at the cutoff, `[node, slot]` before it — and both directions\n * hold their input to it. `node` is the ORDINARY node codec: the repeated key\n * is separated from the occurrence's own fields, which keep its exact-key\n * checks, and is defined back onto the fresh node it materializes.\n *\n * Data depth is iterated, never recursed: a chain is as deep as its data, and\n * the call stack holds only the finite projection. One enter/leave discipline\n * serves both directions — an occurrence joins the SAME active set every\n * ordinary codec uses and leaves it when its own slot completes — so a cyclic\n * value or snapshot is refused at its first re-entry, while one row published\n * as two objects is two occurrences, not a cycle.\n */\nexport function recursiveRelationCodec(\n slot: RecursiveRelationSlot,\n node: ValueCodec\n): ValueCodec {\n return {\n snapshot: (value, active) =>\n walkRecursiveSlot(value, active, slot, {\n read(occurrence) {\n const own: Record<string, unknown> = {};\n const successors: unknown[] = [];\n for (const [key, item] of readSnapshotRecord(occurrence)) {\n if (key === slot.relation) successors.push(item);\n else defineSnapshotProperty(own, key, item);\n }\n return [node.snapshot(own, active), successors];\n },\n write: (row, successors) => [row, ...successors],\n }),\n materialize: (snapshot, active) =>\n walkRecursiveSlot(snapshot, active, slot, {\n read(occurrence) {\n const [row, ...successors] = readSnapshotArray(occurrence);\n return [node.materialize(row, active), successors];\n },\n write(row, successors) {\n // `node` is the ordinary record codec, whose answer is a fresh record.\n if (successors.length > 0) {\n defineSnapshotProperty(\n row as Record<string, unknown>,\n slot.relation,\n successors[0]\n );\n }\n return row;\n },\n }),\n };\n}\n\n/** One direction of a recursive slot, over one entered occurrence. */\ninterface RecursiveDirection {\n /** The occurrence's node output, and the slot inputs it holds. */\n read(\n occurrence: object\n ): readonly [node: unknown, successors: readonly unknown[]];\n /** The occurrence's output: its node output, and its slot output if any. */\n write(node: unknown, successors: readonly unknown[]): unknown;\n}\n\n/**\n * One slot on the walk's current path: the occurrences it holds, the outputs\n * already written for them, and the occurrence that repeats it (none for the\n * outer slot) with that occurrence's node output.\n */\ninterface RecursiveFrame {\n readonly level: number;\n readonly occurrences: readonly unknown[];\n readonly outputs: unknown[];\n readonly owner: object | undefined;\n readonly node: unknown;\n next: number;\n}\n\n/**\n * Walk one recursive slot with an explicit stack of the slots on the current\n * path. An occurrence is entered when it is reached and left when its own slot\n * completes, so the active set holds exactly the occurrences on the path: every\n * cycle a slot can close passes through one of them.\n */\nfunction walkRecursiveSlot(\n value: unknown,\n active: WeakSet<object>,\n slot: RecursiveRelationSlot,\n direction: RecursiveDirection\n): unknown {\n const open = (\n input: unknown,\n level: number,\n owner?: object,\n node?: unknown\n ): RecursiveFrame => {\n let occurrences: readonly unknown[];\n if (slot.many) occurrences = readSnapshotArray(input);\n else if (input !== null) occurrences = [input];\n else occurrences = slot.optional ? [] : failCacheSnapshot();\n return { level, occurrences, outputs: [], owner, node, next: 0 };\n };\n const stack: RecursiveFrame[] = [open(value, 1)];\n let published: unknown;\n while (stack.length > 0) {\n const frame = stack.at(-1) as RecursiveFrame;\n if (frame.next < frame.occurrences.length) {\n const occurrence = frame.occurrences[frame.next];\n frame.next += 1;\n if (typeof occurrence !== \"object\" || occurrence === null) {\n return failCacheSnapshot();\n }\n enterSnapshotObject(active, occurrence);\n const continues = carriesRepeatedKey(slot.depth, frame.level);\n const [node, successors] = direction.read(occurrence);\n // The repeated slot exists exactly when the occurrence continues.\n if (successors.length !== (continues ? 1 : 0)) {\n return failCacheSnapshot();\n }\n if (continues) {\n stack.push(open(successors[0], frame.level + 1, occurrence, node));\n continue;\n }\n active.delete(occurrence);\n frame.outputs.push(direction.write(node, successors));\n continue;\n }\n stack.pop();\n const output = slot.many ? frame.outputs : (frame.outputs[0] ?? null);\n if (frame.owner === undefined) {\n published = output;\n continue;\n }\n // A repeated slot's owner sits in the frame beneath it.\n const parent = stack.at(-1) as RecursiveFrame;\n active.delete(frame.owner);\n parent.outputs.push(direction.write(frame.node, [output]));\n }\n return published;\n}\n\nexport function booleanCodec(): ValueCodec {\n return primitiveCodec(\n (value) => (typeof value === \"boolean\" ? value : failCacheSnapshot()),\n (snapshot) =>\n typeof snapshot === \"boolean\" ? snapshot : failCacheSnapshot()\n );\n}\n\nexport function numberCodec(): ValueCodec {\n return primitiveCodec(encodeSnapshotNumber, decodeSnapshotNumber);\n}\n\nexport function countCodec(): ValueCodec {\n return primitiveCodec(encodeSnapshotCount, decodeSnapshotCount);\n}\n\nfunction readEncodedEntries(\n entries: readonly unknown[],\n active: WeakSet<object>\n): readonly (readonly [string, unknown])[] {\n const decoded: (readonly [string, unknown])[] = new Array(entries.length);\n for (let index = 0; index < entries.length; index += 1) {\n decoded[index] = materializeArray(entries[index], active, (pair) => {\n if (pair.length !== 2 || typeof pair[0] !== \"string\") {\n return failCacheSnapshot();\n }\n return [pair[0], pair[1]];\n });\n }\n return decoded;\n}\n\nfunction stringCodec(): ValueCodec {\n return primitiveCodec(\n (value) => (typeof value === \"string\" ? value : failCacheSnapshot()),\n (snapshot) =>\n typeof snapshot === \"string\" ? snapshot : failCacheSnapshot()\n );\n}\n\nfunction timeCodec(): ValueCodec {\n return primitiveCodec(\n (value) =>\n typeof value === \"string\" && NORMALIZED_TIME.test(value)\n ? value\n : failCacheSnapshot(),\n (snapshot) =>\n typeof snapshot === \"string\" && NORMALIZED_TIME.test(snapshot)\n ? snapshot\n : failCacheSnapshot()\n );\n}\n\nfunction enumCodec(values: ReadonlySet<string>): ValueCodec {\n return primitiveCodec(\n (value) =>\n typeof value === \"string\" && values.has(value)\n ? value\n : failCacheSnapshot(),\n (snapshot) =>\n typeof snapshot === \"string\" && values.has(snapshot)\n ? snapshot\n : failCacheSnapshot()\n );\n}\n\nfunction integerCodec(): ValueCodec {\n return primitiveCodec(\n (value) => {\n if (typeof value !== \"number\" || !Number.isSafeInteger(value)) {\n return failCacheSnapshot();\n }\n return encodeSnapshotNumber(value);\n },\n (snapshot) => {\n const value = decodeSnapshotNumber(snapshot);\n return Number.isSafeInteger(value) ? value : failCacheSnapshot();\n }\n );\n}\n\n/**\n * The cache's two directions across the decimal boundary.\n *\n * A snapshot is DETACHED: the memory backend keeps it by reference and the KV\n * backend puts it through `JSON.stringify`, so a `Decimal` that reached a\n * snapshot would survive in one store and arrive as `{\"s\":1,\"e\":0,\"d\":[12]}` in\n * the other. It is therefore stored as canonical text and rebuilt as a FRESH\n * instance on every hit, which is also what keeps a caller who mutates a\n * returned value from poisoning the next one.\n *\n * BOTH directions are held to the field's domain, for two different reasons.\n * Reading, because a stored entry outlives the schema that wrote it and nothing\n * in the cache key says which precision and scale were in force when it was\n * written. Writing, because a value outside the domain is an incoherent parsed\n * result — and refusing it at the WRITE is what makes that visible when it\n * happens, instead of storing an entry every subsequent hit refuses for the rest\n * of its TTL.\n */\nfunction decimalCodec(descriptor: DecimalDescriptor | undefined): ValueCodec {\n return primitiveCodec(\n (value) => {\n if (!descriptor) return failCacheSnapshot();\n return (\n decodeFieldScalar(canonicalizeMaterializedDecimal(value), descriptor) ??\n failCacheSnapshot()\n );\n },\n (snapshot) => {\n if (!descriptor) return failCacheSnapshot();\n const canonical = decodeFieldScalar(snapshot, descriptor);\n return canonical !== undefined && canonical === snapshot\n ? toDecimal(canonical)\n : failCacheSnapshot();\n }\n );\n}\n\n/** The snapshot spelling of an infinite number sum, as `String` writes it. */\nconst INFINITE_SUMS: ReadonlyMap<unknown, number> = new Map([\n [\"Infinity\", Number.POSITIVE_INFINITY],\n [\"-Infinity\", Number.NEGATIVE_INFINITY],\n]);\n\n/**\n * The SUM leaf's cache boundary: the field's scale, deliberately not the\n * field's precision, so a cached sum materializes exactly like a fresh one. The\n * write is held to the same scale for the same reason the scalar write is.\n * A number sum is a double that may be `±Infinity` (engine-10), an int sum a\n * double that may pass 2^53, and a bigint sum any integer.\n */\nexport function compileWidenedSumCodec(scalar: Scalar): ValueCodec {\n const { type } = scalar[\"~\"].state;\n if (type === \"bigint\") return bigintCodec();\n if (type === \"number\" || type === \"int\")\n return primitiveCodec(\n (value) =>\n value === Number.POSITIVE_INFINITY || value === Number.NEGATIVE_INFINITY\n ? String(value)\n : encodeSnapshotNumber(value),\n (snapshot) =>\n INFINITE_SUMS.get(snapshot) ?? decodeSnapshotNumber(snapshot)\n );\n const descriptor = scalar[\"~\"].state.decimal;\n return primitiveCodec(\n (value) => {\n if (!descriptor) return failCacheSnapshot();\n return (\n decodeWidenedSum(\n canonicalizeMaterializedDecimal(value),\n descriptor.scale\n ) ?? failCacheSnapshot()\n );\n },\n (snapshot) => {\n if (!descriptor) return failCacheSnapshot();\n const canonical = decodeWidenedSum(snapshot, descriptor.scale);\n return canonical !== undefined && canonical === snapshot\n ? toDecimal(canonical)\n : failCacheSnapshot();\n }\n );\n}\n\nfunction bigintCodec(): ValueCodec {\n return primitiveCodec(\n (value) =>\n typeof value === \"bigint\" ? value.toString() : failCacheSnapshot(),\n (snapshot) => {\n if (typeof snapshot !== \"string\") return failCacheSnapshot();\n try {\n const value = BigInt(snapshot);\n return value.toString() === snapshot ? value : failCacheSnapshot();\n } catch {\n return failCacheSnapshot();\n }\n }\n );\n}\n\nfunction dateCodec(dateOnly: boolean): ValueCodec {\n return primitiveCodec(\n (value) => {\n if (\n !(value instanceof Date) ||\n Object.getPrototypeOf(value) !== Date.prototype ||\n Reflect.ownKeys(value).length !== 0\n ) {\n return failCacheSnapshot();\n }\n const time = Date.prototype.getTime.call(value);\n if (!Number.isFinite(time)) return failCacheSnapshot();\n const iso = Date.prototype.toISOString.call(value);\n if (dateOnly && !iso.endsWith(\"T00:00:00.000Z\")) {\n return failCacheSnapshot();\n }\n return iso;\n },\n (snapshot) => {\n if (typeof snapshot !== \"string\") return failCacheSnapshot();\n const value = new Date(snapshot);\n if (\n !Number.isFinite(value.getTime()) ||\n value.toISOString() !== snapshot ||\n (dateOnly && !snapshot.endsWith(\"T00:00:00.000Z\"))\n ) {\n return failCacheSnapshot();\n }\n return value;\n }\n );\n}\n\nfunction jsonCodec(): ValueCodec {\n return {\n snapshot: snapshotJsonValue,\n materialize: materializeJsonValue,\n };\n}\n\nfunction vectorCodec(dimension: number | undefined): ValueCodec {\n return {\n snapshot(value, active) {\n if (!Array.isArray(value)) return failCacheSnapshot();\n return withSnapshotObject(active, value, () => {\n const items = readSnapshotArray(value);\n if (dimension !== undefined && items.length !== dimension) {\n return failCacheSnapshot();\n }\n return items.map(encodeSnapshotNumber);\n });\n },\n materialize(snapshot, active) {\n return materializeArray(snapshot, active, (items) => {\n if (dimension !== undefined && items.length !== dimension) {\n return failCacheSnapshot();\n }\n return items.map(decodeSnapshotNumber);\n });\n },\n };\n}\n\nfunction bytesCodec(): ValueCodec {\n return {\n snapshot(value) {\n if (\n !(value instanceof Uint8Array) ||\n Object.getPrototypeOf(value) !== Uint8Array.prototype ||\n Reflect.ownKeys(value).length !== value.byteLength\n ) {\n return failCacheSnapshot();\n }\n const bytes = new Array<number>(value.byteLength);\n for (let index = 0; index < value.byteLength; index += 1) {\n bytes[index] = value[index]!;\n }\n return bytes;\n },\n materialize(snapshot) {\n const values = readSnapshotArray(snapshot);\n const bytes = new Uint8Array(values.length);\n for (let index = 0; index < values.length; index += 1) {\n const value = values[index];\n if (\n typeof value !== \"number\" ||\n !Number.isInteger(value) ||\n value < 0 ||\n value > 255\n ) {\n return failCacheSnapshot();\n }\n bytes[index] = value;\n }\n return bytes;\n },\n };\n}\n\nfunction pointCodec(): ValueCodec {\n const coordinates = recordCodec(\n new Map<string, ValueCodec>([\n [\"longitude\", numberCodec()],\n [\"latitude\", numberCodec()],\n ])\n );\n return {\n snapshot(value, active) {\n const point = validateGeoPoint(value);\n return point.issues\n ? failCacheSnapshot()\n : coordinates.snapshot(point.value, active);\n },\n materialize(snapshot, active) {\n const point = validateGeoPoint(coordinates.materialize(snapshot, active));\n return point.issues ? failCacheSnapshot() : point.value;\n },\n };\n}\n\nfunction primitiveCodec(\n snapshot: (value: unknown) => unknown,\n materialize: (snapshot: unknown) => unknown\n): ValueCodec {\n return { snapshot, materialize };\n}\n\nfunction materializeArray<Value>(\n snapshot: unknown,\n active: WeakSet<object>,\n materialize: (values: readonly unknown[]) => Value\n): Value {\n if (typeof snapshot !== \"object\" || snapshot === null) {\n return failCacheSnapshot();\n }\n return withSnapshotObject(active, snapshot, () =>\n materialize(readSnapshotArray(snapshot))\n );\n}\n","import { CacheConfigurationError } from \"@errors\";\nimport type { CacheResultCodec } from \"../../cache-flow\";\nimport {\n arrayCodec,\n booleanCodec,\n compileScalarCodec,\n compileWidenedSumCodec,\n countCodec,\n nullableCodec,\n numberCodec,\n recordCodec,\n recursiveRelationCodec,\n taggedRelationCodec,\n type ValueCodec,\n} from \"../../result/cache-value-codecs\";\nimport type { PreparedRead } from \"../commands\";\nimport { EngineInvariantError } from \"../shared/invariant\";\nimport type { Leaf, ProjectionShape } from \"../shared/query\";\n\n/**\n * The detached cache representation of one prepared read.\n *\n * Every value codec here comes from the OFFICIAL owner\n * (`src/query-engine/result/cache-value-codecs.ts`), addressed the way that\n * owner is addressed — by the declaring `Scalar` object, never by a leaf's type\n * name — so the candidate adds no scalar-meaning authority and a cached value\n * materializes exactly as a freshly parsed one does. The STRUCTURE comes from\n * the prepared read's own published facts (`shape`, `value`, `single`,\n * `empty`), which the read owner states beside the statement it decodes, so the\n * codec and the decoder cannot disagree about cardinality.\n */\nexport function cacheCodec(\n read: PreparedRead,\n requestedOperation: string\n): CacheResultCodec {\n // The read owner's own publication for zero rows says whether the public\n // value may be absent: `null` for a located row, `[]`/`{}`/`0`/`false` for\n // the shapes that always publish a value.\n const value = shapeCodec(read.value, requestedOperation);\n const compiled = read.empty === null ? nullableCodec(value) : value;\n return Object.freeze({\n snapshot(input: unknown): unknown {\n try {\n return compiled.snapshot(input, new WeakSet<object>());\n } catch (cause) {\n throw new CacheConfigurationError(\n \"The operation result cannot be represented by the cache result codec.\",\n {\n cause: cause instanceof Error ? cause : undefined,\n meta: { method: \"snapshot\", operation: requestedOperation },\n }\n );\n }\n },\n materialize(snapshot: unknown): unknown {\n try {\n return compiled.materialize(snapshot, new WeakSet<object>());\n } catch (cause) {\n throw new CacheConfigurationError(\n \"The cached result snapshot is malformed.\",\n {\n cause: cause instanceof Error ? cause : undefined,\n meta: { method: \"materialize\", operation: requestedOperation },\n }\n );\n }\n },\n });\n}\n\n/** One published shape, composed from the official structural codecs. */\nfunction shapeCodec(\n shape: ProjectionShape | Leaf,\n requestedOperation: string\n): ValueCodec {\n // biome-ignore lint/style/useDefaultSwitchClause: the published shape union is exhaustive; a default would be dead code.\n switch (shape.kind) {\n case \"scalar\":\n return leafCodec(shape, requestedOperation);\n case \"object\": {\n const fields = new Map<string, ValueCodec>();\n for (const [name, field] of Object.entries(shape.fields))\n fields.set(name, shapeCodec(field, requestedOperation));\n const record = recordCodec(fields);\n return shape.nullable === false ? record : nullableCodec(record);\n }\n case \"collection\":\n return arrayCodec(shapeCodec(shape.row, requestedOperation));\n case \"variants\": {\n const arms = new Map<string, ValueCodec>();\n for (const [type, arm] of Object.entries(shape.arms))\n arms.set(\n type,\n shapeCodec(\n shape.many && arm.kind === \"collection\" ? arm.row : arm,\n requestedOperation\n )\n );\n const tagged = taggedRelationCodec(arms);\n return shape.many ? arrayCodec(tagged) : nullableCodec(tagged);\n }\n case \"recursive\":\n // The decoder published every occurrence; the entry keeps them as they\n // were published. The node is the ordinary row codec, and the structural\n // owner reads only the slot's own prepared facts — never an identity,\n // never the cycle policy the decoder already applied.\n return recursiveRelationCodec(\n {\n relation: shape.relation,\n many: shape.many,\n optional: shape.optional,\n depth: shape.recurrence.depth,\n },\n shapeCodec(shape.row, requestedOperation)\n );\n }\n}\n\n/**\n * One leaf's value codec.\n *\n * A leaf that a column declares carries that `Scalar`, and the official owner\n * compiles it: `compileWidenedSumCodec` for a decimal, bigint, number or int\n * `_sum` (which answers outside the field's domain), `compileScalarCodec`\n * otherwise, with the DECLARED nullability switched off because the\n * projection's own `nullable` is the fact — an aggregate over a non-null\n * column still publishes `null` for an empty window.\n *\n * The leaves with no declaring scalar are the read owner's OWN values, not a\n * column's meaning: `_count` (including a relation count), `exist`, and the\n * number a non-decimal `_avg` or a `_distance` publishes. Naming those three is\n * not a second scalar authority.\n *\n * Those three exhaust the scalar-less leaves `Queries` constructs, so the last\n * arm names a state this engine cannot be in when it is right: an INVARIANT,\n * not a refusal a caller can reach (N4, plan §4). `Leaf.type` is a `string`\n * because it also carries every declared scalar's type name, so the compiler\n * cannot close the set here; the assertion states the fact the leaf builder\n * upstream established.\n */\nfunction leafCodec(leaf: Leaf, requestedOperation: string): ValueCodec {\n const declared = leaf.scalar;\n let value: ValueCodec;\n if (declared) {\n value = leaf.widened\n ? compileWidenedSumCodec(declared)\n : compileScalarCodec(declared, false);\n } else if (leaf.type === \"boolean\") value = booleanCodec();\n else if (leaf.type === \"int\") value = countCodec();\n else if (leaf.type === \"number\") value = numberCodec();\n else\n throw new EngineInvariantError(\n `Cannot cache a '${leaf.type}' result for '${requestedOperation}': its scalar declaration is missing.`\n );\n return leaf.nullable ? nullableCodec(value) : value;\n}\n","// What the core client calls only once a chain carries the official cache:\n// the scope binding, the cache flow and the cached result codec. `cache()`\n// installs this object, so it loads with `viborm/cache` and never with the\n// core client alone.\n\nimport type { ResolvedExtensionChain } from \"@extensions/chain\";\nimport {\n admitMutationCacheOptions,\n cacheKeyOf,\n createCacheExecutionOptions,\n executeCachedResultOperation,\n invalidateManualCache,\n prepareMutationCacheWriteOutcome,\n readMutationCacheOptions,\n validateCacheableOperation,\n} from \"@query-engine/cache-flow\";\nimport { cacheCodec } from \"@query-engine/raptor3/route/cache-codec\";\nimport {\n getOfficialCacheChainDefinition,\n installOfficialCacheRuntime,\n type OfficialCacheBindTarget,\n setOfficialCacheChainCapability,\n} from \"./capability\";\nimport { createOfficialCacheScope, readCacheExecutionOutcomes } from \"./driver\";\nimport { createOfficialCacheNamespace } from \"./key\";\n\n/**\n * The derivation is pure, so appending another extension re-derives the SAME\n * namespace: the scope is retained by value, with no registry keyed on chain\n * identity to keep in step and no second scope to split the cache.\n */\nfunction bindChain(\n chain: ResolvedExtensionChain,\n target: OfficialCacheBindTarget\n): void {\n const definition = getOfficialCacheChainDefinition(chain);\n if (definition === undefined) return;\n setOfficialCacheChainCapability(\n chain,\n Object.freeze({\n driver: definition.driver,\n version: definition.version,\n waitUntil: definition.waitUntil,\n scope: createOfficialCacheScope(\n createOfficialCacheNamespace({\n version: definition.version,\n dialect: target.dialect,\n namespace: target.adapter.namespace,\n })\n ),\n })\n );\n}\n\nexport const OFFICIAL_CACHE_RUNTIME = Object.freeze({\n admitMutationCacheOptions,\n bindChain,\n cacheCodec,\n cacheKeyOf,\n createCacheExecutionOptions,\n executeCachedResultOperation,\n invalidateManualCache,\n prepareMutationCacheWriteOutcome,\n readCacheExecutionOutcomes,\n readMutationCacheOptions,\n validateCacheableOperation,\n});\n\nexport type OfficialCacheRuntime = typeof OFFICIAL_CACHE_RUNTIME;\n\n// Loading the cache entry is what makes the runtime reachable. `cache()`\n// installs it too, so a bundler that drops this statement changes nothing.\ninstallOfficialCacheRuntime(OFFICIAL_CACHE_RUNTIME);\n","import { CacheConfigurationError } from \"@errors\";\nimport type { GenericQueryHandler } from \"@extensions/query\";\nimport {\n isFunction,\n isNumber,\n isRecord,\n isString,\n} from \"@validation/value-guards\";\nimport { errorCause } from \"../errors/diagnostic-safety\";\nimport {\n OFFICIAL_CACHE_NAME,\n type OfficialCacheDefinitionCapability,\n type OfficialCacheExtension,\n officialCacheControls,\n registerOfficialCacheQuery,\n} from \"./capability\";\nimport { CacheDriver, type WaitUntilFn } from \"./driver\";\nimport { OFFICIAL_CACHE_RUNTIME } from \"./runtime\";\n\n// The capability helpers moved to `./capability` so the core client can read\n// them without loading the cache; they stay importable from here.\nexport {\n bindOfficialCacheChain,\n getOfficialCacheChainCapability,\n getOfficialCacheChainDefinition,\n getOfficialCacheQueryCapability,\n OFFICIAL_CACHE_NAME,\n type OfficialCacheBindTarget,\n type OfficialCacheControls,\n type OfficialCacheExtension,\n type OfficialCacheQueryContribution,\n registerOfficialCacheChain,\n} from \"./capability\";\nexport interface CacheExtensionConfig {\n readonly driver: CacheDriver;\n readonly version?: string | number;\n readonly waitUntil?: WaitUntilFn;\n}\n\ntype ConfigKeys<Config> = Config extends unknown ? keyof Config : never;\n\ntype ExactCacheExtensionConfig<Config> = Record<\n Exclude<ConfigKeys<Config>, keyof CacheExtensionConfig>,\n never\n>;\n\nfunction configurationError(message: string, cause?: unknown): never {\n throw new CacheConfigurationError(message, {\n cause: cause === undefined ? undefined : errorCause(cause),\n });\n}\n\nfunction isCacheDriver(value: unknown): value is CacheDriver {\n try {\n return value instanceof CacheDriver;\n } catch (cause) {\n configurationError(\n \"Cache extension driver capability could not be inspected.\",\n cause\n );\n }\n}\n\nfunction snapshotConfig(value: unknown): OfficialCacheDefinitionCapability {\n if (!isRecord(value)) {\n configurationError(\"Cache extension configuration must be an object.\");\n }\n let keys: PropertyKey[];\n try {\n keys = Reflect.ownKeys(value);\n } catch (cause) {\n configurationError(\n \"Cache extension configuration could not be inspected.\",\n cause\n );\n }\n for (const key of keys) {\n if (\n typeof key !== \"string\" ||\n (key !== \"driver\" && key !== \"version\" && key !== \"waitUntil\")\n ) {\n configurationError(\n `Cache extension configuration has unknown member \"${String(key)}\".`\n );\n }\n }\n\n const read = (key: \"driver\" | \"version\" | \"waitUntil\"): unknown => {\n if (!keys.includes(key)) return undefined;\n try {\n return value[key];\n } catch (cause) {\n configurationError(\n `Cache extension configuration member \"${key}\" could not be read.`,\n cause\n );\n }\n };\n\n const driver = read(\"driver\");\n const version = read(\"version\");\n const waitUntil = read(\"waitUntil\");\n if (!isCacheDriver(driver)) {\n configurationError(\n \"Cache extension configuration requires a CacheDriver instance.\"\n );\n }\n if (\n version !== undefined &&\n !(isString(version) || (isNumber(version) && Number.isFinite(version)))\n ) {\n configurationError(\n 'Cache extension configuration \"version\" must be a string or finite number.'\n );\n }\n if (waitUntil !== undefined && !isFunction<WaitUntilFn>(waitUntil)) {\n configurationError(\n 'Cache extension configuration \"waitUntil\" must be a function.'\n );\n }\n return Object.freeze({ driver, version, waitUntil });\n}\n\n/** Create VibORM's fixed-name cache extension. */\nexport function cache<const Config>(\n config: Config &\n NoInfer<CacheExtensionConfig & ExactCacheExtensionConfig<Config>>\n): OfficialCacheExtension;\nexport function cache(config: CacheExtensionConfig): unknown {\n const capability = snapshotConfig(config);\n const query: GenericQueryHandler = ({ proceed }) => proceed();\n registerOfficialCacheQuery(query, capability, OFFICIAL_CACHE_RUNTIME);\n return Object.freeze({\n name: OFFICIAL_CACHE_NAME,\n query,\n controls: officialCacheControls,\n });\n}\n"],"mappings":"ysBAsCA,MAAM,EAAoC,IAAI,IAAI,CAChD,YACA,WACA,aACA,oBACA,mBACA,QACA,YACA,UACA,QACD,CAAC,CAGI,EAA0B,IAAI,QAOpC,SAAgB,0BACd,EAC0B,CAC1B,IAAM,EAAS,EAAM,EAAyBA,EAAM,CACpD,GAAI,EAAO,OACT,MAAM,IAAI,EACR,mCAAmC,EAAO,OAAO,IAAK,GAAU,EAAM,QAAQ,CAAC,KAAK,KAAK,GACzF,CAAE,MAAO,EAA2B,EAAO,CAAE,CAC9C,CAEH,IAAM,EACJ,EAAO,MAAM,aAAe,IAAA,GACxB,IAAA,GACA,CAAC,GAAG,EAAO,MAAM,WAAW,CAG9B,GAAY,OAAO,OAAO,EAAW,CACzC,IAAM,EAAoC,OAAO,OAAO,CACtD,eAAgB,EAAO,MAAM,eAC7B,GAAI,IAAe,IAAA,GAAY,EAAE,CAAG,CAAE,aAAY,CACnD,CAAC,CAEF,OADA,EAAwB,IAAI,EAAS,EAAQ,CACtC,EAIT,SAAgB,yBACd,EACsC,CACtC,IAAM,EAAW,GAAU,MAC3B,OAAO,EAAS,EAAS,CAAG,EAAwB,IAAI,EAAS,CAAG,IAAA,GAatE,SAAgB,WACd,EACA,EACA,EACA,EACS,CAIT,GAAI,IAAU,IAAA,GAAW,CACvB,IAAM,EAAM,WAAW,EAAM,EAAU,EAAK,CAC5C,OAAO,IAAQ,IAAA,GAAY,IAAA,GAAY,CAAC,QAAS,EAAK,EAAM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AAQ,UACd,IAAQ,UAAY,IAAQ,WAAa,IAAQ,cAElD,mBACE,qDAAqD,OAAO,EAAI,CAAC,IAClE,CAIL,IAAM,KAAQ,GAAqD,CAC5D,KAAK,SAAS,EAAI,CACvB,GAAI,CACF,OAAO,EAAM,SACN,EAAO,CACd,mBACE,yCAAyC,EAAI,sBAC7C,EACD,GAIC,EAAS,KAAK,SAAS,CACvB,EAAU,KAAK,UAAU,CACzB,EAAY,KAAK,YAAY,CAmBnC,OAlBK,cAAc,EAAO,EACxB,mBACE,iEACD,CAGD,IAAY,IAAA,IACZ,EAAE,EAAS,EAAQ,EAAK,EAAS,EAAQ,EAAI,OAAO,SAAS,EAAQ,GAErE,mBACE,6EACD,CAEC,IAAc,IAAA,IAAa,CAAC,EAAwB,EAAU,EAChE,mBACE,gEACD,CAEI,OAAO,OAAO,CAAE,SAAQ,UAAS,YAAW,CAAC,CAQtD,SAAgB,MAAM,EAAuC,CAC3D,IAAM,EAAa,eAAe,EAAO,CACnC,OAA8B,CAAE,aAAc,GAAS,CAE7D,OADA,EAA2B,MAAO,EAAY,EAAuB,CAC9D,OAAO,OAAO,CACnB,KAAM,EACN,MACA,SAAU,EACX,CAAC"}
1
+ {"version":3,"file":"cache.mjs","names":["codec","key","key","codec","key"],"sources":["../src/cache/result-codec.ts","../src/cache/extension.ts","../src/cache/revalidate.ts","../src/cache/storage.ts"],"sourcesContent":["import { CacheConfigurationError } from \"../errors/cache\";\nimport type { Codec } from \"../index\";\n\n/** One codec step, its failure the cache's: named, exposing no value. */\nfunction step<T>(\n method: \"snapshot\" | \"materialize\",\n operation: string,\n message: string,\n run: () => T\n): T {\n try {\n return run();\n } catch (cause) {\n throw new CacheConfigurationError(message, {\n cause: cause instanceof Error ? cause : undefined,\n meta: { method, operation },\n });\n }\n}\n\n/**\n * A call's codec whose failures are the cache's: a value the codec cannot\n * represent, and a stored entry that does not follow the shape, are each a\n * `CacheConfigurationError` that names the step and exposes no value.\n */\nexport function cacheCodec<R>(codec: Codec<R>, operation: string): Codec<R> {\n return {\n run: () => codec.run(),\n snapshot: () =>\n step(\n \"snapshot\",\n operation,\n \"The operation result cannot be represented by the cache result codec.\",\n () => codec.snapshot()\n ),\n materialize: (snapshot) =>\n step(\n \"materialize\",\n operation,\n \"The cached result snapshot is malformed.\",\n () => codec.materialize(snapshot)\n ),\n };\n}\n","/**\n * VibORM's cache, written with the public extension contract:\n * `client.$extends(cache({ driver }))`.\n *\n * - `$withCache(options)` binds the view's read options (`cacheRead`, a\n * bound argument): what marks a read the cache serves.\n * - A read through that view is served closest to the core (`inner`), keyed\n * on the prepared call (`key(run)`), and run uncached when it has no key\n * or runs in a transaction or an array.\n * - A write invalidates the scope once durable (`settled`), as its own\n * `cache` argument says; `$invalidate` once the view's work is durable.\n * - The scope is a pure function of the cache `version` and the database the\n * call works against (`database`), so two clients of one database share\n * entries and two databases never do.\n */\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { CachedClientOf, MutationOperations } from \"../client/exports\";\nimport { VibORMError } from \"../errors/base\";\nimport {\n CacheConfigurationError,\n CacheOperationNotCacheableError,\n} from \"../errors/cache\";\nimport { accepts, args, bound } from \"../extensions/args\";\nimport { around, call } from \"../extensions/call\";\nimport { codec } from \"../extensions/codec\";\nimport { type Database, database } from \"../extensions/database\";\nimport { extension } from \"../extensions/extension\";\nimport { key } from \"../extensions/key\";\nimport { methods } from \"../extensions/methods-part\";\nimport { reads, target, writes } from \"../extensions/on\";\nimport { settled } from \"../extensions/settled\";\nimport type {\n AnyTarget,\n Extension,\n Facts,\n PlacedArgument,\n Run,\n} from \"../index\";\nimport {\n CacheDriver,\n INVALIDATE,\n type Revalidate,\n SERVE,\n scopedKey,\n type WaitUntilFn,\n} from \"./driver\";\nimport { createOfficialCacheNamespace } from \"./key\";\nimport { cacheCodec } from \"./result-codec\";\nimport {\n admitMutationOptions,\n admitReadOptions,\n CACHEABLE,\n type CacheInvalidationOptions,\n type CacheReadOptions,\n hasCacheInvalidationWork,\n type WithCacheOptions,\n} from \"./schema\";\n\nexport interface CacheExtensionConfig {\n readonly driver: CacheDriver;\n readonly version?: string | number;\n readonly waitUntil?: WaitUntilFn;\n /**\n * `staleWhileRevalidate`, imported from `viborm/cache`: what lets a view's\n * `swr` option serve a stale entry and refresh it in the background.\n */\n readonly swr?: Revalidate;\n}\n\ntype ConfigKeys<Config> = Config extends unknown ? keyof Config : never;\n\ntype ExactCacheExtensionConfig<Config> = Record<\n Exclude<ConfigKeys<Config>, keyof CacheExtensionConfig>,\n never\n>;\n\n/** `Self` is a client, not a transaction nor a view: what the cache's methods are called on. */\ntype OnClient<Self> = [CachedClientOf<Self>] extends [never] ? never : unknown;\n\n/**\n * The client methods the cache adds, typed through `this` from the client\n * they are called on, whatever the chain added after the cache.\n */\nexport interface CacheMethods {\n /** A view whose reads the cache serves: read operations only. */\n $withCache<Self>(\n this: Self & OnClient<Self>,\n options?: WithCacheOptions\n ): CachedClientOf<Self>;\n /** Invalidate entries by keys or patterns (a `*` suffix matches a prefix). */\n $invalidate<Self>(\n this: Self & OnClient<Self>,\n ...keys: string[]\n ): Promise<void>;\n}\n\n/** What the cache adds to a client: its `cache` argument on writes, `$withCache`, `$invalidate`. */\ntype CacheFacts = Facts<\n CacheMethods,\n Record<never, never>,\n {\n readonly cache: PlacedArgument<\n CacheInvalidationOptions,\n PropertyKey,\n MutationOperations\n >;\n },\n never,\n never,\n Record<never, never>,\n Record<never, never>,\n false\n>;\n\n/** A validator as a Standard Schema: what an argument of the cache is checked by. */\nconst validator = <T>(admit: (value: unknown) => T): StandardSchemaV1<T> => ({\n \"~standard\": {\n version: 1,\n vendor: \"viborm.cache\",\n validate: (value: unknown) => ({ value: admit(value) }),\n },\n});\n\nfunction configurationError(message: string): never {\n throw new CacheConfigurationError(message);\n}\n\n/** The cache's view of one read: what its moment one leaves its second. */\ninterface Values {\n readonly cache?: CacheInvalidationOptions;\n readonly cacheRead?: CacheReadOptions;\n}\n\n/**\n * VibORM's fixed-name cache extension: `client.$extends(cache({ driver }))`.\n */\nexport function cache<T extends AnyTarget, const Config>(\n config: Config &\n NoInfer<CacheExtensionConfig & ExactCacheExtensionConfig<Config>>\n): Extension<T, CacheFacts>;\nexport function cache(config: CacheExtensionConfig): unknown {\n const { driver, version, waitUntil, swr } = config;\n if (!(driver instanceof CacheDriver))\n configurationError(\n \"Cache extension configuration requires a CacheDriver instance.\"\n );\n if (\n version !== undefined &&\n !(typeof version === \"string\" || Number.isFinite(version))\n )\n configurationError(\n 'Cache extension configuration \"version\" must be a string or finite number.'\n );\n if (waitUntil !== undefined && typeof waitUntil !== \"function\")\n configurationError(\n 'Cache extension configuration \"waitUntil\" must be a function.'\n );\n\n // Pure in its facts: the same version and database always give one scope.\n const namespaceOf = ({ dialect, namespace }: Database): string =>\n createOfficialCacheNamespace({ version, dialect, namespace });\n /**\n * Invalidate the scope of `origin`'s database. A backend failure is the\n * cache's; after a write (`meta`), whatever failed is, and a key\n * `$invalidate` was handed that the scope refuses is said as it is.\n */\n const invalidate = async (\n origin: object,\n options: CacheInvalidationOptions | undefined,\n meta?: {\n model?: string;\n operation: string;\n commitCertainty: \"committed\" | \"may-have-committed\";\n }\n ): Promise<void> => {\n try {\n const namespace = namespaceOf(database(origin));\n await driver[INVALIDATE](\"\", options, origin, (key) =>\n scopedKey(namespace, key)\n );\n } catch (cause) {\n if (meta === undefined && cause instanceof VibORMError) throw cause;\n throw new CacheConfigurationError(\n meta\n ? `Cache invalidation failed after mutation '${meta.operation}' on model '${meta.model}'.`\n : \"Cache invalidation failed.\",\n {\n cause: cause instanceof Error ? cause : undefined,\n meta: { method: \"invalidate\", ...meta },\n }\n );\n }\n };\n\n return extension(\n \"viborm.cache\",\n args({\n // A write's own invalidation options.\n cache: accepts(validator(admitMutationOptions)).on(writes),\n // Only `$withCache` binds it: the mark of a read the cache serves.\n cacheRead: bound(\n validator((value) => {\n const read = admitReadOptions(value);\n if (read.swr !== false && swr === undefined)\n configurationError(\n 'A view\\'s \"swr\" option needs the cache configured with it: cache({ driver, swr: staleWhileRevalidate }).'\n );\n return read;\n })\n ),\n }),\n\n // Writes: none through the read view; the scope is invalidated once the\n // write is durable.\n call((c) => {\n const values: Values = c.values;\n // Only reads are served through the view: this part sees writes alone.\n if (values.cacheRead !== undefined)\n throw new CacheOperationNotCacheableError(c.operation, [...CACHEABLE]);\n const options = values.cache;\n if (!hasCacheInvalidationWork(options)) return;\n settled(c, ({ certainty }) =>\n invalidate(c, options, {\n model: c.model,\n operation: c.operation,\n commitCertainty: certainty,\n })\n );\n }, target(writes)),\n\n // Reads through the view: answered from the store, closest to the core,\n // so every other part sees each call and the core's answer is stored.\n around(\n (c) => {\n const values: Values = c.values;\n const read = values.cacheRead;\n if (read === undefined) return;\n // target(reads) selects model calls only: each names its model.\n const model = c.model!;\n return <R>(run: Run<unknown, R>): Promise<R> => {\n // A transaction's and an array's reads see their own writes.\n if (run.mode !== \"direct\") return run();\n const id = key(run);\n if (id === undefined) return run();\n const db = database(run);\n return driver[SERVE]({\n id,\n codec: cacheCodec(codec(run), c.operation),\n read,\n namespace: namespaceOf(db),\n waitUntil,\n model,\n operation: c.operation,\n origin: run,\n database: db,\n revalidate: swr,\n });\n };\n },\n target(reads),\n { inner: true }\n ),\n\n methods((scope) => ({\n $withCache: (options?: WithCacheOptions) =>\n scope.$bind({ cacheRead: options }),\n $invalidate: (...keys: string[]) =>\n settled(scope, () => invalidate(scope, { invalidate: keys })),\n }))\n );\n}\n","/**\n * Stale-while-revalidate, a value the cache is configured with\n * (`cache({ driver, swr: staleWhileRevalidate })`): a cache without it\n * carries none of this code, and refuses a view's `swr` option.\n */\nimport { work } from \"@extensions/observation\";\nimport { note } from \"@extensions/unit-words\";\nimport { marker, scheduleBackground } from \"./cache-background\";\nimport type { Refresh, Revalidate } from \"./driver\";\nimport { cacheOutcome, revalidationStart } from \"./units\";\n\n/**\n * A stale entry within its window is served, and refreshed in the\n * background: claim the backend's marker (best effort; another request\n * holding it skips), replay the read's core keeping its rows, store them,\n * and always clear the marker. Nothing here rejects: its `revalidate` unit\n * presents a failure, the replay's primary over the cleanup's, both\n * retained.\n */\nexport const staleWhileRevalidate: Revalidate = (refresh) => {\n const { request, entry, now } = refresh;\n const window = request.read.swr;\n if (\n window === false ||\n now - entry.createdAt >= window ||\n now >= entry.expiresAt!\n )\n return false;\n // Stale, served; refreshed in the background, where the read runs once\n // more after this serve returned: the core alone.\n scheduleBackground(refreshed(refresh), request.waitUntil);\n note(request.origin, cacheOutcome(\"hit\", \"stale\"));\n return true;\n};\n\nasync function refreshed({\n request,\n key,\n backend,\n store,\n}: Refresh): Promise<void> {\n try {\n if (!(await marker(backend, key, true))) return;\n } catch {\n // A marker that cannot be claimed skips the refresh, never the read.\n return;\n }\n const { codec } = request;\n // Its own `cache` unit, whose terminal outcome is noted on it; a failure\n // of the replay is primary over the cleanup's, both retained.\n await work(\n request.origin,\n {\n kind: \"cache\",\n operation: \"revalidate\",\n note: revalidationStart(request, request.database),\n },\n async (unit) => {\n let failed = false;\n let failure: unknown;\n let terminal: ReturnType<typeof cacheOutcome>;\n try {\n await codec.run();\n await store(codec.snapshot());\n terminal = cacheOutcome(\"revalidate\", \"success\", undefined, request);\n } catch (error) {\n failed = true;\n failure = error;\n terminal = cacheOutcome(\"revalidate\", \"error\", error, request);\n }\n try {\n await marker(backend, key, false);\n } catch (cleanupFailure) {\n failure = failed\n ? new AggregateError(\n [failure, cleanupFailure],\n \"Cache revalidation work and cleanup both failed.\",\n { cause: failure }\n )\n : cleanupFailure;\n failed = true;\n }\n note(unit, terminal);\n if (failed) throw failure;\n }\n );\n}\n","/**\n * The unscoped storage of a cache driver, outside the official cache: what a\n * backend's own test or an application reads and writes under the bare\n * `viborm` root. Functions of the driver rather than its methods, so an\n * application that never calls them carries none of them; none of them\n * reaches the official namespace, which only an applied cache extension\n * writes.\n */\nimport { CacheInvalidKeyError } from \"@errors\";\nimport { marker } from \"./cache-background\";\nimport {\n BACKEND,\n type CacheDriver,\n type CacheEntry,\n type CacheSetOptions,\n DROP,\n GET,\n INVALIDATE,\n SET,\n} from \"./driver\";\nimport { CACHE_PREFIX, OFFICIAL_CACHE_NAMESPACE_ROOT } from \"./key\";\nimport type { CacheInvalidationOptions } from \"./schema\";\n\n/**\n * A public storage key under the bare `viborm` root (a key that already\n * begins with `viborm:` is taken as it is), refused inside the official\n * namespace. There is only one such root, so no sibling exists for a clear\n * to cross into.\n */\nfunction unscoped(key: string): string {\n const prefixedKey = key.startsWith(`${CACHE_PREFIX}:`)\n ? key\n : key\n ? `${CACHE_PREFIX}:${key}`\n : CACHE_PREFIX;\n if (\n prefixedKey === OFFICIAL_CACHE_NAMESPACE_ROOT ||\n prefixedKey.startsWith(`${OFFICIAL_CACHE_NAMESPACE_ROOT}:`)\n ) {\n throw new CacheInvalidKeyError(\n \"The official cache namespace is the cache extension's own: the public storage functions cannot address a key under it.\"\n );\n }\n return prefixedKey;\n}\n\n/** The entry stored under `key`, or `null`. */\nexport async function getEntry<T>(\n driver: CacheDriver,\n key: string,\n origin?: object\n): Promise<CacheEntry<T> | null> {\n return driver[GET]<T>(unscoped(key), origin);\n}\n\n/** Store `value` under `key` for `options.ttl` milliseconds. */\nexport async function setEntry<T>(\n driver: CacheDriver,\n key: string,\n value: T,\n options: CacheSetOptions,\n origin?: object\n): Promise<void> {\n return driver[SET](unscoped(key), value, options, origin);\n}\n\n/** Delete the entry under `key` and its revalidation marker. */\nexport async function deleteEntry(\n driver: CacheDriver,\n key: string,\n origin?: object\n): Promise<void> {\n return driver[DROP](\"delete\", unscoped(key), origin);\n}\n\n/** Clear every entry under `prefix`; every unscoped entry without one. */\nexport async function clearEntries(\n driver: CacheDriver,\n prefix?: string,\n origin?: object\n): Promise<void> {\n return driver[DROP](\"clear\", unscoped(prefix ?? \"\"), origin);\n}\n\n/**\n * Invalidate `model`'s entries (`autoInvalidate`, the default) and the keys\n * or `*` prefixes `options.invalidate` names, validated whole first.\n */\nexport async function invalidateEntries(\n driver: CacheDriver,\n model: string,\n options?: CacheInvalidationOptions,\n origin?: object\n): Promise<void> {\n return driver[INVALIDATE](`${model}:`, options, origin, unscoped);\n}\n\n/** Claim the refresh of `key`: whether this caller performs it. */\nexport async function markRevalidating(\n driver: CacheDriver,\n key: string\n): Promise<boolean> {\n return marker(driver[BACKEND](), unscoped(key), true);\n}\n\n/** Release the claim on the refresh of `key`. */\nexport async function clearRevalidating(\n driver: CacheDriver,\n key: string\n): Promise<void> {\n await marker(driver[BACKEND](), unscoped(key), false);\n}\n"],"mappings":"yrBAIA,SAAS,KACP,EACA,EACA,EACA,EACG,CACH,GAAI,CACF,OAAO,GAAK,OACL,EAAO,CACd,MAAM,IAAI,EAAwB,EAAS,CACzC,MAAO,aAAiB,MAAQ,EAAQ,IAAA,GACxC,KAAM,CAAE,SAAQ,YAAW,CAC5B,CAAC,EASN,SAAgB,WAAc,EAAiB,EAA6B,CAC1E,MAAO,CACL,QAAWA,EAAM,KAAK,CACtB,aACE,KACE,WACA,EACA,4EACMA,EAAM,UAAU,CACvB,CACH,YAAc,GACZ,KACE,cACA,EACA,+CACMA,EAAM,YAAY,EAAS,CAClC,CACJ,CCyEH,MAAM,UAAgB,IAAuD,CAC3E,YAAa,CACX,QAAS,EACT,OAAQ,eACR,SAAW,IAAoB,CAAE,MAAO,EAAM,EAAM,CAAE,EACvD,CACF,EAED,SAAS,mBAAmB,EAAwB,CAClD,MAAM,IAAI,EAAwB,EAAQ,CAgB5C,SAAgB,MAAM,EAAuC,CAC3D,GAAM,CAAE,SAAQ,UAAS,YAAW,OAAQ,EACtC,aAAkB,GACtB,mBACE,iEACD,CAED,IAAY,IAAA,IACZ,EAAE,OAAO,GAAY,UAAY,OAAO,SAAS,EAAQ,GAEzD,mBACE,6EACD,CACC,IAAc,IAAA,IAAa,OAAO,GAAc,YAClD,mBACE,gEACD,CAGH,IAAM,aAAe,CAAE,UAAS,eAC9B,EAA6B,CAAE,UAAS,UAAS,YAAW,CAAC,CAMzD,WAAa,MACjB,EACA,EACA,IAKk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ACD,EACJ,EAAS,GAGX,GADA,EAAK,EAAM,EAAS,CAChB,EAAQ,MAAM,GAErB,CCxDH,SAAS,SAAS,EAAqB,CACrC,IAAM,EAAcE,EAAI,WAAW,GAAG,EAAa,GAAG,CAClDA,EACAA,EACE,GAAG,EAAa,GAAGA,IACnB,EACN,GACE,IAAgB,GAChB,EAAY,WAAW,GAAG,EAA8B,GAAG,CAE3D,MAAM,IAAI,EACR,yHACD,CAEH,OAAO,EAIT,eAAsB,SACpB,EACA,EACA,EAC+B,CAC/B,OAAO,EAAO,GAAQ,SAASA,EAAI,CAAE,EAAO,CAI9C,eAAsB,SACpB,EACA,EACA,EACA,EACA,EACe,CACf,OAAO,EAAO,GAAK,SAASA,EAAI,CAAE,EAAO,EAAS,EAAO,CAI3D,eAAsB,YACpB,EACA,EACA,EACe,CACf,OAAO,EAAO,GAAM,SAAU,SAASA,EAAI,CAAE,EAAO,CAItD,eAAsB,aACpB,EACA,EACA,EACe,CACf,OAAO,EAAO,GAAM,QAAS,SAAS,GAAU,GAAG,CAAE,EAAO,CAO9D,eAAsB,kBACpB,EACA,EACA,EACA,EACe,CACf,OAAO,EAAO,GAAY,GAAG,EAAM,GAAI,EAAS,EAAQ,SAAS,CAInE,eAAsB,iBACpB,EACA,EACkB,CAClB,OAAO,EAAO,EAAO,IAAU,CAAE,SAASA,EAAI,CAAE,GAAK,CAIvD,eAAsB,kBACpB,EACA,EACe,CACf,MAAM,EAAO,EAAO,IAAU,CAAE,SAASA,EAAI,CAAE,GAAM"}
@@ -0,0 +1,2 @@
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{t,y as n}from"./base-z-cH5ZBI.mjs";import{p as r}from"./validation--qS7OPmg.mjs";import{i,l as a,n as o}from"./coordination-6qZHx_kl.mjs";import{i as s,o as c}from"./value-guards-CBuxSC66.mjs";import{r as l}from"./extension-CGepsF-p.mjs";import{i as u}from"./schema-BYA-_bpk.mjs";import{s as d,t as f,u as p}from"./on-ylYaKuRu.mjs";const m=new Set([`select`,`include`,`omit`,`_count`,`_avg`,`_sum`,`_min`,`_max`,`by`]);function targetedHandlers(e){let t=e.filter(e=>!e.on),n=new Map;return{placed:e,global:t,handlers(r,i){if(r===void 0)return t.length>0?t:void 0;let a=u(n,`${r}.${i}`,()=>e.filter(({on:e})=>!e||e.models.has(r)&&e.operations.has(i)));return a.length>0?a:void 0}}}const h=Object.freeze({});function firstOf({handler:e,keep:i,told:o,watch:l},u){let first=({extension:d,args:f},p,g,_,v,y,b)=>{let refusal=(e,t)=>new r(`Extension "${d}" first moment for ${p===void 0?g:`${p}.${g}`} ${e}.`,{cause:n(t),meta:{model:p,operation:g}}),x;try{x=e({kind:p===void 0?`raw`:`model`,schema:u,model:p,operation:g,get args(){return _.args},values:(f&&y?.owned(b,f))??h,set(e){if(p===void 0||!c(e))throw refusal(`set no model call's arguments`);for(let t of Object.keys(e)){let e=m.has(t);if(e||y?.names.has(t))throw refusal(e?`set "${t}", which decides the result's shape`:`set argument "${t}"`)}_.args=Object.freeze({..._.args,...e})},...p===void 0?o?.(v,d):l?.registering(v,d),[a]:p===void 0?void 0:v})}catch(e){throw e instanceof t?e:refusal(`threw`,e)}if(c(x)&&s(x.then))throw refusal(`returned a promise`);if(s(x)){if(i===void 0)throw refusal(`returned a function: write around()`);i(v,first,x)}};return first}function runFirstMoments(e,t,n,r,i,a,o){let s={args:c(t)?Object.freeze({...t}):t};for(let t of n)t.handler(t,i,e,s,r,a,o);return s.args}function keepSecond(e,t,n){(e.seconds??=new Map).set(t,n)}const rawTold=(e,t)=>({[p]({settled:n,collect:r,tell:i}){return n===void 0?!1:((e.told??=[]).push({extension:t,listener:n,collect:r,tell:i}),!0)}}),secondMoment=e=>(t,n)=>{let r=t.call?.seconds?.get(e);return r===void 0?n():r(n)};function placed({on:e,inner:t},n,{schema:r,owner:{name:i,args:a}}){let known=(e,t)=>new Set(e.map(e=>t(e)?e:l(`Extension "${i}" target names unknown model or operation "${e}".`,i)));return{extension:i,handler:n,args:a,inner:t,on:e&&{models:known(e.models??Object.keys(r),e=>Object.hasOwn(r,e)),operations:known(e.operations??[...f],e=>f.has(e))}}}function appendFirst(e,t,n){let{next:r}=e;r.call={...targetedHandlers([...r.call?.placed??[],placed(t,n,e)]),apply:runFirstMoments}}function callPart(e){return{join(t){e.watch&&t.bring(e.watch),appendFirst(t,e,firstOf(e,t.schema))}}}function aroundPart(e){return{join(t){let{next:n}=t;e.watch&&t.bring(e.watch);let r=firstOf(e,t.schema);appendFirst(t,e,r);let a=placed(e,secondMoment(r),t);n.around=targetedHandlers([...n.around?.placed??[],a].sort((e,t)=>Number(!!e.inner)-Number(!!t.inner))),i(n,o)}}}function call(e,t){if(!s(e))throw TypeError(`call() takes a function of the call`);let n=d(t);return callPart({handler:e,on:n,watch:n?.watch})}function around(e,t,n){if(!s(e))throw TypeError(`around() takes a function of the call`);let r=d(t);return aroundPart({handler:e,on:r,keep:keepSecond,told:rawTold,watch:r?.watch,inner:n?.inner})}export{call as n,around as t};
2
+ //# sourceMappingURL=call-Cz8XUmrl.mjs.map