viborm 1.2.4 → 1.3.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 (275) hide show
  1. package/README.md +6 -1
  2. package/dist/{adapter-internals-n3Mf3css.mjs → adapter-internals-AGgQRu5t.mjs} +1 -1
  3. package/dist/{adapter-internals-n3Mf3css.mjs.map → adapter-internals-AGgQRu5t.mjs.map} +1 -1
  4. package/dist/adapter-namespace-BpMbLKpL.mjs +2 -0
  5. package/dist/{adapter-namespace-DqkJQdrD.mjs.map → adapter-namespace-BpMbLKpL.mjs.map} +1 -1
  6. package/dist/adapters.d.mts +1 -1
  7. package/dist/adapters.mjs +1 -1
  8. package/dist/{array-literal-BsbbSLw3.mjs → array-literal-BKdLfNzM.mjs} +1 -1
  9. package/dist/{array-literal-BsbbSLw3.mjs.map → array-literal-BKdLfNzM.mjs.map} +1 -1
  10. package/dist/{base-AdXAoy6l.mjs → base-D3m1S7Uc.mjs} +2 -2
  11. package/dist/{base-AdXAoy6l.mjs.map → base-D3m1S7Uc.mjs.map} +1 -1
  12. package/dist/{batch-refs-4L8ECdPU.mjs → batch-refs-B4zn-FAu.mjs} +2 -2
  13. package/dist/{batch-refs-4L8ECdPU.mjs.map → batch-refs-B4zn-FAu.mjs.map} +1 -1
  14. package/dist/{bind-parameter-capacity-CjPgqnmx.mjs → bind-parameter-capacity-qfEejeOX.mjs} +2 -2
  15. package/dist/{bind-parameter-capacity-CjPgqnmx.mjs.map → bind-parameter-capacity-qfEejeOX.mjs.map} +1 -1
  16. package/dist/builder-s1ySUuMb.mjs +2 -0
  17. package/dist/builder-s1ySUuMb.mjs.map +1 -0
  18. package/dist/bun-sql.d.mts +3 -1
  19. package/dist/bun-sql.mjs +1 -1
  20. package/dist/bun-sql.mjs.map +1 -1
  21. package/dist/bun-sqlite.d.mts +1 -1
  22. package/dist/bun-sqlite.mjs +1 -1
  23. package/dist/cache/cloudflare-kv.d.mts +1 -1
  24. package/dist/cache/cloudflare-kv.mjs +1 -1
  25. package/dist/cache/memory.d.mts +1 -1
  26. package/dist/cache/memory.mjs +1 -1
  27. package/dist/{cache-BO57X0TT.mjs → cache-CIPRF-pz.mjs} +2 -2
  28. package/dist/{cache-BO57X0TT.mjs.map → cache-CIPRF-pz.mjs.map} +1 -1
  29. package/dist/cache.d.mts +1 -1
  30. package/dist/cache.mjs +1 -1
  31. package/dist/cache.mjs.map +1 -1
  32. package/dist/{canonical-json-rfC2Dg0X.mjs → canonical-json-BReb5nFO.mjs} +2 -2
  33. package/dist/{canonical-json-rfC2Dg0X.mjs.map → canonical-json-BReb5nFO.mjs.map} +1 -1
  34. package/dist/chain-7qiFSE8J.mjs +2 -0
  35. package/dist/chain-7qiFSE8J.mjs.map +1 -0
  36. package/dist/cli.mjs +2 -2
  37. package/dist/cli.mjs.map +1 -1
  38. package/dist/client-6YgGlXzN.mjs +2 -0
  39. package/dist/client-6YgGlXzN.mjs.map +1 -0
  40. package/dist/{client-CUnPXifK.d.mts → client-70MrTq1E.d.mts} +3 -3
  41. package/dist/client-BgJ7Faln.mjs +49 -0
  42. package/dist/{client-B3VWFhv_.mjs.map → client-BgJ7Faln.mjs.map} +1 -1
  43. package/dist/client.d.mts +2 -2
  44. package/dist/client.mjs +1 -1
  45. package/dist/{clock-CK41KO7t.mjs → clock-C24RcpwO.mjs} +1 -1
  46. package/dist/{clock-CK41KO7t.mjs.map → clock-C24RcpwO.mjs.map} +1 -1
  47. package/dist/config.d.mts +2 -2
  48. package/dist/config.mjs +1 -1
  49. package/dist/controls-KQ85SWfT.mjs +2 -0
  50. package/dist/controls-KQ85SWfT.mjs.map +1 -0
  51. package/dist/{current-DyzK6OCh.mjs → current-oXcxSCBQ.mjs} +1 -1
  52. package/dist/{current-DyzK6OCh.mjs.map → current-oXcxSCBQ.mjs.map} +1 -1
  53. package/dist/d1.d.mts +1 -1
  54. package/dist/d1.mjs +1 -1
  55. package/dist/d1.mjs.map +1 -1
  56. package/dist/{datetime-physical-codec-oIhiYZEP.mjs → datetime-physical-codec-BEqQbIP_.mjs} +2 -2
  57. package/dist/{datetime-physical-codec-oIhiYZEP.mjs.map → datetime-physical-codec-BEqQbIP_.mjs.map} +1 -1
  58. package/dist/driver-B9fIori_.mjs +2 -0
  59. package/dist/driver-B9fIori_.mjs.map +1 -0
  60. package/dist/{driver-B19QlFqn.mjs → driver-vn-9CN0y.mjs} +2 -2
  61. package/dist/{driver-B19QlFqn.mjs.map → driver-vn-9CN0y.mjs.map} +1 -1
  62. package/dist/driver.d.mts +1 -1
  63. package/dist/driver.mjs +1 -1
  64. package/dist/error-mapping-C9WgitPi.mjs +2 -0
  65. package/dist/error-mapping-C9WgitPi.mjs.map +1 -0
  66. package/dist/every-CcpKWCVo.mjs +2 -0
  67. package/dist/{every-o-Nu9Em8.mjs.map → every-CcpKWCVo.mjs.map} +1 -1
  68. package/dist/{execution-context-BKR3bgES.mjs → execution-context-rJXTRVrJ.mjs} +1 -1
  69. package/dist/{execution-context-BKR3bgES.mjs.map → execution-context-rJXTRVrJ.mjs.map} +1 -1
  70. package/dist/{fs-estate-CAhDg7nY.mjs → fs-estate-i8Zlr1OQ.mjs} +2 -2
  71. package/dist/{fs-estate-CAhDg7nY.mjs.map → fs-estate-i8Zlr1OQ.mjs.map} +1 -1
  72. package/dist/{geo-area-codec-1SY9im7O.mjs → geo-area-codec-CbkmFArQ.mjs} +2 -2
  73. package/dist/{geo-area-codec-1SY9im7O.mjs.map → geo-area-codec-CbkmFArQ.mjs.map} +1 -1
  74. package/dist/geo-point-codec-DyEHMdJg.mjs +2 -0
  75. package/dist/geo-point-codec-DyEHMdJg.mjs.map +1 -0
  76. package/dist/hydration-BsPZI4jE.mjs +2 -0
  77. package/dist/{hydration-CAxOL4aI.mjs.map → hydration-BsPZI4jE.mjs.map} +1 -1
  78. package/dist/identifier-conversion-BneQiLxQ.mjs +2 -0
  79. package/dist/{identifier-conversion-GgbwHc2G.mjs.map → identifier-conversion-BneQiLxQ.mjs.map} +1 -1
  80. package/dist/{identity-CLFhCTZx.mjs → identity-oQvIe7u8.mjs} +2 -2
  81. package/dist/{identity-CLFhCTZx.mjs.map → identity-oQvIe7u8.mjs.map} +1 -1
  82. package/dist/{index-B0b7asA4.d.mts → index-VsM29vYN.d.mts} +5257 -4915
  83. package/dist/index.d.mts +3 -3
  84. package/dist/index.mjs +1 -1
  85. package/dist/index.mjs.map +1 -1
  86. package/dist/instrumentation.d.mts +1 -1
  87. package/dist/instrumentation.mjs +1 -1
  88. package/dist/{invariant-BnLYqsHO.mjs → invariant-D57gi_yW.mjs} +1 -1
  89. package/dist/{invariant-BnLYqsHO.mjs.map → invariant-D57gi_yW.mjs.map} +1 -1
  90. package/dist/{json-number-CGXpPu4D.mjs → json-number-DvmiNx0n.mjs} +1 -1
  91. package/dist/{json-number-CGXpPu4D.mjs.map → json-number-DvmiNx0n.mjs.map} +1 -1
  92. package/dist/key-D9LtHxVK.mjs +2 -0
  93. package/dist/{key-BeoOwGr3.mjs.map → key-D9LtHxVK.mjs.map} +1 -1
  94. package/dist/{libsql-Drp-zaxq.mjs → libsql-BlSBYwd_.mjs} +3 -3
  95. package/dist/{libsql-Drp-zaxq.mjs.map → libsql-BlSBYwd_.mjs.map} +1 -1
  96. package/dist/libsql.d.mts +1 -1
  97. package/dist/libsql.mjs +1 -1
  98. package/dist/{memory-CDTUZQWL.mjs → memory-C0k-_S_n.mjs} +2 -2
  99. package/dist/{memory-CDTUZQWL.mjs.map → memory-C0k-_S_n.mjs.map} +1 -1
  100. package/dist/migrations/mysql.d.mts +5 -5
  101. package/dist/migrations/mysql.mjs +1 -1
  102. package/dist/migrations/postgres.d.mts +5 -5
  103. package/dist/migrations/postgres.mjs +1 -1
  104. package/dist/migrations/sqlite.d.mts +5 -5
  105. package/dist/migrations/sqlite.mjs +1 -1
  106. package/dist/migrations/storage/durable-object.d.mts +1 -1
  107. package/dist/migrations/storage/durable-object.mjs +1 -1
  108. package/dist/migrations/storage/fs.d.mts +1 -1
  109. package/dist/migrations/storage/fs.mjs +1 -1
  110. package/dist/migrations/storage/r2.d.mts +1 -1
  111. package/dist/migrations/storage/r2.mjs +1 -1
  112. package/dist/migrations/tenant.d.mts +3 -3
  113. package/dist/migrations/tenant.mjs +1 -1
  114. package/dist/{migrations-DTObIjAm.mjs → migrations-Bn1SatyB.mjs} +2 -2
  115. package/dist/{migrations-DTObIjAm.mjs.map → migrations-Bn1SatyB.mjs.map} +1 -1
  116. package/dist/migrations.d.mts +5 -5
  117. package/dist/migrations.mjs +1 -1
  118. package/dist/{mysql-D7zC03yD.mjs → mysql-DOLHwIM_.mjs} +6 -6
  119. package/dist/{mysql-D7zC03yD.mjs.map → mysql-DOLHwIM_.mjs.map} +1 -1
  120. package/dist/mysql-adapter-C6c5govr.mjs +2 -0
  121. package/dist/{mysql-adapter-DkJPfoGf.mjs.map → mysql-adapter-C6c5govr.mjs.map} +1 -1
  122. package/dist/mysql2.d.mts +1 -1
  123. package/dist/mysql2.mjs +1 -1
  124. package/dist/{native-types-veeTk36s.mjs → native-types-asNCr26n.mjs} +1 -1
  125. package/dist/{native-types-veeTk36s.mjs.map → native-types-asNCr26n.mjs.map} +1 -1
  126. package/dist/neon-http.d.mts +3 -1
  127. package/dist/neon-http.mjs +1 -1
  128. package/dist/neon-http.mjs.map +1 -1
  129. package/dist/{object-store-DQR6bTBY.mjs → object-store-ChYHlOMD.mjs} +2 -2
  130. package/dist/{object-store-DQR6bTBY.mjs.map → object-store-ChYHlOMD.mjs.map} +1 -1
  131. package/dist/{object-store-DMFXXQEC.d.mts → object-store-D9mvOHP4.d.mts} +4 -4
  132. package/dist/{observation-DUSm7oXK.mjs → observation-Co72iCd1.mjs} +2 -2
  133. package/dist/{observation-DUSm7oXK.mjs.map → observation-Co72iCd1.mjs.map} +1 -1
  134. package/dist/permissions.d.mts +424 -0
  135. package/dist/permissions.mjs +2 -0
  136. package/dist/permissions.mjs.map +1 -0
  137. package/dist/pg.d.mts +9 -1
  138. package/dist/pg.mjs +1 -1
  139. package/dist/pg.mjs.map +1 -1
  140. package/dist/pglite.d.mts +3 -1
  141. package/dist/pglite.mjs +1 -1
  142. package/dist/pglite.mjs.map +1 -1
  143. package/dist/{physical-6V_LNU3L.mjs → physical-CAOaNM4R.mjs} +2 -2
  144. package/dist/{physical-6V_LNU3L.mjs.map → physical-CAOaNM4R.mjs.map} +1 -1
  145. package/dist/{pinned-session-CLxj5M5e.mjs → pinned-session-BTplL3iZ.mjs} +2 -2
  146. package/dist/{pinned-session-CLxj5M5e.mjs.map → pinned-session-BTplL3iZ.mjs.map} +1 -1
  147. package/dist/planetscale.d.mts +1 -1
  148. package/dist/planetscale.mjs +1 -1
  149. package/dist/{planner-C0Q7ks-V.d.mts → planner-C1NzLBge.d.mts} +1 -1
  150. package/dist/{postgres-Dv-QnnbD.mjs → postgres-DQVSTqVm.mjs} +4 -4
  151. package/dist/{postgres-Dv-QnnbD.mjs.map → postgres-DQVSTqVm.mjs.map} +1 -1
  152. package/dist/postgres-adapter-CGthb5yh.mjs +2 -0
  153. package/dist/postgres-adapter-CGthb5yh.mjs.map +1 -0
  154. package/dist/postgres-adapter-CxEit2-v.mjs +2 -0
  155. package/dist/postgres-adapter-CxEit2-v.mjs.map +1 -0
  156. package/dist/{postgres-result-7F0DllQe.mjs → postgres-result-KyBKBNJr.mjs} +2 -2
  157. package/dist/{postgres-result-7F0DllQe.mjs.map → postgres-result-KyBKBNJr.mjs.map} +1 -1
  158. package/dist/postgres.d.mts +3 -1
  159. package/dist/postgres.mjs +1 -1
  160. package/dist/postgres.mjs.map +1 -1
  161. package/dist/{provider-limits-BHATED_m.mjs → provider-limits-Da00ilvv.mjs} +2 -2
  162. package/dist/{provider-limits-BHATED_m.mjs.map → provider-limits-Da00ilvv.mjs.map} +1 -1
  163. package/dist/{result-parsing-DRXC89ek.mjs → result-parsing-8wEK3GY1.mjs} +1 -1
  164. package/dist/{result-parsing-DRXC89ek.mjs.map → result-parsing-8wEK3GY1.mjs.map} +1 -1
  165. package/dist/result-shape-B6yWtnx_.mjs +2 -0
  166. package/dist/result-shape-B6yWtnx_.mjs.map +1 -0
  167. package/dist/scalar-CpEwuJvn.mjs +4 -0
  168. package/dist/scalar-CpEwuJvn.mjs.map +1 -0
  169. package/dist/schema/json.d.mts +1 -1
  170. package/dist/schema/json.mjs +1 -1
  171. package/dist/schema/json.mjs.map +1 -1
  172. package/dist/schema-BnzGHn7k.mjs +2 -0
  173. package/dist/{schema-Cjem1-0f.mjs.map → schema-BnzGHn7k.mjs.map} +1 -1
  174. package/dist/{schema-introspection-DEYGC2qg.mjs → schema-introspection-DZsdP6bi.mjs} +4 -4
  175. package/dist/{schema-introspection-DEYGC2qg.mjs.map → schema-introspection-DZsdP6bi.mjs.map} +1 -1
  176. package/dist/schema.d.mts +1 -1
  177. package/dist/schema.mjs +1 -1
  178. package/dist/{select-assembly-f1UGoblh.mjs → select-assembly-CkGe2ABs.mjs} +2 -2
  179. package/dist/{select-assembly-f1UGoblh.mjs.map → select-assembly-CkGe2ABs.mjs.map} +1 -1
  180. package/dist/{settle-B9Vg1FnP.mjs → settle-CS_k6Ztm.mjs} +2 -2
  181. package/dist/{settle-B9Vg1FnP.mjs.map → settle-CS_k6Ztm.mjs.map} +1 -1
  182. package/dist/soft-delete.d.mts +27 -96
  183. package/dist/soft-delete.mjs +1 -1
  184. package/dist/soft-delete.mjs.map +1 -1
  185. package/dist/sql-Bhxq9arK.mjs +2 -0
  186. package/dist/sql-Bhxq9arK.mjs.map +1 -0
  187. package/dist/{sql-BvfwUKIh.d.mts → sql-EsoN_7Et.d.mts} +24 -0
  188. package/dist/{sql-statement-tokens-BBcoGmJb.mjs → sql-statement-tokens-CFi1y3bK.mjs} +1 -1
  189. package/dist/{sql-statement-tokens-BBcoGmJb.mjs.map → sql-statement-tokens-CFi1y3bK.mjs.map} +1 -1
  190. package/dist/sql.d.mts +1 -1
  191. package/dist/sql.mjs +1 -1
  192. package/dist/sqlite-adapter-BXAJy3mI.mjs +2 -0
  193. package/dist/sqlite-adapter-BXAJy3mI.mjs.map +1 -0
  194. package/dist/{sqlite-utils-DlgokMJN.mjs → sqlite-utils-D_cypcyW.mjs} +2 -2
  195. package/dist/{sqlite-utils-DlgokMJN.mjs.map → sqlite-utils-D_cypcyW.mjs.map} +1 -1
  196. package/dist/sqlite3.d.mts +3 -1
  197. package/dist/sqlite3.mjs +1 -1
  198. package/dist/sqlite3.mjs.map +1 -1
  199. package/dist/{standard-sql-Bk4RZPqJ.mjs → standard-sql-CoGqv-iX.mjs} +3 -3
  200. package/dist/standard-sql-CoGqv-iX.mjs.map +1 -0
  201. package/dist/{suppressed-failure-BwULh-8h.mjs → suppressed-failure-Bdo2aK81.mjs} +1 -1
  202. package/dist/{suppressed-failure-BwULh-8h.mjs.map → suppressed-failure-Bdo2aK81.mjs.map} +1 -1
  203. package/dist/to-many-C5RMZl05.mjs +2 -0
  204. package/dist/to-many-C5RMZl05.mjs.map +1 -0
  205. package/dist/{transaction-Bnl6ULTw.mjs → transaction-4dfqals6.mjs} +2 -2
  206. package/dist/{transaction-Bnl6ULTw.mjs.map → transaction-4dfqals6.mjs.map} +1 -1
  207. package/dist/{transaction-operation-CKK3l_9x.mjs → transaction-operation-CU1zlxiG.mjs} +2 -2
  208. package/dist/{transaction-operation-CKK3l_9x.mjs.map → transaction-operation-CU1zlxiG.mjs.map} +1 -1
  209. package/dist/{types-C4v6iAmY.mjs → types-C5Oxz9yp.mjs} +1 -1
  210. package/dist/{types-C4v6iAmY.mjs.map → types-C5Oxz9yp.mjs.map} +1 -1
  211. package/dist/{utils-CZNaOZR7.mjs → utils-C3r4gO3Y.mjs} +4 -4
  212. package/dist/{utils-CZNaOZR7.mjs.map → utils-C3r4gO3Y.mjs.map} +1 -1
  213. package/dist/v-DtLdBQYg.mjs +2 -0
  214. package/dist/v-DtLdBQYg.mjs.map +1 -0
  215. package/dist/validation-BQtO6srU.mjs +2 -0
  216. package/dist/{validation-PF9-_nKd.mjs.map → validation-BQtO6srU.mjs.map} +1 -1
  217. package/dist/validation-BamBwne9.mjs +2 -0
  218. package/dist/validation-BamBwne9.mjs.map +1 -0
  219. package/dist/validation.d.mts +1 -1
  220. package/dist/validation.mjs +1 -1
  221. package/dist/validator-CVSrhn0u.mjs +2 -0
  222. package/dist/validator-CVSrhn0u.mjs.map +1 -0
  223. package/dist/version-C8QLCt1n.mjs +2 -0
  224. package/dist/{version-nt0parEY.mjs.map → version-C8QLCt1n.mjs.map} +1 -1
  225. package/package.json +36 -9
  226. package/dist/adapter-namespace-DqkJQdrD.mjs +0 -2
  227. package/dist/builder-Ycvq3ETg.mjs +0 -2
  228. package/dist/builder-Ycvq3ETg.mjs.map +0 -1
  229. package/dist/chain-Dh0FV72b.mjs +0 -2
  230. package/dist/chain-Dh0FV72b.mjs.map +0 -1
  231. package/dist/client-B3VWFhv_.mjs +0 -49
  232. package/dist/client-BLiBmykn.mjs +0 -2
  233. package/dist/client-BLiBmykn.mjs.map +0 -1
  234. package/dist/controls-DXgIn4zh.mjs +0 -2
  235. package/dist/controls-DXgIn4zh.mjs.map +0 -1
  236. package/dist/driver-BlnKXPFF.mjs +0 -2
  237. package/dist/driver-BlnKXPFF.mjs.map +0 -1
  238. package/dist/error-mapping-CnPCv1dm.mjs +0 -2
  239. package/dist/error-mapping-CnPCv1dm.mjs.map +0 -1
  240. package/dist/every-o-Nu9Em8.mjs +0 -2
  241. package/dist/geo-point-codec-lhxH42SK.mjs +0 -2
  242. package/dist/geo-point-codec-lhxH42SK.mjs.map +0 -1
  243. package/dist/hydration-CAxOL4aI.mjs +0 -2
  244. package/dist/identifier-conversion-GgbwHc2G.mjs +0 -2
  245. package/dist/identifier-hQCs8M1n.mjs +0 -2
  246. package/dist/identifier-hQCs8M1n.mjs.map +0 -1
  247. package/dist/key-BeoOwGr3.mjs +0 -2
  248. package/dist/mysql-adapter-DkJPfoGf.mjs +0 -2
  249. package/dist/postgres-adapter-B3SQvcV1.mjs +0 -2
  250. package/dist/postgres-adapter-B3SQvcV1.mjs.map +0 -1
  251. package/dist/postgres-adapter-CQD2oGuD.mjs +0 -2
  252. package/dist/postgres-adapter-CQD2oGuD.mjs.map +0 -1
  253. package/dist/registration-preflight-DEjv050M.mjs +0 -4
  254. package/dist/registration-preflight-DEjv050M.mjs.map +0 -1
  255. package/dist/result-shape-CTNdNSW3.mjs +0 -2
  256. package/dist/result-shape-CTNdNSW3.mjs.map +0 -1
  257. package/dist/scalar-U0wD5bKy.mjs +0 -2
  258. package/dist/scalar-U0wD5bKy.mjs.map +0 -1
  259. package/dist/schema-Cjem1-0f.mjs +0 -2
  260. package/dist/sql-Bp7jicEX.mjs +0 -2
  261. package/dist/sql-Bp7jicEX.mjs.map +0 -1
  262. package/dist/sqlite-adapter-CW_3l6ea.mjs +0 -2
  263. package/dist/sqlite-adapter-CW_3l6ea.mjs.map +0 -1
  264. package/dist/standard-sql-Bk4RZPqJ.mjs.map +0 -1
  265. package/dist/terminal-C8cq1WWX.mjs +0 -2
  266. package/dist/terminal-C8cq1WWX.mjs.map +0 -1
  267. package/dist/v-D5Z06FKN.mjs +0 -2
  268. package/dist/v-D5Z06FKN.mjs.map +0 -1
  269. package/dist/validation-Dk9Q_-C7.mjs +0 -2
  270. package/dist/validation-Dk9Q_-C7.mjs.map +0 -1
  271. package/dist/validation-PF9-_nKd.mjs +0 -2
  272. package/dist/validator-X9-bwtRo.mjs +0 -2
  273. package/dist/validator-X9-bwtRo.mjs.map +0 -1
  274. package/dist/version-nt0parEY.mjs +0 -2
  275. /package/dist/{contract-CIIqgFyb.d.mts → contract-Dw0FR78e.d.mts} +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"cache.mjs","names":["cache","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 {\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 type { ResolvedExtensionChain } from \"@extensions/chain\";\nimport {\n type AdmittedControls,\n isStableControlValue,\n} from \"@extensions/controls\";\nimport type { WriteOutcomeRegistration } from \"@extensions/query\";\nimport { parse } from \"@validation\";\nimport { readValidationFailureCause } from \"@validation/parse-failure\";\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. 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): unknown {\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 return rows === undefined ? [args, controls] : [args, controls, rows];\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","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":"0nBA+BA,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,GAYtE,SAAgB,WACd,EACA,EACA,EACS,CACT,GAAI,IAAa,IAAA,GAAW,OAAO,EAG9B,UAAO,OAAO,EAAS,C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,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":["cache","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 {\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 type { ResolvedExtensionChain } from \"@extensions/chain\";\nimport {\n type AdmittedControls,\n isStableControlValue,\n} from \"@extensions/controls\";\nimport type { WriteOutcomeRegistration } from \"@extensions/query\";\nimport { parse } from \"@validation\";\nimport { readValidationFailureCause } from \"@validation/parse-failure\";\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. 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): unknown {\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 return rows === undefined ? [args, controls] : [args, controls, rows];\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","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":"2nBA+BA,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,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EAAO,QAAQ,QAAQ,EAAM,OACtB,EAAO,CACd,mBACE,wDACA,EACD,CAEH,IAAK,IAAM,KAAO,GAEd,OAAO,GAAQ,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,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{o as t}from"./value-guards-CK9guf2Z.mjs";import{b as n,n as r}from"./base-AdXAoy6l.mjs";import{t as i}from"./migrations-DTObIjAm.mjs";const a=new TextEncoder;function canonicalizeJson(e){return a.encode(serializeJcs(e))}function canonicalizeJsonText(e){return serializeJcs(e)}function serializeJcs(e){if(e===null)return`null`;if(e===!0)return`true`;if(e===!1)return`false`;if(typeof e==`string`)return JSON.stringify(e);if(typeof e==`number`)return serializeNumber(e);if(Array.isArray(e)){let t=Array(e.length);for(let n=0;n<e.length;n++)t[n]=serializeJcs(e[n]);return`[${t.join(`,`)}]`}if(t(e)){let t=Object.keys(e).sort(compareUtf16),n=Array(t.length);for(let r=0;r<t.length;r++){let i=t[r];n[r]=`${JSON.stringify(i)}:${serializeJcs(e[i])}`}return`{${n.join(`,`)}}`}throw new i(`Canonical JSON refuses undefined, bigint, function, symbol, and boxed values`,r.MIGRATION_INVALID_ESTATE)}function serializeNumber(e){if(!Number.isFinite(e))throw new i(`Canonical JSON refuses NaN and Infinity`,r.MIGRATION_INVALID_ESTATE);return Object.is(e,-0)?`0`:JSON.stringify(e)}function compareUtf16(e,t){return e===t?0:e<t?-1:1}function assertCanonicalBytes(e,t,n){let a=canonicalizeJson(t);if(e.length!==a.length)throw new i(`${n} is not canonical RFC 8785 JSON`,r.MIGRATION_INVALID_ESTATE);for(let t=0;t<e.length;t++)if(e[t]!==a[t])throw new i(`${n} is not canonical RFC 8785 JSON`,r.MIGRATION_INVALID_ESTATE)}function parseJsonBytes(e,t){if(e.length>=3&&e[0]===239&&e[1]===187&&e[2]===191)throw new i(`${t} must be UTF-8 without a BOM`,r.MIGRATION_INVALID_ESTATE);try{return JSON.parse(new TextDecoder(`utf-8`,{fatal:!0}).decode(e))}catch(e){throw new i(`${t} is not valid UTF-8 JSON`,r.MIGRATION_INVALID_ESTATE,{cause:n(e)})}}function bytesEqual(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}export{parseJsonBytes as a,canonicalizeJsonText as i,bytesEqual as n,canonicalizeJson as r,assertCanonicalBytes as t};
2
- //# sourceMappingURL=canonical-json-rfC2Dg0X.mjs.map
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{o as t}from"./value-guards-CK9guf2Z.mjs";import{b as n,n as r}from"./base-D3m1S7Uc.mjs";import{t as i}from"./migrations-Bn1SatyB.mjs";const a=new TextEncoder;function canonicalizeJson(e){return a.encode(serializeJcs(e))}function canonicalizeJsonText(e){return serializeJcs(e)}function serializeJcs(e){if(e===null)return`null`;if(e===!0)return`true`;if(e===!1)return`false`;if(typeof e==`string`)return JSON.stringify(e);if(typeof e==`number`)return serializeNumber(e);if(Array.isArray(e)){let t=Array(e.length);for(let n=0;n<e.length;n++)t[n]=serializeJcs(e[n]);return`[${t.join(`,`)}]`}if(t(e)){let t=Object.keys(e).sort(compareUtf16),n=Array(t.length);for(let r=0;r<t.length;r++){let i=t[r];n[r]=`${JSON.stringify(i)}:${serializeJcs(e[i])}`}return`{${n.join(`,`)}}`}throw new i(`Canonical JSON refuses undefined, bigint, function, symbol, and boxed values`,r.MIGRATION_INVALID_ESTATE)}function serializeNumber(e){if(!Number.isFinite(e))throw new i(`Canonical JSON refuses NaN and Infinity`,r.MIGRATION_INVALID_ESTATE);return Object.is(e,-0)?`0`:JSON.stringify(e)}function compareUtf16(e,t){return e===t?0:e<t?-1:1}function assertCanonicalBytes(e,t,n){let a=canonicalizeJson(t);if(e.length!==a.length)throw new i(`${n} is not canonical RFC 8785 JSON`,r.MIGRATION_INVALID_ESTATE);for(let t=0;t<e.length;t++)if(e[t]!==a[t])throw new i(`${n} is not canonical RFC 8785 JSON`,r.MIGRATION_INVALID_ESTATE)}function parseJsonBytes(e,t){if(e.length>=3&&e[0]===239&&e[1]===187&&e[2]===191)throw new i(`${t} must be UTF-8 without a BOM`,r.MIGRATION_INVALID_ESTATE);try{return JSON.parse(new TextDecoder(`utf-8`,{fatal:!0}).decode(e))}catch(e){throw new i(`${t} is not valid UTF-8 JSON`,r.MIGRATION_INVALID_ESTATE,{cause:n(e)})}}function bytesEqual(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}export{parseJsonBytes as a,canonicalizeJsonText as i,bytesEqual as n,canonicalizeJson as r,assertCanonicalBytes as t};
2
+ //# sourceMappingURL=canonical-json-BReb5nFO.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"canonical-json-rfC2Dg0X.mjs","names":[],"sources":["../src/migrations/canonical-json.ts"],"sourcesContent":["import { errorCause } from \"../errors/diagnostic-safety\";\n/**\n * RFC 8785 JSON Canonicalization Scheme (JCS).\n *\n * Hash identity is these exact UTF-8 bytes. No locale, insertion order,\n * platform line ending, or display formatter participates.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { isRecord } from \"../validation/value-guards\";\n\nconst UTF8 = new TextEncoder();\n\nexport function canonicalizeJson(value: unknown): Uint8Array {\n return UTF8.encode(serializeJcs(value));\n}\n\nexport function canonicalizeJsonText(value: unknown): string {\n return serializeJcs(value);\n}\n\nfunction serializeJcs(value: unknown): string {\n if (value === null) return \"null\";\n if (value === true) return \"true\";\n if (value === false) return \"false\";\n if (typeof value === \"string\") return JSON.stringify(value);\n if (typeof value === \"number\") return serializeNumber(value);\n if (Array.isArray(value)) {\n const parts = new Array<string>(value.length);\n for (let i = 0; i < value.length; i++) {\n parts[i] = serializeJcs(value[i]);\n }\n return `[${parts.join(\",\")}]`;\n }\n if (isRecord(value)) {\n const keys = Object.keys(value).sort(compareUtf16);\n const parts = new Array<string>(keys.length);\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]!;\n parts[i] = `${JSON.stringify(key)}:${serializeJcs(value[key])}`;\n }\n return `{${parts.join(\",\")}}`;\n }\n throw new MigrationError(\n \"Canonical JSON refuses undefined, bigint, function, symbol, and boxed values\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n}\n\nfunction serializeNumber(value: number): string {\n if (!Number.isFinite(value)) {\n throw new MigrationError(\n \"Canonical JSON refuses NaN and Infinity\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n if (Object.is(value, -0)) return \"0\";\n return JSON.stringify(value);\n}\n\nfunction compareUtf16(a: string, b: string): number {\n if (a === b) return 0;\n return a < b ? -1 : 1;\n}\n\nexport function assertCanonicalBytes(\n bytes: Uint8Array,\n reconstructed: unknown,\n label: string\n): void {\n const expected = canonicalizeJson(reconstructed);\n if (bytes.length !== expected.length) {\n throw new MigrationError(\n `${label} is not canonical RFC 8785 JSON`,\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n for (let i = 0; i < bytes.length; i++) {\n if (bytes[i] !== expected[i]) {\n throw new MigrationError(\n `${label} is not canonical RFC 8785 JSON`,\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n }\n}\n\nexport function parseJsonBytes(bytes: Uint8Array, label: string): unknown {\n if (\n bytes.length >= 3 &&\n bytes[0] === 0xef &&\n bytes[1] === 0xbb &&\n bytes[2] === 0xbf\n ) {\n throw new MigrationError(\n `${label} must be UTF-8 without a BOM`,\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n try {\n return JSON.parse(new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes));\n } catch (cause) {\n throw new MigrationError(\n `${label} is not valid UTF-8 JSON`,\n VibORMErrorCode.MIGRATION_INVALID_ESTATE,\n { cause: errorCause(cause) }\n );\n }\n}\n\nexport function bytesEqual(left: Uint8Array, right: Uint8Array): boolean {\n if (left.length !== right.length) return false;\n for (let i = 0; i < left.length; i++) {\n if (left[i] !== right[i]) return false;\n }\n return true;\n}\n"],"mappings":"sLAWA,MAAM,EAAO,IAAI,YAEjB,SAAgB,iBAAiB,EAA4B,CAC3D,OAAO,EAAK,OAAO,aAAa,EAAM,CAAC,CAGzC,SAAgB,qBAAqB,EAAwB,CAC3D,OAAO,aAAa,EAAM,CAG5B,SAAS,aAAa,EAAwB,CAC5C,GAAI,IAAU,KAAM,MAAO,OAC3B,GAAI,IAAU,GAAM,MAAO,OAC3B,GAAI,IAAU,GAAO,MAAO,QAC5B,GAAI,OAAO,GAAU,SAAU,OAAO,KAAK,UAAU,EAAM,CAC3D,GAAI,OAAO,GAAU,SAAU,OAAO,gBAAgB,EAAM,CAC5D,GAAI,MAAM,QAAQ,EAAM,CAAE,CACxB,IAAM,EAAY,MAAc,EAAM,OAAO,CAC7C,IAAK,IAAI,EAAI,EAAG,EAAI,EAAM,OAAQ,IAChC,EAAM,GAA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EAAO,CACd,MAAM,IAAI,EACR,GAAG,EAAM,0BACT,EAAgB,yBAChB,CAAE,MAAO,EAAW,EAAM,CAAE,CAC7B,EAIL,SAAgB,WAAW,EAAkB,EAA4B,CACvE,GAAI,EAAK,SAAW,EAAM,OAAQ,MAAO,GACzC,IAAK,IAAI,EAAI,EAAG,EAAI,EAAK,OAAQ,IAC/B,GAAI,EAAK,KAAO,EAAM,GAAI,MAAO,GAEnC,MAAO"}
1
+ {"version":3,"file":"canonical-json-BReb5nFO.mjs","names":[],"sources":["../src/migrations/canonical-json.ts"],"sourcesContent":["import { errorCause } from \"../errors/diagnostic-safety\";\n/**\n * RFC 8785 JSON Canonicalization Scheme (JCS).\n *\n * Hash identity is these exact UTF-8 bytes. No locale, insertion order,\n * platform line ending, or display formatter participates.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { isRecord } from \"../validation/value-guards\";\n\nconst UTF8 = new TextEncoder();\n\nexport function canonicalizeJson(value: unknown): Uint8Array {\n return UTF8.encode(serializeJcs(value));\n}\n\nexport function canonicalizeJsonText(value: unknown): string {\n return serializeJcs(value);\n}\n\nfunction serializeJcs(value: unknown): string {\n if (value === null) return \"null\";\n if (value === true) return \"true\";\n if (value === false) return \"false\";\n if (typeof value === \"string\") return JSON.stringify(value);\n if (typeof value === \"number\") return serializeNumber(value);\n if (Array.isArray(value)) {\n const parts = new Array<string>(value.length);\n for (let i = 0; i < value.length; i++) {\n parts[i] = serializeJcs(value[i]);\n }\n return `[${parts.join(\",\")}]`;\n }\n if (isRecord(value)) {\n const keys = Object.keys(value).sort(compareUtf16);\n const parts = new Array<string>(keys.length);\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]!;\n parts[i] = `${JSON.stringify(key)}:${serializeJcs(value[key])}`;\n }\n return `{${parts.join(\",\")}}`;\n }\n throw new MigrationError(\n \"Canonical JSON refuses undefined, bigint, function, symbol, and boxed values\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n}\n\nfunction serializeNumber(value: number): string {\n if (!Number.isFinite(value)) {\n throw new MigrationError(\n \"Canonical JSON refuses NaN and Infinity\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n if (Object.is(value, -0)) return \"0\";\n return JSON.stringify(value);\n}\n\nfunction compareUtf16(a: string, b: string): number {\n if (a === b) return 0;\n return a < b ? -1 : 1;\n}\n\nexport function assertCanonicalBytes(\n bytes: Uint8Array,\n reconstructed: unknown,\n label: string\n): void {\n const expected = canonicalizeJson(reconstructed);\n if (bytes.length !== expected.length) {\n throw new MigrationError(\n `${label} is not canonical RFC 8785 JSON`,\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n for (let i = 0; i < bytes.length; i++) {\n if (bytes[i] !== expected[i]) {\n throw new MigrationError(\n `${label} is not canonical RFC 8785 JSON`,\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n }\n}\n\nexport function parseJsonBytes(bytes: Uint8Array, label: string): unknown {\n if (\n bytes.length >= 3 &&\n bytes[0] === 0xef &&\n bytes[1] === 0xbb &&\n bytes[2] === 0xbf\n ) {\n throw new MigrationError(\n `${label} must be UTF-8 without a BOM`,\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n try {\n return JSON.parse(new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes));\n } catch (cause) {\n throw new MigrationError(\n `${label} is not valid UTF-8 JSON`,\n VibORMErrorCode.MIGRATION_INVALID_ESTATE,\n { cause: errorCause(cause) }\n );\n }\n}\n\nexport function bytesEqual(left: Uint8Array, right: Uint8Array): boolean {\n if (left.length !== right.length) return false;\n for (let i = 0; i < left.length; i++) {\n if (left[i] !== right[i]) return false;\n }\n return true;\n}\n"],"mappings":"sLAWA,MAAM,EAAO,IAAI,YAEjB,SAAgB,iBAAiB,EAA4B,CAC3D,OAAO,EAAK,OAAO,aAAa,EAAM,CAAC,CAGzC,SAAgB,qBAAqB,EAAwB,CAC3D,OAAO,aAAa,EAAM,CAG5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OAAQ,IAChC,GAAI,EAAM,KAAO,EAAS,GACxB,MAAM,IAAI,EACR,GAAG,EAAM,iCACT,EAAgB,yBACjB,CAKP,SAAgB,eAAe,EAAmB,EAAwB,CACxE,GACE,EAAM,QAAU,GAChB,EAAM,KAAO,KACb,EAAM,KAAO,KACb,EAAM,KAAO,IAEb,MAAM,IAAI,EACR,GAAG,EAAM,8BACT,EAAgB,yBACjB,CAEH,GAAI,CACF,OAAO,KAAK,MAAM,IAAI,YAAY,QAAS,CAAE,MAAO,GAAM,CAAC,CAAC,OAAO,EAAM,CAAC,OACnE,EAAO,CACd,MAAM,IAAI,EACR,GAAG,EAAM,0BACT,EAAgB,yBAChB,CAAE,MAAO,EAAW,EAAM,CAAE,CAC7B,EAIL,SAAgB,WAAW,EAAkB,EAA4B,CACvE,GAAI,EAAK,SAAW,EAAM,OAAQ,MAAO,GACzC,IAAK,IAAI,EAAI,EAAG,EAAI,EAAK,OAAQ,IAC/B,GAAI,EAAK,KAAO,EAAM,GAAI,MAAO,GAEnC,MAAO"}
@@ -0,0 +1,2 @@
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t,o as n}from"./value-guards-CK9guf2Z.mjs";import{a as r,c as i,f as a,g as o,h as s,o as c,x as l,y as u}from"./controls-KQ85SWfT.mjs";import{b as d}from"./base-D3m1S7Uc.mjs";import{r as f}from"./validation-BamBwne9.mjs";import{_ as p,a as m}from"./v-DtLdBQYg.mjs";import{B as h,rt as g}from"./geo-point-codec-DyEHMdJg.mjs";import{n as _}from"./builder-s1ySUuMb.mjs";import{l as v,n as y,t as b}from"./observation-Co72iCd1.mjs";function readDriverIdentity(e){try{let t=e.adapter.namespace;return Object.freeze({dialect:e.dialect,driverName:e.driverName,...t===void 0?{}:{namespace:t}})}catch{return}}const x=`viborm.defaultOmit`,S=new WeakMap,C=new WeakMap;function configurationError(e,t){throw new f(e,{cause:t===void 0?void 0:d(t)})}function ownKeys(e,t){try{return Reflect.ownKeys(e)}catch(e){configurationError(`Default omit ${t} members could not be inspected.`,e)}}function readOwn$1(e,t,n){try{return e[t]}catch(e){configurationError(`Default omit ${n} member "${t}" could not be read.`,e)}}e(readOwn$1,`readOwn`);function isConfigurationRecord(e,t){try{return n(e)}catch(e){configurationError(`Default omit ${t} could not be inspected.`,e)}}function snapshotConfig(e){isConfigurationRecord(e,`configuration`)||configurationError(`Default omit configuration must be an object.`);let t=Object.create(null);for(let n of ownKeys(e,`configuration`)){typeof n!=`string`&&configurationError(`Default omit configuration contains a non-string model key.`);let r=readOwn$1(e,n,`configuration`);isConfigurationRecord(r,`configuration.${n}`)||configurationError(`Default omit configuration member "${n}" must be an object.`);let i=Object.create(null);for(let e of ownKeys(r,`configuration.${n}`))typeof e!=`string`&&configurationError(`Default omit configuration member "${n}" contains a non-string field key.`),readOwn$1(r,e,`configuration.${n}`)!==!0&&configurationError(`Default omit configuration member "${n}.${e}" must be true.`),i[e]=!0;t[n]=Object.freeze(i)}return Object.freeze(t)}function defaultOmit(){return e=>{let t=Object.freeze({config:snapshotConfig(e)}),request=()=>({});return S.set(request,t),Object.freeze({name:x,request})}}function getOfficialDefaultOmitRequestCapability(e){return t(e)?S.get(e):void 0}function getOfficialDefaultOmitChainCapability(e){return e===void 0?void 0:C.get(e)}function registerOfficialDefaultOmitChain(e,t){C.set(e,t)}const parseStamped=(e,t)=>h((t,n)=>e.get(t)?.create?.[n]!==void 0,t);var Parameter=class{control;path;now;#e;constructor(e,t){e===void 0?this.now=!0:this.control=e,t!==void 0&&(this.path=t),this.#e=t===void 0?[]:t.split(`.`),Object.freeze(this)}read(e,t){if(this.control===void 0)return t();let n=e?.controls[this.control];for(let e of this.#e){if(typeof n!=`object`||!n)return;n=Object.hasOwn(n,e)?n[e]:void 0}return n??void 0}},Condition=class{parameter;test;constructor(e,t){this.parameter=e,this.test=t,Object.freeze(this)}holds(e,t){let n=this.parameter.read(e,t),r=this.test;return`exists`in r?n!==void 0===r.exists:n===void 0?!1:`equals`in r?Object.is(n,r.equals):`in`in r?r.in.includes(n):Array.isArray(n)?`has`in r?n.includes(r.has):r.hasSome.some(e=>n.includes(e)):!1}};const w=new WeakMap;function standaloneRegistry(e){let t=w.get(e);return t===void 0&&(t=_(e),w.set(e,t)),t}const T=new WeakMap,E=new WeakSet;function isImmutableRowData(e,t=new Set){if(typeof e!=`object`||!e)return typeof e!=`function`&&typeof e!=`symbol`;if(E.has(e))return!0;if(!Object.isFrozen(e)||t.has(e))return!1;let n=Object.getPrototypeOf(e);if(Array.isArray(e)?n!==Array.prototype||!Array.from({length:e.length},(t,n)=>Object.hasOwn(e,n)).every(Boolean):n!==Object.prototype&&n!==null&&n!==Parameter.prototype&&n!==Condition.prototype)return!1;t.add(e);let r=Reflect.ownKeys(e).every(n=>{let r=Object.getOwnPropertyDescriptor(e,n);return typeof n==`string`&&r&&`value`in r&&isImmutableRowData(r.value,t)});return t.delete(e),r&&E.add(e),r}function freezeAdmitted(e,t=new Set){if(!(typeof e!=`object`||!e||t.has(e))){t.add(e);for(let n of Object.values(e))freezeAdmitted(n,t);Object.freeze(e)}}const D={predicates:!0,read:!0,update:!0,delete:!0,writes:!0,place:!0,moves:!0,acyclic:!0,evidence:!0,reads:!0},O=/^\$[a-zA-Z_][a-zA-Z0-9_]*$/;function keyFields(e){return new Set([...Object.entries(e.scalars).filter(([,e])=>e[`~`].state.isId===!0).map(([e])=>e),...Object.keys(e.uniques),...[...Object.values(e.compoundId??{}),...Object.values(e.compoundUniques??{})].flatMap(({entries:e})=>Object.keys(e)),...Object.values(e.relations).flatMap(e=>e[`~`].state.foreignKey?.fields??[])])}const k=[`exists`,`equals`,`in`,`has`,`hasSome`];function isReference(e){return p(e)&&typeof e.control==`string`&&Object.keys(e).every(e=>e===`control`||e===`path`)&&(e.path===void 0||typeof e.path==`string`)}const isInstant=e=>p(e)&&e.now===!0&&Object.keys(e).length===1,A=`a condition names one control and exactly one of ${k.join(`, `)}`;function conditionOf(e){if(!p(e))return A;let{control:t,path:n,...r}=e,[i,...a]=Object.keys(r),o=r[i];return typeof t!=`string`||n!==void 0&&typeof n!=`string`||!k.includes(i)||a.length>0||i===`exists`&&typeof o!=`boolean`||(i===`in`||i===`hasSome`)&&!Array.isArray(o)?A:new Condition(new Parameter(t,n),Object.freeze({[i]:o}))}const j={value:e=>isReference(e)?new Parameter(e.control,e.path):isInstant(e)?new Parameter:void 0,condition:conditionOf};function cyclePath(e,t,n=new Set,r=[]){if(!(typeof e!=`object`||!e||t.has(e))){if(n.has(e))return r.join(`.`);n.add(e);for(let[i,a]of Object.entries(e)){r.push(i);let e=cyclePath(a,t,n,r);if(e!==void 0)return e;r.pop()}n.delete(e),t.add(e)}}function admitRows(e,t,n,r=standaloneRegistry(t)){let i=isImmutableRowData(e)&&Object.values(t).every(e=>{let t=e[`~`].state;return Object.values(t.scalars).every(e=>e[`~`].state.schema===void 0)}),a=i?Object.entries(t):void 0,o=i?T.get(r)?.get(e):void 0;if(o&&o.schema===t&&a?.length===o.entries.length&&a.every(([e,t],n)=>e===o.entries[n][0]&&t===o.entries[n][1]))return o.admitted;let refuse=(e,t,r,i)=>{throw new f(`Extension "${n}" rows.${t} at "${r}": ${i}.`,{meta:{extension:n,model:e}})},s=new WeakSet,c=new WeakMap,admit=(e,n,i)=>{let a=cyclePath(i,s);a!==void 0&&refuse(e,n,a,`contains itself`);let o=r.getModelSchemas(t[e]).core.where,l=m(j,()=>g(o,i),c);if(!l.issues)return l.value;let[u]=l.issues;return refuse(e,n,u.path?.map(String).join(`.`)||`root`,u.message)},l={};for(let[n,r]of Object.entries(e.verbs??{})){let e=`verbs.${n}`;Object.hasOwn(t,n)||refuse(n,e,`root`,`names an unknown model`);for(let t of Object.keys(r))Object.hasOwn(D,t)||refuse(n,e,t,`is not one of ${Object.keys(D).join(`, `)}`);let{state:i}=t[n][`~`],a=Object.fromEntries(Object.entries(r.predicates).map(([t,r])=>[t,admit(n,`${e}.predicates.${t}`,r)])),known=(t,r)=>{r!==void 0&&!Object.hasOwn(a,r)&&refuse(n,e,t,`names unknown predicate "${r}"`)};known(`read`,r.read),known(`update`,r.update),known(`delete`,r.delete),known(`place`,r.place);for(let t of[`writes`,`moves`])for(let[a,o]of Object.entries(r[t]??{}))Object.hasOwn(i.scalars,a)||Object.hasOwn(i.relations,a)||refuse(n,e,`${t}.${a}`,`names an unknown field`),known(`${t}.${a}`,o);for(let a of r.acyclic??[]){let r=Object.hasOwn(i.relations,a)?i.relations[a][`~`]:void 0;(r?.state.foreignKey===void 0||r.settleTarget()!==t[n])&&refuse(n,e,`acyclic.${a}`,`names no to-one relation of the model to itself holding its key`)}let{evidence:o}=r;if(o!==void 0){O.test(o.as)||refuse(n,e,`evidence.as`,"is not `$` and an identifier");for(let[e,t]of o.names.entries())known(`evidence.names.${e}`,t)}let s=r.reads===void 0?void 0:keyFields(i);for(let[t,a]of Object.entries(r.reads??{}))Object.hasOwn(i.scalars,t)||refuse(n,e,`reads.${t}`,`names no scalar of the model`),s.has(t)&&refuse(n,e,`reads.${t}`,`names a key, a unique or a foreign key field`),known(`reads.${t}`,a);l[n]=Object.freeze({...r,predicates:Object.freeze(a)})}let u={};for(let[t,n]of Object.entries(e.models)){let e=new Map;for(let[r,i]of Object.entries(n)){let n={};for(let e of[`root`,`related`]){let a=i[e];if(a===void 0)continue;let o=`${t}.${r}.${e}`;typeof a==`string`?Object.hasOwn(l[t]?.predicates??{},a)?n[e]=l[t].predicates[a]:refuse(t,o,`root`,`names unknown predicate "${a}"`):n[e]=admit(t,o,a)}e.set(r,Object.freeze(n))}u[t]=Object.freeze(Object.fromEntries(e))}let d=Object.freeze({...e,models:Object.freeze(u),...e.verbs&&{verbs:Object.freeze(l)}});if(a&&freezeAdmitted(d),a&&isImmutableRowData(d)){let n=T.get(r);n||(n=new WeakMap,T.set(r,n)),n.set(e,{schema:t,entries:a,admitted:d})}return d}const M=new Set([`name`,`request`,`query`,`statement`,`observe`,`client`,`model`,`controls`,`rows`,`deletion`,`data`]);function extensionError(e,t){throw new f(e,{meta:t?{extension:t}:void 0})}function readOwnKeys(e,t){try{return Reflect.ownKeys(e)}catch(e){throw new f(t?`Extension "${t}" members could not be inspected.`:`Client extension members could not be inspected.`,{cause:d(e),meta:t?{extension:t}:void 0})}}function readOwn(e,t,n){try{return e[t]}catch(e){throw new f(n?`Extension "${n}" member "${t}" could not be read.`:`Client extension member "${t}" could not be read.`,{cause:d(e),meta:n?{extension:n}:void 0})}}function requireFunction(e,n,r){return t(e)||extensionError(`Extension "${r}" ${n} must be a function.`,r),e}function snapshotOperationMap(e,r,a,o){if(t(e))return e;n(e)||extensionError(`Extension "${a}" ${r} must be a function or model map.`,a);let s=Object.create(null);for(let t of readOwnKeys(e,a)){typeof t!=`string`&&extensionError(`Extension "${a}" ${r} contains a non-string model key.`,a),o&&!Object.hasOwn(o,t)&&extensionError(`Extension "${a}" ${r} names unknown model "${t}".`,a);let c=readOwn(e,t,a);n(c)||extensionError(`Extension "${a}" ${r}.${t} must be an operation map.`,a);let l=Object.create(null);for(let e of readOwnKeys(c,a))typeof e!=`string`&&extensionError(`Extension "${a}" ${r}.${t} contains a non-string operation key.`,a),i.has(e)||extensionError(`Extension "${a}" ${r}.${t} names unknown operation "${e}".`,a),l[e]=requireFunction(readOwn(c,e,a),`${r}.${t}.${e}`,a);s[t]=Object.freeze(l)}return Object.freeze(s)}function snapshotModelFactories(e,t,r){n(e)||extensionError(`Extension "${t}" model must be a model map.`,t);let i=Object.create(null);for(let n of readOwnKeys(e,t))typeof n!=`string`&&extensionError(`Extension "${t}" model contains a non-string model key.`,t),r&&!Object.hasOwn(r,n)&&extensionError(`Extension "${t}" model names unknown model "${n}".`,t),i[n]=requireFunction(readOwn(e,n,t),`model.${n}`,t);return Object.freeze(i)}function validateNamedPolicies(e,t,r){if(t)for(let i of[`rows`,`data`,`deletion`]){let a=readOwn(e,i,r);if(a===void 0)continue;n(a)||extensionError(`Extension "${r}" ${i} must be an object.`,r);let o=readOwn(a,`models`,r);n(o)||extensionError(`Extension "${r}" ${i}.models must be an object.`,r);let s,c=i===`rows`?readOwn(a,`default`,r):void 0;for(let e of readOwnKeys(o,r)){(typeof e!=`string`||!Object.hasOwn(t,e))&&extensionError(`Extension "${r}" ${i} names unknown model "${String(e)}".`,r);let a=t[e],l=readOwn(o,e,r);n(l)||extensionError(`Extension "${r}" ${i}.${e} must be an object.`,r);let fields=t=>{if(t!==void 0){n(t)||extensionError(`Extension "${r}" ${i}.${e} fields must be an object.`,r);for(let n of readOwnKeys(t,r))(typeof n!=`string`||!Object.hasOwn(a[`~`].state.scalars,n))&&extensionError(`Extension "${r}" ${i}.${e} names unknown field "${String(n)}".`,r)}};if(i===`rows`){let e=readOwnKeys(l,r).filter(e=>typeof e==`string`),t=s;(typeof c!=`string`||!e.includes(c)||t&&(t.length!==e.length||e.some(e=>!t.includes(e))))&&extensionError(`Extension "${r}" row models must share mode names and include the default mode.`,r),s??=e;for(let e of readOwnKeys(l,r))typeof e!=`string`&&extensionError(`Extension "${r}" row mode must be a string.`,r),n(readOwn(l,e,r))||extensionError(`Extension "${r}" row mode must be an object.`,r)}else if(i===`data`)fields(readOwn(l,`create`,r)),fields(readOwn(l,`update`,r));else{let t=readOwn(l,`at`,r);t!==void 0&&(typeof t!=`string`||!Object.hasOwn(a[`~`].state.scalars,t))&&extensionError(`Extension "${r}" deletion.${e}.at names unknown scalar.`,r),fields(readOwn(l,`assign`,r))}}}}function normalizeExtensionDefinition(e,t,r){n(e)||extensionError(`Client extension must be an object.`);let i=readOwnKeys(e);i.includes(`name`)||extensionError(`Client extension name must be a non-empty string.`);let a=readOwn(e,`name`);(typeof a!=`string`||a.trim().length===0)&&extensionError(`Client extension name must be a non-empty string.`);let o=a;for(let e of i)(typeof e!=`string`||!M.has(e))&&extensionError(`Extension "${o}" has unknown member "${String(e)}".`,o);let s=i.includes(`request`)?readOwn(e,`request`,o):void 0,c=s===void 0?void 0:snapshotOperationMap(s,`request`,o,t),l=i.includes(`query`)?readOwn(e,`query`,o):void 0,u=l===void 0?void 0:snapshotOperationMap(l,`query`,o,t),d=i.includes(`statement`)?readOwn(e,`statement`,o):void 0,f=d===void 0?void 0:requireFunction(d,`statement`,o),p=i.includes(`observe`)?readOwn(e,`observe`,o):void 0,m=p===void 0?void 0:requireFunction(p,`observe`,o),h=i.includes(`client`)?readOwn(e,`client`,o):void 0,g=h===void 0?void 0:requireFunction(h,`client`,o),_=i.includes(`model`)?readOwn(e,`model`,o):void 0,v=_===void 0?void 0:snapshotModelFactories(_,o,t),{controls:y,deletion:b,data:x}=e;validateNamedPolicies({rows:e.rows,deletion:b,data:x},t,o);let S=t&&e.rows?admitRows(e.rows,t,o,r):e.rows;return Object.freeze({name:o,...c?{request:c}:{},...u?{query:u}:{},...f?{statement:f}:{},...m?{observe:m}:{},...g?{client:g}:{},...v?{model:v}:{},...y?{controls:y}:{},...S?{rows:S}:{},...b?{deletion:b}:{},...x?{data:x}:{}})}function defineExtension(...e){return e.length===0?e=>normalizeExtensionDefinition(e):normalizeExtensionDefinition(e[0])}const NEVER_REQUIRED=()=>!1,N=Object.freeze(Object.create(null)),P=Object.freeze({}),F=Symbol(`absent`);function collectReferences(e,t,n=new Set){let r=e instanceof Condition?e.parameter:e;if(r instanceof Parameter)r.control!==void 0&&t.add(r.control);else if(isReference(e))t.add(e.control);else if(Array.isArray(e)||p(e)){if(n.has(e))return;n.add(e);for(let r of Object.values(e))collectReferences(r,t,n)}}const I=new WeakMap;function referencesOfRows(e){let t=I.get(e);if(t)return t;let n=new Set,r=new Set;for(let t of Object.values(e.models))for(let e of Object.values(t))collectReferences(e.root,n,r),collectReferences(e.related,n,r);for(let t of Object.values(e.verbs??{}))collectReferences(t.predicates,n,r);let i=[...n];return isImmutableRowData(e)&&I.set(e,i),i}function collectStampReferences(e,t){for(let n of Object.values(e??{}))collectReferences(n,t)}function undeclaredControlReferencesOf(e){let t=new Set(Object.keys(e.controls??{}));e.rows&&t.add(e.rows.control);let n=new Set(e.rows?referencesOfRows(e.rows):[]);for(let t of Object.values(e.data?.models??{}))collectStampReferences(t.create,n),collectStampReferences(t.update,n);for(let t of Object.keys(e.deletion?.removeWhen??{}))n.add(t);return[...n].filter(e=>!t.has(e))}function readsCall(e){return e instanceof Parameter||e instanceof Condition?!0:Array.isArray(e)?e.some(readsCall):p(e)&&Object.values(e).some(readsCall)}function stampValue(e,t){if(isReference(e)){let n=t?.[e.control],{path:r}=e;for(let e of r===void 0?[]:r.split(`.`))n=p(n)&&Object.hasOwn(n,e)?n[e]:void 0;return n===void 0?F:n}if(Array.isArray(e)){let n=e.map(e=>stampValue(e,t));return n.includes(F)?F:n.every((t,n)=>t===e[n])?e:n}if(!p(e))return e;let n;for(let[r,i]of Object.entries(e)){let a=stampValue(i,t);if(a===F)return F;a!==i&&((n??={...e})[r]=a)}return n??e}function boundStamp(e,t){if(e===void 0)return;let n={},r=!1;for(let[i,a]of Object.entries(e)){let e=stampValue(a,t);r||=e!==a,e!==F&&(n[i]=e)}return r?Object.freeze(n):e}function boundStamps(e,t){let n=new Map;for(let[r,i]of e){let e=boundStamp(i.create,t),a=boundStamp(i.update,t);n.set(r,e===i.create&&a===i.update?i:Object.freeze({create:e,update:a}))}return n}const L=new Parameter;function withInstants(e){let t;for(let[n,r]of Object.entries(e??{}))isInstant(r)&&((t??={...e})[n]=L);return t===void 0?e:Object.freeze(t)}function requiredOn(e){let t=new Map;for(let n of e?.all??[])n.required!==void 0&&t.set(n.name,n.required);return t.size===0?NEVER_REQUIRED:(e,n)=>{let r=t.get(e);return r===!0||r?.has(n)===!0}}function modelDomain(e,t,n){let r=new Map;for(let[i,a]of e.entries())for(let[e,o]of Object.entries(a.models)){let a=o[t[i]]?.[n];if(a===void 0)continue;let s=r.get(e)??[];s[i]=a,r.set(e,s)}return r}const R=Object.freeze({OR:Object.freeze([])}),fieldsOf=(e,t)=>new Map(Object.entries(e??{}).map(([e,n])=>[e,t(n)]));function modelVerbs(e){let t=new Map,n=new Set;for(let[r,i]of e.entries())for(let[e,a]of Object.entries(i.verbs??{})){let i=a.evidence&&`${e}.${a.evidence.as}`;if(i!==void 0&&n.has(i))throw new f(`rows.verbs.${e}.evidence.as "${a.evidence.as}" is declared by two extensions of the chain.`,{meta:{model:e}});i!==void 0&&n.add(i);let named=e=>e===void 0?R:a.predicates[e],o=t.get(e)??[];o[r]=Object.freeze({read:named(a.read),update:named(a.update),delete:named(a.delete),writes:fieldsOf(a.writes,named),...a.place!==void 0&&{place:named(a.place)},moves:fieldsOf(a.moves,named),acyclic:Object.freeze([...a.acyclic??[]]),...a.evidence&&{evidence:Object.freeze({as:a.evidence.as,names:Object.freeze(a.evidence.names.map(e=>Object.freeze([e,named(e)]))),ordered:a.evidence.ordered===!0})},reads:fieldsOf(a.reads,named)}),t.set(e,o)}return t.size===0?void 0:t}function bindRows(e,t,n,r){let i=e??[],a=1,o=i.map(e=>{let t=c(e),n={control:e.control,names:t,modes:new Map(t.map((e,t)=>[e,t])),fallback:t.indexOf(e.default),stride:a};return a*=t.length,n}),s=[],l=modelVerbs(i);for(let e=0;e<a;e++){let t=o.map(t=>t.names[Math.floor(e/t.stride)%t.names.length]);s.push(Object.freeze({root:modelDomain(i,t,`root`),related:modelDomain(i,t,`related`),...l&&{verbs:l}}))}let u=s[o.reduce((e,t)=>e+t.fallback*t.stride,0)],d=t===void 0?void 0:new Map(Object.entries(t)),f=n===void 0?void 0:new Map(Object.entries(n).map(([e,t])=>{let n=withInstants(t.create),r=withInstants(t.update);return[e,n===t.create&&r===t.update?t:Object.freeze({create:n,update:r})]})),p=new Set;for(let e of f?.values()??[])collectStampReferences(e.create,p),collectStampReferences(e.update,p);let m=s.map(e=>Object.freeze({domain:e,defaults:u,...f&&{stamps:f}})),h=i.some(e=>Object.values(e.verbs??{}).some(e=>readsCall(e.predicates))),reads=e=>h||[e.root,e.related].some(e=>[...e.values()].some(readsCall));return Object.freeze({members:o,deletion:t??N,physical:m,tombstoning:d===void 0?m:m.map(e=>Object.freeze({...e,tombstones:d})),parametric:s.map(e=>reads(e)||reads(u)),bindsStamps:p.size>0,required:requiredOn(r)})}function callRows(e,t,n){let r=0;for(let t of e.members)r+=t.stride*(t.modes.get(n?.[t.control])??t.fallback);let i=e.deletion[t]?.removeWhen,a=(i!==void 0&&Object.entries(i).every(([e,t])=>n?.[e]===t)?e.physical:e.tombstoning)[r],o=e.parametric[r];return o||e.bindsStamps?Object.freeze({...a,...o&&{values:Object.freeze({controls:n??P,required:e.required})},...e.bindsStamps&&{stamps:boundStamps(a.stamps,n)}}):a}const z=`viborm.instrumentation`;function lookupResolvedExtensionHandlers(e,t,n,r){if(e===void 0)return;let i=e[t],a=i.global.length===0?void 0:i.global;return n===void 0?t===`query`?a:void 0:i.models[n]?.[r]??a}function lookupPlacedControls(e,t,n){return e?.controls?.placed(t,n)??B}const B=Object.freeze([]);function resolvedHandler(e,t){return Object.freeze({extension:e.name,handler:t})}function resolvedOperationHandler(e,t){return Object.freeze(e.controls===void 0?{extension:e.name,handler:t}:{extension:e.name,handler:t,controls:e.controls})}function appendModelHandler(e,t,n,r,i){let a=e[t]??=Object.create(null);(a[n]??=[...i]).push(r)}function appendGlobalHandler(e,t){for(let n of Object.values(e))for(let e of Object.values(n))e.push(t)}function appendOperationHandlers(e,n,r){if(r===void 0&&e!==void 0)return e;let i=Object.create(null),a=e?[...e.global]:[];if(e)for(let[t,n]of Object.entries(e.models)){let e=Object.create(null);for(let[t,r]of Object.entries(n))e[t]=[...r];i[t]=e}if(r)if(t(r)){let e=resolvedOperationHandler(n,r);a.push(e),appendGlobalHandler(i,e)}else for(let[e,t]of Object.entries(r))for(let[r,o]of Object.entries(t))appendModelHandler(i,e,r,resolvedOperationHandler(n,o),a);let o=Object.create(null);for(let[e,t]of Object.entries(i)){let n=Object.create(null);for(let[e,r]of Object.entries(t))n[e]=Object.freeze(r);o[e]=Object.freeze(n)}return Object.freeze({global:Object.freeze(a),models:Object.freeze(o)})}function hasCompiledHandlers(e){if(e.global.length>0)return!0;for(let t of Object.values(e.models))if(Object.keys(t).length>0)return!0;return!1}function appendFlatHandler(e,t,n){if(n===void 0)return e??Object.freeze([]);let r=e?[...e]:[];return r.push(resolvedHandler(t,n)),Object.freeze(r)}function appendObserver(e,t,n){if(n===void 0)return e??Object.freeze([]);let r=y(n);return r!==void 0&&!r.observesLifecycle?e??Object.freeze([]):appendFlatHandler(e,t,n)}function appendControls(e,t){let n=new Set(e?.names);for(let{name:r,extension:i}of t){if(n.has(r)){let n=[...e?.all??[],...t].find(e=>e.name===r).extension;extensionError(`Extension "${i}" declares control "${r}", which extension "${n}" already declares.`,i)}n.add(r)}let r=Object.freeze([...e?.all??[],...t.map(e=>Object.freeze(e))]),i=new Map,placed=(e,t)=>{let n=`${e}\u0000${t}`,a=i.get(n);if(a===void 0){let o=r.filter(n=>n.operations.has(t)&&(n.models===void 0||n.models.has(e)));a=o.length===0?B:Object.freeze(o),i.set(n,a)}return a};return Object.freeze({names:n,all:r,placed})}const V=Object.freeze({});function appendDeletion(e,t,n){let r=Object.create(null);Object.assign(r,e);for(let[e,i]of Object.entries(n.models))r[e]=Object.freeze({extension:t,...i,assign:i.assign??V,...n.removeWhen===void 0?{}:{removeWhen:n.removeWhen}});return Object.freeze(r)}function withStamp(e,t){return t===void 0?e:Object.freeze({...e,...t})}function appendData(e,t){let n=Object.create(null);Object.assign(n,e);for(let[e,r]of Object.entries(t.models)){let t=n[e];n[e]=Object.freeze({create:withStamp(t?.create,r.create),update:withStamp(t?.update,r.update)})}return Object.freeze(n)}function asOfficialCacheDefinition(e){let{query:t,...n}=e;return Object.freeze({...n,controls:u})}function stripOfficialDefaultOmitRequest(e){let{request:t,...n}=e;return Object.freeze(n)}function consumesOperationResults(e){return e.query!==void 0&&!t(e.query)||e.client!==void 0||e.model!==void 0}function assertOfficialExtensionAdmission(e){e.hasIdentity&&e.isAlreadyPresent&&extensionError(e.duplicateMessage,e.definitionName),e.hasIdentity&&e.definitionName!==e.officialName&&extensionError(`The official ${e.label} extension name must be "${e.officialName}".`,e.definitionName),!e.hasIdentity&&e.definitionName===e.officialName&&extensionError(`Extension name "${e.officialName}" is reserved for the official ${e.label} extension.`,e.definitionName)}function appendResolvedExtension(e,t,n,i){let c=normalizeExtensionDefinition(t,n,i),u=o(c.query),d=s(e),f=getOfficialDefaultOmitRequestCapability(c.request),p=getOfficialDefaultOmitChainCapability(e);assertOfficialExtensionAdmission({definitionName:c.name,officialName:a,label:`cache`,hasIdentity:u!==void 0,isAlreadyPresent:d!==void 0,duplicateMessage:`The official cache extension is already present on this client.`}),assertOfficialExtensionAdmission({definitionName:c.name,officialName:x,label:`default omit`,hasIdentity:f!==void 0,isAlreadyPresent:!1,duplicateMessage:`Extension "${x}" is already present on this client.`}),f!==void 0&&e?.hasResultConsumers===!0&&extensionError(`The default omit extension cannot follow an extension that defines model-mapped query, client, or model behavior.`,c.name),c.rows!==void 0&&e?.hasResultConsumers===!0&&extensionError(`Extension "${c.name}" declares rows, which cannot follow an extension that defines model-mapped query, client, or model behavior.`,c.name);let m=y(c.observe),h=b(e);assertOfficialExtensionAdmission({definitionName:c.name,officialName:z,label:`instrumentation`,hasIdentity:m!==void 0,isAlreadyPresent:h!==void 0,duplicateMessage:`The official instrumentation extension is already present on this client.`}),e?.extensions.some(e=>e.name===c.name)&&extensionError(`Extension "${c.name}" is already present on this client.`,c.name);let g=u===void 0?f===void 0?c:stripOfficialDefaultOmitRequest(c):asOfficialCacheDefinition(c),_=g.controls===void 0&&g.rows===void 0?void 0:r(g);for(let t of undeclaredControlReferencesOf(g))e?.controls?.names.has(t)!==!0&&extensionError(`Extension "${c.name}" references undeclared control "${t}".`,c.name);let S=Object.freeze({name:c.name,...g.client===void 0?{}:{client:g.client},...g.model===void 0?{}:{model:g.model}}),C=_===void 0?S:{name:c.name,controls:Object.freeze(_.map(e=>e.name))},w=Object.freeze(e?[...e.extensions,S]:[S]),T=appendOperationHandlers(e?.request,C,g.request),E=appendOperationHandlers(e?.query,C,g.query),D=_===void 0?e?.controls:appendControls(e?.controls,_),O=g.rows===void 0?e?.rows:Object.freeze([...e?.rows??[],g.rows]),k=g.deletion===void 0?e?.deletion:appendDeletion(e?.deletion,c.name,g.deletion),A=g.data===void 0?e?.data:appendData(e?.data,g.data),j=O===e?.rows&&k===e?.deletion&&A===e?.data?e?.callRows:bindRows(O,k,A,D),M=Object.freeze({...D===void 0?{}:{controls:D},...O===void 0?{}:{rows:O},...k===void 0?{}:{deletion:k},...A===void 0?{}:{data:A},...j===void 0?{}:{callRows:j},extensions:w,hasCache:u!==void 0||e?.hasCache===!0,hasRequestHandlers:hasCompiledHandlers(T),hasQueryHandlers:hasCompiledHandlers(E),hasResultConsumers:e?.hasResultConsumers===!0||consumesOperationResults(g),request:T,query:E,statement:appendFlatHandler(e?.statement,S,g.statement),observe:appendObserver(e?.observe,S,g.observe)}),N=m??h;N!==void 0&&v(M,N);let P=u??d;P!==void 0&&l(M,P);let F=f??p;return F!==void 0&&registerOfficialDefaultOmitChain(M,F),M}export{callRows as a,Condition as c,defaultOmit as d,getOfficialDefaultOmitChainCapability as f,lookupResolvedExtensionHandlers as i,Parameter as l,appendResolvedExtension as n,defineExtension as o,readDriverIdentity as p,lookupPlacedControls as r,extensionError as s,z as t,parseStamped as u};
2
+ //# sourceMappingURL=chain-7qiFSE8J.mjs.map