viborm 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (300) hide show
  1. package/README.md +4 -3
  2. package/dist/{adapter-namespace-DMhEF6my.mjs → adapter-namespace-DqkJQdrD.mjs} +2 -2
  3. package/dist/{adapter-namespace-DMhEF6my.mjs.map → adapter-namespace-DqkJQdrD.mjs.map} +1 -1
  4. package/dist/adapters.d.mts +1 -1
  5. package/dist/adapters.mjs +1 -1
  6. package/dist/{array-literal-D9FexFqy.mjs → array-literal-BsbbSLw3.mjs} +1 -1
  7. package/dist/{array-literal-D9FexFqy.mjs.map → array-literal-BsbbSLw3.mjs.map} +1 -1
  8. package/dist/base-AdXAoy6l.mjs +2 -0
  9. package/dist/base-AdXAoy6l.mjs.map +1 -0
  10. package/dist/batch-refs-4L8ECdPU.mjs +2 -0
  11. package/dist/batch-refs-4L8ECdPU.mjs.map +1 -0
  12. package/dist/bind-parameter-capacity-CjPgqnmx.mjs +2 -0
  13. package/dist/{bind-parameter-capacity-DzMcIB95.mjs.map → bind-parameter-capacity-CjPgqnmx.mjs.map} +1 -1
  14. package/dist/builder-Ycvq3ETg.mjs +2 -0
  15. package/dist/builder-Ycvq3ETg.mjs.map +1 -0
  16. package/dist/bun-sql.d.mts +19 -2
  17. package/dist/bun-sql.mjs +1 -1
  18. package/dist/bun-sql.mjs.map +1 -1
  19. package/dist/bun-sqlite.d.mts +9 -8
  20. package/dist/bun-sqlite.mjs +1 -1
  21. package/dist/bun-sqlite.mjs.map +1 -1
  22. package/dist/cache/cloudflare-kv.d.mts +1 -1
  23. package/dist/cache/cloudflare-kv.mjs +1 -1
  24. package/dist/cache/memory.d.mts +1 -1
  25. package/dist/cache/memory.mjs +1 -1
  26. package/dist/cache/memory.mjs.map +1 -1
  27. package/dist/cache-BO57X0TT.mjs +2 -0
  28. package/dist/cache-BO57X0TT.mjs.map +1 -0
  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 +2 -0
  33. package/dist/canonical-json-rfC2Dg0X.mjs.map +1 -0
  34. package/dist/chain-Dh0FV72b.mjs +2 -0
  35. package/dist/chain-Dh0FV72b.mjs.map +1 -0
  36. package/dist/cli.mjs +5 -6
  37. package/dist/cli.mjs.map +1 -1
  38. package/dist/client-BLiBmykn.mjs +2 -0
  39. package/dist/client-BLiBmykn.mjs.map +1 -0
  40. package/dist/client-CCgfcp5A.mjs +52 -0
  41. package/dist/client-CCgfcp5A.mjs.map +1 -0
  42. package/dist/client-CRBo95D0.d.mts +610 -0
  43. package/dist/client.d.mts +1 -1
  44. package/dist/client.mjs +1 -1
  45. package/dist/{clock-W8H2Khng.mjs → clock-CK41KO7t.mjs} +1 -1
  46. package/dist/{clock-W8H2Khng.mjs.map → clock-CK41KO7t.mjs.map} +1 -1
  47. package/dist/config.d.mts +3 -3
  48. package/dist/config.mjs +1 -1
  49. package/dist/controls-DXgIn4zh.mjs +2 -0
  50. package/dist/controls-DXgIn4zh.mjs.map +1 -0
  51. package/dist/d1.d.mts +1 -1
  52. package/dist/d1.mjs +1 -1
  53. package/dist/d1.mjs.map +1 -1
  54. package/dist/datetime-physical-codec-oIhiYZEP.mjs +2 -0
  55. package/dist/datetime-physical-codec-oIhiYZEP.mjs.map +1 -0
  56. package/dist/driver-B19QlFqn.mjs +2 -0
  57. package/dist/{driver-CRaDT4B7.mjs.map → driver-B19QlFqn.mjs.map} +1 -1
  58. package/dist/driver-BlnKXPFF.mjs +2 -0
  59. package/dist/driver-BlnKXPFF.mjs.map +1 -0
  60. package/dist/driver.d.mts +2 -2
  61. package/dist/driver.mjs +1 -1
  62. package/dist/error-mapping-CnPCv1dm.mjs +2 -0
  63. package/dist/error-mapping-CnPCv1dm.mjs.map +1 -0
  64. package/dist/every-4KE0p2Gw.mjs +2 -0
  65. package/dist/every-4KE0p2Gw.mjs.map +1 -0
  66. package/dist/execution-context-BKR3bgES.mjs +2 -0
  67. package/dist/execution-context-BKR3bgES.mjs.map +1 -0
  68. package/dist/fs-estate-CAhDg7nY.mjs +2 -0
  69. package/dist/fs-estate-CAhDg7nY.mjs.map +1 -0
  70. package/dist/{geo-area-codec-B4DRInvA.mjs → geo-area-codec-1SY9im7O.mjs} +2 -2
  71. package/dist/{geo-area-codec-B4DRInvA.mjs.map → geo-area-codec-1SY9im7O.mjs.map} +1 -1
  72. package/dist/geo-point-codec-lhxH42SK.mjs +2 -0
  73. package/dist/geo-point-codec-lhxH42SK.mjs.map +1 -0
  74. package/dist/{hydration-D6JICBQG.mjs → hydration-CAxOL4aI.mjs} +2 -2
  75. package/dist/{hydration-D6JICBQG.mjs.map → hydration-CAxOL4aI.mjs.map} +1 -1
  76. package/dist/identifier-conversion-GgbwHc2G.mjs +2 -0
  77. package/dist/identifier-conversion-GgbwHc2G.mjs.map +1 -0
  78. package/dist/{identifier-EsWKVHXi.mjs → identifier-hQCs8M1n.mjs} +2 -2
  79. package/dist/{identifier-EsWKVHXi.mjs.map → identifier-hQCs8M1n.mjs.map} +1 -1
  80. package/dist/identity-CLFhCTZx.mjs +2 -0
  81. package/dist/identity-CLFhCTZx.mjs.map +1 -0
  82. package/dist/{index-T0YKKw66.d.mts → index-C_XLSTy2.d.mts} +723 -400
  83. package/dist/index.d.mts +2 -2
  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/instrumentation.mjs.map +1 -1
  89. package/dist/{invariant-DCsftyml.mjs → invariant-BnLYqsHO.mjs} +1 -1
  90. package/dist/{invariant-DCsftyml.mjs.map → invariant-BnLYqsHO.mjs.map} +1 -1
  91. package/dist/{json-number-C10HFiy6.mjs → json-number-CGXpPu4D.mjs} +1 -1
  92. package/dist/{json-number-C10HFiy6.mjs.map → json-number-CGXpPu4D.mjs.map} +1 -1
  93. package/dist/key-BeoOwGr3.mjs +2 -0
  94. package/dist/key-BeoOwGr3.mjs.map +1 -0
  95. package/dist/libsql-Bu_IdFU1.mjs +11 -0
  96. package/dist/libsql-Bu_IdFU1.mjs.map +1 -0
  97. package/dist/libsql.d.mts +8 -3
  98. package/dist/libsql.mjs +1 -1
  99. package/dist/libsql.mjs.map +1 -1
  100. package/dist/memory-D4yxtCPK.mjs +2 -0
  101. package/dist/memory-D4yxtCPK.mjs.map +1 -0
  102. package/dist/migrations/mysql.d.mts +6 -0
  103. package/dist/migrations/mysql.mjs +2 -0
  104. package/dist/migrations/mysql.mjs.map +1 -0
  105. package/dist/migrations/postgres.d.mts +6 -0
  106. package/dist/migrations/postgres.mjs +2 -0
  107. package/dist/migrations/postgres.mjs.map +1 -0
  108. package/dist/migrations/sqlite.d.mts +6 -0
  109. package/dist/migrations/sqlite.mjs +2 -0
  110. package/dist/migrations/sqlite.mjs.map +1 -0
  111. package/dist/migrations/storage/durable-object.d.mts +17 -0
  112. package/dist/migrations/storage/durable-object.mjs +2 -0
  113. package/dist/migrations/storage/durable-object.mjs.map +1 -0
  114. package/dist/migrations/storage/fs.d.mts +6 -1
  115. package/dist/migrations/storage/fs.mjs +1 -1
  116. package/dist/migrations/storage/r2.d.mts +14 -0
  117. package/dist/migrations/storage/r2.mjs +2 -0
  118. package/dist/migrations/storage/r2.mjs.map +1 -0
  119. package/dist/migrations/tenant.d.mts +92 -0
  120. package/dist/migrations/tenant.mjs +2 -0
  121. package/dist/migrations/tenant.mjs.map +1 -0
  122. package/dist/{migrations-BWZSBMZh.mjs → migrations-DTObIjAm.mjs} +2 -2
  123. package/dist/migrations-DTObIjAm.mjs.map +1 -0
  124. package/dist/migrations.d.mts +6 -559
  125. package/dist/migrations.mjs +1 -1
  126. package/dist/migrations.mjs.map +1 -1
  127. package/dist/mysql-CibPaHSp.mjs +99 -0
  128. package/dist/mysql-CibPaHSp.mjs.map +1 -0
  129. package/dist/mysql-adapter-DkJPfoGf.mjs +2 -0
  130. package/dist/mysql-adapter-DkJPfoGf.mjs.map +1 -0
  131. package/dist/mysql2.d.mts +1 -3
  132. package/dist/mysql2.mjs +1 -1
  133. package/dist/mysql2.mjs.map +1 -1
  134. package/dist/neon-http.d.mts +1 -1
  135. package/dist/neon-http.mjs +1 -1
  136. package/dist/neon-http.mjs.map +1 -1
  137. package/dist/object-store-DQR6bTBY.mjs +2 -0
  138. package/dist/object-store-DQR6bTBY.mjs.map +1 -0
  139. package/dist/object-store-DyYOCtmX.d.mts +156 -0
  140. package/dist/observation-DUSm7oXK.mjs +2 -0
  141. package/dist/observation-DUSm7oXK.mjs.map +1 -0
  142. package/dist/pg.d.mts +37 -12
  143. package/dist/pg.mjs +1 -1
  144. package/dist/pg.mjs.map +1 -1
  145. package/dist/pglite.d.mts +2 -1
  146. package/dist/pglite.mjs +1 -1
  147. package/dist/pglite.mjs.map +1 -1
  148. package/dist/physical-6V_LNU3L.mjs +2 -0
  149. package/dist/{physical-BkelResN.mjs.map → physical-6V_LNU3L.mjs.map} +1 -1
  150. package/dist/pinned-session-CLxj5M5e.mjs +2 -0
  151. package/dist/pinned-session-CLxj5M5e.mjs.map +1 -0
  152. package/dist/planetscale.d.mts +1 -1
  153. package/dist/planetscale.mjs +1 -1
  154. package/dist/planetscale.mjs.map +1 -1
  155. package/dist/{planner-B11VjIin.d.mts → planner-C6Lfsasx.d.mts} +57 -3
  156. package/dist/postgres-adapter-B3SQvcV1.mjs +2 -0
  157. package/dist/postgres-adapter-B3SQvcV1.mjs.map +1 -0
  158. package/dist/postgres-adapter-CQD2oGuD.mjs +2 -0
  159. package/dist/postgres-adapter-CQD2oGuD.mjs.map +1 -0
  160. package/dist/postgres-oqNW9xqo.mjs +415 -0
  161. package/dist/postgres-oqNW9xqo.mjs.map +1 -0
  162. package/dist/{postgres-result-Dc_iW3Hb.mjs → postgres-result-7F0DllQe.mjs} +2 -2
  163. package/dist/{postgres-result-Dc_iW3Hb.mjs.map → postgres-result-7F0DllQe.mjs.map} +1 -1
  164. package/dist/postgres.d.mts +11 -1
  165. package/dist/postgres.mjs +1 -1
  166. package/dist/postgres.mjs.map +1 -1
  167. package/dist/provider-limits-BHATED_m.mjs +2 -0
  168. package/dist/provider-limits-BHATED_m.mjs.map +1 -0
  169. package/dist/registration-preflight-DEjv050M.mjs +4 -0
  170. package/dist/registration-preflight-DEjv050M.mjs.map +1 -0
  171. package/dist/result-shape-CTNdNSW3.mjs +2 -0
  172. package/dist/result-shape-CTNdNSW3.mjs.map +1 -0
  173. package/dist/scalar-U0wD5bKy.mjs +2 -0
  174. package/dist/{scalar-BTktMqvO.mjs.map → scalar-U0wD5bKy.mjs.map} +1 -1
  175. package/dist/schema/json.d.mts +1 -1
  176. package/dist/schema/json.mjs +1 -1
  177. package/dist/schema/json.mjs.map +1 -1
  178. package/dist/schema-Cjem1-0f.mjs +2 -0
  179. package/dist/{schema-BFNcMdO6.mjs.map → schema-Cjem1-0f.mjs.map} +1 -1
  180. package/dist/schema-introspection-DEYGC2qg.mjs +6 -0
  181. package/dist/schema-introspection-DEYGC2qg.mjs.map +1 -0
  182. package/dist/schema.d.mts +1 -1
  183. package/dist/schema.mjs +1 -1
  184. package/dist/{select-assembly-BgqlrePH.mjs → select-assembly-f1UGoblh.mjs} +2 -2
  185. package/dist/select-assembly-f1UGoblh.mjs.map +1 -0
  186. package/dist/settle-B9Vg1FnP.mjs +2 -0
  187. package/dist/settle-B9Vg1FnP.mjs.map +1 -0
  188. package/dist/soft-delete.d.mts +1 -1
  189. package/dist/{sql--69HUgel.mjs → sql-Bp7jicEX.mjs} +1 -1
  190. package/dist/{sql--69HUgel.mjs.map → sql-Bp7jicEX.mjs.map} +1 -1
  191. package/dist/{sql-statement-tokens-CykxFmOJ.mjs → sql-statement-tokens-BBcoGmJb.mjs} +1 -1
  192. package/dist/{sql-statement-tokens-CykxFmOJ.mjs.map → sql-statement-tokens-BBcoGmJb.mjs.map} +1 -1
  193. package/dist/sql.d.mts +1 -1
  194. package/dist/sql.mjs +1 -1
  195. package/dist/sqlite-adapter-CW_3l6ea.mjs +2 -0
  196. package/dist/sqlite-adapter-CW_3l6ea.mjs.map +1 -0
  197. package/dist/sqlite-utils-DlgokMJN.mjs +2 -0
  198. package/dist/sqlite-utils-DlgokMJN.mjs.map +1 -0
  199. package/dist/sqlite3.d.mts +2 -8
  200. package/dist/sqlite3.mjs +1 -1
  201. package/dist/sqlite3.mjs.map +1 -1
  202. package/dist/standard-sql-Bk4RZPqJ.mjs +6 -0
  203. package/dist/standard-sql-Bk4RZPqJ.mjs.map +1 -0
  204. package/dist/{suppressed-failure-BPxfHTMc.mjs → suppressed-failure-BwULh-8h.mjs} +1 -1
  205. package/dist/{suppressed-failure-BPxfHTMc.mjs.map → suppressed-failure-BwULh-8h.mjs.map} +1 -1
  206. package/dist/{terminal-BbRi0CNZ.mjs → terminal-C8cq1WWX.mjs} +2 -2
  207. package/dist/{terminal-BbRi0CNZ.mjs.map → terminal-C8cq1WWX.mjs.map} +1 -1
  208. package/dist/{transaction-oskVwmsf.mjs → transaction-Bnl6ULTw.mjs} +2 -2
  209. package/dist/transaction-Bnl6ULTw.mjs.map +1 -0
  210. package/dist/{transaction-operation-BC7aua5V.mjs → transaction-operation-CKK3l_9x.mjs} +2 -2
  211. package/dist/transaction-operation-CKK3l_9x.mjs.map +1 -0
  212. package/dist/{utils-DfztpPvR.mjs → utils-CZNaOZR7.mjs} +4 -3
  213. package/dist/utils-CZNaOZR7.mjs.map +1 -0
  214. package/dist/v-D5Z06FKN.mjs +2 -0
  215. package/dist/v-D5Z06FKN.mjs.map +1 -0
  216. package/dist/validation-Dk9Q_-C7.mjs +2 -0
  217. package/dist/validation-Dk9Q_-C7.mjs.map +1 -0
  218. package/dist/validation-PF9-_nKd.mjs +2 -0
  219. package/dist/{validation-tgjL_9n8.mjs.map → validation-PF9-_nKd.mjs.map} +1 -1
  220. package/dist/validation.d.mts +1 -1
  221. package/dist/validation.mjs +1 -1
  222. package/dist/validator-X9-bwtRo.mjs +2 -0
  223. package/dist/{validator-DMlEScV3.mjs.map → validator-X9-bwtRo.mjs.map} +1 -1
  224. package/dist/value-guards-CK9guf2Z.mjs +2 -0
  225. package/dist/value-guards-CK9guf2Z.mjs.map +1 -0
  226. package/dist/version-JDaZht4U.mjs +2 -0
  227. package/dist/{version-Cr80LFvx.mjs.map → version-JDaZht4U.mjs.map} +1 -1
  228. package/package.json +75 -34
  229. package/dist/base-vfur-DaU.mjs +0 -2
  230. package/dist/base-vfur-DaU.mjs.map +0 -1
  231. package/dist/batch-refs-BY51FIXm.mjs +0 -6
  232. package/dist/batch-refs-BY51FIXm.mjs.map +0 -1
  233. package/dist/bind-parameter-capacity-DzMcIB95.mjs +0 -2
  234. package/dist/builder-bPfagDQV.mjs +0 -2
  235. package/dist/builder-bPfagDQV.mjs.map +0 -1
  236. package/dist/chain-uIFlkkXS.mjs +0 -2
  237. package/dist/chain-uIFlkkXS.mjs.map +0 -1
  238. package/dist/client-NleI4Nm-.mjs +0 -434
  239. package/dist/client-NleI4Nm-.mjs.map +0 -1
  240. package/dist/client-tjSMPjeZ.mjs +0 -2
  241. package/dist/client-tjSMPjeZ.mjs.map +0 -1
  242. package/dist/controls-BhxRnPYS.mjs +0 -2
  243. package/dist/controls-BhxRnPYS.mjs.map +0 -1
  244. package/dist/decimal-12NERGYZ.mjs +0 -3
  245. package/dist/decimal-12NERGYZ.mjs.map +0 -1
  246. package/dist/driver-CRaDT4B7.mjs +0 -2
  247. package/dist/driver-options-DxlB1tms.mjs +0 -2
  248. package/dist/driver-options-DxlB1tms.mjs.map +0 -1
  249. package/dist/driver-yCYqzIQg.mjs +0 -2
  250. package/dist/driver-yCYqzIQg.mjs.map +0 -1
  251. package/dist/error-mapping-BWzb-l02.mjs +0 -2
  252. package/dist/error-mapping-BWzb-l02.mjs.map +0 -1
  253. package/dist/execution-context-BPk0YLhd.mjs +0 -2
  254. package/dist/execution-context-BPk0YLhd.mjs.map +0 -1
  255. package/dist/fs-estate-3Bu_K9mk.d.mts +0 -7
  256. package/dist/fs-estate-BcjgY4iY.mjs +0 -2
  257. package/dist/fs-estate-BcjgY4iY.mjs.map +0 -1
  258. package/dist/geo-point-codec-DUTTtlav.mjs +0 -2
  259. package/dist/geo-point-codec-DUTTtlav.mjs.map +0 -1
  260. package/dist/identifiers-By-JRCb5.mjs +0 -2
  261. package/dist/identifiers-By-JRCb5.mjs.map +0 -1
  262. package/dist/key-DKaqPb8w.mjs +0 -2
  263. package/dist/key-DKaqPb8w.mjs.map +0 -1
  264. package/dist/migrations-BWZSBMZh.mjs.map +0 -1
  265. package/dist/mysql-adapter-D9FoHlWE.mjs +0 -2
  266. package/dist/mysql-adapter-D9FoHlWE.mjs.map +0 -1
  267. package/dist/observation-CLp8ylmL.mjs +0 -2
  268. package/dist/observation-CLp8ylmL.mjs.map +0 -1
  269. package/dist/physical-BkelResN.mjs +0 -2
  270. package/dist/pinned-session-Ca7C9yxY.mjs +0 -2
  271. package/dist/pinned-session-Ca7C9yxY.mjs.map +0 -1
  272. package/dist/postgres-adapter-T2Iko-vt.mjs +0 -2
  273. package/dist/postgres-adapter-T2Iko-vt.mjs.map +0 -1
  274. package/dist/registration-preflight-BrA3EWvq.mjs +0 -4
  275. package/dist/registration-preflight-BrA3EWvq.mjs.map +0 -1
  276. package/dist/result-shape-DKTu8yre.mjs +0 -2
  277. package/dist/result-shape-DKTu8yre.mjs.map +0 -1
  278. package/dist/scalar-BTktMqvO.mjs +0 -2
  279. package/dist/schema-BFNcMdO6.mjs +0 -2
  280. package/dist/schema-introspection-DsXPfCst.mjs +0 -6
  281. package/dist/schema-introspection-DsXPfCst.mjs.map +0 -1
  282. package/dist/select-assembly-BgqlrePH.mjs.map +0 -1
  283. package/dist/sqlite-adapter-HqO3GpAK.mjs +0 -2
  284. package/dist/sqlite-adapter-HqO3GpAK.mjs.map +0 -1
  285. package/dist/sqlite-utils-D26BFuJJ.mjs +0 -2
  286. package/dist/sqlite-utils-D26BFuJJ.mjs.map +0 -1
  287. package/dist/transaction-operation-BC7aua5V.mjs.map +0 -1
  288. package/dist/transaction-oskVwmsf.mjs.map +0 -1
  289. package/dist/transactions-gjmrWN5W.mjs +0 -2
  290. package/dist/transactions-gjmrWN5W.mjs.map +0 -1
  291. package/dist/utils-DfztpPvR.mjs.map +0 -1
  292. package/dist/v-B2WwtcRz.mjs +0 -2
  293. package/dist/v-B2WwtcRz.mjs.map +0 -1
  294. package/dist/validation-Du6j0Q38.mjs +0 -2
  295. package/dist/validation-Du6j0Q38.mjs.map +0 -1
  296. package/dist/validation-tgjL_9n8.mjs +0 -2
  297. package/dist/validator-DMlEScV3.mjs +0 -2
  298. package/dist/version-Cr80LFvx.mjs +0 -2
  299. /package/dist/{contract-BHUOUAZ-.d.mts → contract-CIIqgFyb.d.mts} +0 -0
  300. /package/dist/{sql--yhoVvRM.d.mts → sql-BvfwUKIh.d.mts} +0 -0
@@ -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{b as r,t as i}from"./base-AdXAoy6l.mjs";import{f as a,t as o}from"./validation-Dk9Q_-C7.mjs";import{a as s}from"./key-BeoOwGr3.mjs";const c=`viborm.cache`,l=Object.freeze({cache:Object.freeze({schema:Object.freeze({"~standard":Object.freeze({version:1,vendor:`viborm`,validate:e=>Object.freeze({value:officialCacheRuntime().admitMutationCacheOptions(e)})})}),on:`writes`})}),u=new WeakMap,d=new WeakMap,f=new WeakMap;let p;function registerOfficialCacheQuery(e,t,n){p=n,u.set(e,t)}function installOfficialCacheRuntime(e){p=e}function officialCacheRuntime(){if(p===void 0)throw Error(`The official cache runtime is not loaded: import cache() from viborm/cache.`);return p}function getOfficialCacheQueryCapability(e){return t(e)?u.get(e):void 0}function getOfficialCacheChainDefinition(e){return e===void 0?void 0:d.get(e)}function getOfficialCacheChainCapability(e){return e===void 0?void 0:f.get(e)}function registerOfficialCacheChain(e,t){d.set(e,t)}function setOfficialCacheChainCapability(e,t){f.set(e,t)}function bindOfficialCacheChain(e,t){d.get(e)!==void 0&&officialCacheRuntime().bindChain(e,t)}function isCacheManagedExecution(e){return e?.skipSpan===!0}const m=new Set([`findMany`,`findUnique`,`findFirst`,`findUniqueOrThrow`,`findFirstOrThrow`,`count`,`aggregate`,`groupBy`,`exist`]);function isReadOperation(e){return m.has(e)}const h=new Set([...m,`create`,`update`,`delete`,`upsert`,`createMany`,`updateMany`,`deleteMany`]);function isWriteOperation(e){return h.has(e)&&!isReadOperation(e)}function baseOperation(e){return e===`findUniqueOrThrow`?`findUnique`:e===`findFirstOrThrow`?`findFirst`:e}const g={reads:new Set([...h].filter(isReadOperation)),writes:new Set([...h].filter(isWriteOperation)),all:h},_=new Set([...h].filter(e=>e!==`create`&&e!==`createMany`)),v=new Set([`delete`,`deleteMany`]);function placeControls(e){let t=[],{name:n,controls:r,rows:i,deletion:a,data:o}=e,s=a?.removeWhen??{},c=new Set(Object.keys(a?.models??{})),l=new Set([...c,...Object.keys(i?.models??{}),...Object.keys(o?.models??{})]),u=l.size===0?!0:l;for(let[e,i]of Object.entries(r??{})){let r=Object.hasOwn(s,e);t.push({name:e,extension:n,declaration:i,operations:r?v:placementOf(i.on),models:r?c:void 0,required:i.required===!0?u:void 0})}return i!==void 0&&t.push({name:i.control,extension:n,declaration:Object.freeze({oneOf:Object.freeze(rowsModes(i))}),operations:_,fallback:i.default}),t}function placementOf(e){return e===void 0?h:typeof e==`string`?g[e]:new Set(e)}function rowsModes(e){let[t]=Object.values(e.models);return t===void 0?[e.default]:Object.keys(t)}const y=new WeakSet;function snapshotControlValue(e){if(typeof e!=`object`||!e||!s(e))return e;let t;try{t=captureOf(e,new WeakSet)}catch{return e}if(t===`opaque`)return e;if(t===`fixed`)return y.add(e),e;let n;try{n=structuredClone(e)}catch{return e}return freezeCopy(n)&&y.add(n),n}function captureOf(e,t){if(ArrayBuffer.isView(e))return`opaque`;if(t.has(e))return`fixed`;t.add(e);let n=e instanceof Date||!Object.isFrozen(e)?`copy`:`fixed`,r=Array.isArray(e);for(let i of Reflect.ownKeys(e)){if(r&&i===`length`)continue;let a=Object.getOwnPropertyDescriptor(e,i);if(typeof i==`symbol`||!a.enumerable||!(`value`in a))return`opaque`;let o=a.value;if(typeof o!=`object`||!o)continue;let s=captureOf(o,t);if(s===`opaque`)return`opaque`;s===`copy`&&(n=`copy`)}return n}function freezeCopy(e){if(e instanceof Date)return!1;let t=!0;for(let n of Object.values(e))typeof n==`object`&&n&&!freezeCopy(n)&&(t=!1);return Object.freeze(e),t}function isStableControlValue(e){return typeof e!=`object`||!e||y.has(e)}function admitControls(e,t,n,r){if(typeof n!=`object`||!n)return{args:n,controls:void 0};let i;try{i=Reflect.ownKeys(n)}catch(n){throw controlFailure(`The arguments of ${e}.${t} could not be inspected for controls`,e,t,n)}let a=[],o;for(let s of r){let r;i.includes(s.name)&&((o??=new Set).add(s.name),r=readControl(n,s,e,t));let c=r===void 0?s.fallback:admitControl(s,r,e,t),{required:l}=s;if(c!==void 0)a.push([s.name,snapshotControlValue(c)]);else if(l===!0||l?.has(e))throw invalidControl(s,e,t,[`is required`])}return{args:o===void 0?n:withoutControls(n,i,o,e,t),controls:a.length===0?void 0:Object.freeze(Object.fromEntries(a))}}function controlsOwnedBy(e,t){let n=[];for(let r of t)e!==void 0&&Object.hasOwn(e,r)&&n.push([r,e[r]]);return Object.freeze(Object.fromEntries(n))}function readControl(e,t,n,r){try{return Reflect.get(e,t.name)}catch(e){throw controlFailure(`Extension "${t.extension}" control "${t.name}" of ${n}.${r} could not be read`,n,r,e)}}function withoutControls(e,t,n,r,i){let a={};try{for(let r of t){if(n.has(r))continue;let t=Object.getOwnPropertyDescriptor(e,r);t&&Object.defineProperty(a,r,t)}}catch(e){throw controlFailure(`The arguments of ${r}.${i} could not be inspected for controls`,r,i,e)}return a}function admitControl(e,r,i,a){let{declaration:o}=e;if(`oneOf`in o){if(o.oneOf.some(e=>e===r))return r;throw invalidControl(e,i,a,[`must be one of ${o.oneOf.map(e=>JSON.stringify(e)).join(`, `)}`])}let s;try{s=o.schema[`~standard`].validate(r)}catch(t){throw isVibORMFailure(t)?t:validatorFailure(e,i,a,`threw`,t)}let c=`malformed`,l=[],u;try{if(n(s)){let e=`then`in s?s.then:void 0;if(t(e))c=`promise`,Reflect.apply(e,s,[void 0,()=>void 0]);else{let e=s.issues;e===void 0?`value`in s&&(c=`value`,u=s.value):Array.isArray(e)&&(c=`issues`,l=e)}}}catch(t){throw validatorFailure(e,i,a,`returned an unreadable result`,t)}switch(c){case`value`:return u;case`issues`:throw invalidControl(e,i,a,issueMessages(l));case`promise`:throw validatorFailure(e,i,a,`returned a promise`,TypeError(`Control validators must return synchronously`));default:throw validatorFailure(e,i,a,`returned a malformed result`,TypeError(`A Standard Schema result has a value or an issue list`))}}function issueMessages(e){let t=[];try{for(let r of e){let e=n(r)?r.message:void 0;t.push(typeof e==`string`?e:`is invalid`)}}catch{return[`is invalid`]}return t.length===0?[`is invalid`]:t}function isVibORMFailure(e){try{return e instanceof i}catch{return!1}}function invalidControl(e,t,n,r){return new o({kind:`operation`,operation:n,model:t},r.map(t=>({path:e.name,message:`Control "${e.name}" ${t}`})),{meta:{model:t,extension:e.extension}})}function validatorFailure(e,t,n,r,i){return controlFailure(`Extension "${e.extension}" control "${e.name}" validator for ${t}.${n} ${r}`,t,n,i)}function controlFailure(e,t,n,i){return new a(`${e}.`,{cause:r(i),meta:{model:t,operation:n}})}export{l as _,rowsModes as a,registerOfficialCacheQuery as b,isReadOperation as c,bindOfficialCacheChain as d,getOfficialCacheChainCapability as f,isCacheManagedExecution as g,installOfficialCacheRuntime as h,placeControls as i,isWriteOperation as l,getOfficialCacheQueryCapability as m,controlsOwnedBy as n,h as o,getOfficialCacheChainDefinition as p,isStableControlValue as r,baseOperation as s,admitControls as t,c as u,officialCacheRuntime as v,setOfficialCacheChainCapability as x,registerOfficialCacheChain as y};
2
+ //# sourceMappingURL=controls-DXgIn4zh.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"controls-DXgIn4zh.mjs","names":[],"sources":["../src/cache/capability.ts","../src/query-engine/routed-operations.ts","../src/extensions/controls.ts"],"sourcesContent":["// The part of the official cache the core client reads on every operation:\n// whether a chain carries the cache, and a handle on the cache runtime. The\n// runtime itself (cache driver, cache flow, result codecs) is installed by\n// `cache()` from `viborm/cache`, so an application that never creates the\n// extension does not load it. A chain can only carry the capability after\n// `cache()` ran, which is what makes `officialCacheRuntime()` total wherever\n// the core asks for it.\n\nimport type { ResolvedExtensionChain } from \"@extensions/chain\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type {\n GenericQueryHandler,\n OfficialGenericQueryHandler,\n} from \"@extensions/query\";\nimport { isFunction } from \"@validation/value-guards\";\nimport type { CacheDriver, WaitUntilFn } from \"./driver\";\nimport type { OfficialCacheRuntime } from \"./runtime\";\nimport type { CacheInvalidationOptions } from \"./schema\";\n\nexport const OFFICIAL_CACHE_NAME = \"viborm.cache\";\n\n/** The exact official query contribution. It is recognized by identity. */\nexport type OfficialCacheQueryContribution = OfficialGenericQueryHandler & {\n bind(thisArg: unknown): GenericQueryHandler;\n};\n\n/**\n * A mutation's `cache` argument is the cache's declared control (ruling 7):\n * core removes and admits it before request handlers run, through the cache's\n * own parser, so a malformed value is still a `CacheConfigurationError`.\n */\nexport type OfficialCacheControls = {\n readonly cache: {\n readonly schema: StandardSchemaV1<CacheInvalidationOptions>;\n readonly on: \"writes\";\n };\n};\n\n/** The official value accepted by the dedicated `$extends` overload. */\nexport type OfficialCacheExtension = {\n readonly name: typeof OFFICIAL_CACHE_NAME;\n readonly query: OfficialCacheQueryContribution;\n readonly controls: OfficialCacheControls;\n};\n\n/**\n * The cache's one declaration. The chain places it for any definition carrying\n * the cache's query, whatever `controls` that definition spells: the query is\n * the cache's identity, so its control cannot be forged or left out. It lives\n * here, in the part core always loads, and admits through the runtime: a chain\n * carries the cache only after `cache()` installed that runtime.\n */\nexport const officialCacheControls: OfficialCacheControls = Object.freeze({\n cache: Object.freeze({\n schema: Object.freeze({\n \"~standard\": Object.freeze({\n version: 1,\n vendor: \"viborm\",\n validate: (value: unknown) =>\n Object.freeze({\n value: officialCacheRuntime().admitMutationCacheOptions(value),\n }),\n }),\n }),\n on: \"writes\",\n }),\n});\n\n/**\n * What `cache()` knows before it meets a client: no scope, because the scope\n * partitions on facts (dialect, SQL namespace) that only a concrete driver\n * carries. One definition may be appended to several clients.\n */\nexport interface OfficialCacheDefinitionCapability {\n readonly driver: CacheDriver;\n readonly version: string | number | undefined;\n readonly waitUntil: WaitUntilFn | undefined;\n}\n\n/** The definition once bound to one client's driver, gaining its scope. */\nexport interface OfficialCacheCapability\n extends OfficialCacheDefinitionCapability {\n readonly scope: object;\n}\n\n/**\n * The two driver facts the scope derives from. Structural, so the cache holds\n * no driver reference and no import edge back into `src/drivers`.\n */\nexport interface OfficialCacheBindTarget {\n readonly dialect: string;\n readonly adapter: { readonly namespace?: string | undefined };\n}\n\nconst capabilitiesByQuery = new WeakMap<\n CallableFunction,\n OfficialCacheDefinitionCapability\n>();\nconst definitionsByChain = new WeakMap<\n ResolvedExtensionChain,\n OfficialCacheDefinitionCapability\n>();\nconst capabilitiesByChain = new WeakMap<\n ResolvedExtensionChain,\n OfficialCacheCapability\n>();\nlet runtime: OfficialCacheRuntime | undefined;\n\n/** Recognize `query` as the official cache's contribution. `cache()` only. */\nexport function registerOfficialCacheQuery(\n query: CallableFunction,\n capability: OfficialCacheDefinitionCapability,\n installed: OfficialCacheRuntime\n): void {\n runtime = installed;\n capabilitiesByQuery.set(query, capability);\n}\n\n/** Make the cache runtime reachable; `viborm/cache` does this as it loads. */\nexport function installOfficialCacheRuntime(\n installed: OfficialCacheRuntime\n): void {\n runtime = installed;\n}\n\n/** The cache runtime; reachable only where a chain carries the cache. */\nexport function officialCacheRuntime(): OfficialCacheRuntime {\n if (runtime === undefined)\n throw new Error(\n \"The official cache runtime is not loaded: import cache() from viborm/cache.\"\n );\n return runtime;\n}\n\nexport function getOfficialCacheQueryCapability(\n query: unknown\n): OfficialCacheDefinitionCapability | undefined {\n return isFunction(query) ? capabilitiesByQuery.get(query) : undefined;\n}\n\n/**\n * The definition carried by this chain, scope or no scope. Generic\n * extension-chain code sees only this: admission, duplicate refusal, and\n * propagation are all decisions about the DEFINITION, and none of them may\n * depend on whether a client has bound it yet.\n */\nexport function getOfficialCacheChainDefinition(\n chain: ResolvedExtensionChain | undefined\n): OfficialCacheDefinitionCapability | undefined {\n return chain === undefined ? undefined : definitionsByChain.get(chain);\n}\n\n/** The bound capability: present only after a client composition root bound it. */\nexport function getOfficialCacheChainCapability(\n chain: ResolvedExtensionChain | undefined\n): OfficialCacheCapability | undefined {\n return chain === undefined ? undefined : capabilitiesByChain.get(chain);\n}\n\nexport function registerOfficialCacheChain(\n chain: ResolvedExtensionChain,\n capability: OfficialCacheDefinitionCapability\n): void {\n definitionsByChain.set(chain, capability);\n}\n\n/** Publish the capability the runtime bound for one chain. */\nexport function setOfficialCacheChainCapability(\n chain: ResolvedExtensionChain,\n capability: OfficialCacheCapability\n): void {\n capabilitiesByChain.set(chain, capability);\n}\n\n/**\n * Bind one resolved chain's cache definition to the concrete client driver,\n * deriving the scope that partitions its storage.\n *\n * Called by the client composition root — the one place that holds both the\n * resolved chain and the driver — and only for a chain that carries the\n * official cache, so an ordinary extension costs nothing here.\n */\nexport function bindOfficialCacheChain(\n chain: ResolvedExtensionChain,\n target: OfficialCacheBindTarget\n): void {\n if (definitionsByChain.get(chain) === undefined) return;\n officialCacheRuntime().bindChain(chain, target);\n}\n\n/** Whether an operation runs under the official cache's managed execution. */\nexport function isCacheManagedExecution(\n options: { readonly skipSpan?: boolean } | undefined\n): boolean {\n return options?.skipSpan === true;\n}\n","import type { Operations } from \"@client/types\";\n\n/**\n * The client operation vocabulary, retained at the C-01 cutover.\n *\n * These four names are the only part of the deleted shipped routing module that\n * owners OUTSIDE the engine consume: the client (`isWriteOperation`), the\n * official cache (`isWriteOperation`), the extension surface\n * (`ROUTED_OPERATIONS`) and the query-interception seam (`isReadOperation`).\n * The text below is the deleted `write-engine/routing.ts` definitions verbatim,\n * so no operation changes classification at the cutover.\n */\n\nconst READ_OPERATIONS: ReadonlySet<string> = new Set([\n \"findMany\",\n \"findUnique\",\n \"findFirst\",\n \"findUniqueOrThrow\",\n \"findFirstOrThrow\",\n \"count\",\n \"aggregate\",\n \"groupBy\",\n \"exist\",\n]);\n\n/** Whether a public operation routes through the engine's read owner. */\nexport function isReadOperation(operation: string): boolean {\n return READ_OPERATIONS.has(operation);\n}\n\n/**\n * The operation names the engine owns a construction path for. Every client\n * operation family is here; a name outside it (there is none on the client path)\n * resolves to `undefined`.\n */\nexport const ROUTED_OPERATIONS: ReadonlySet<string> = new Set([\n ...READ_OPERATIONS,\n \"create\",\n \"update\",\n \"delete\",\n \"upsert\",\n \"createMany\",\n \"updateMany\",\n \"deleteMany\",\n]);\n\n/** Whether a public operation routes through the engine's write owner. */\nexport function isWriteOperation(operation: string): boolean {\n return ROUTED_OPERATIONS.has(operation) && !isReadOperation(operation);\n}\n\n/**\n * The verb an `…OrThrow` operation shares its whole envelope with: its schema,\n * its admission and its result. Every other verb is its own base.\n */\nexport function baseOperation(\n operation: Operations\n): Exclude<Operations, \"findUniqueOrThrow\" | \"findFirstOrThrow\"> {\n if (operation === \"findUniqueOrThrow\") return \"findUnique\";\n if (operation === \"findFirstOrThrow\") return \"findFirst\";\n return operation;\n}\n","import { isCanonicalKeyData } from \"@cache/key\";\nimport type {\n CacheableOperations,\n MutationOperations,\n Operations,\n} from \"@client/types\";\nimport { QueryError, ValidationError, VibORMError } from \"@errors\";\nimport {\n isReadOperation,\n isWriteOperation,\n ROUTED_OPERATIONS,\n} from \"@query-engine/routed-operations\";\nimport type { Operation } from \"@query-engine/types\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { isFunction, isRecord } from \"@validation/value-guards\";\nimport { errorCause } from \"../errors/diagnostic-safety\";\nimport type { ControlLiteral, RuntimeExtensionDefinition } from \"./definition\";\n\n// =============================================================================\n// DEFINITION MEMBERS: plain data, checked by TypeScript only\n// =============================================================================\n\n/** The operations a declared control is accepted on. */\nexport type ControlPlacement =\n | \"reads\"\n | \"writes\"\n | \"all\"\n | readonly Operations[];\n\n/**\n * One argument an extension declares. Its values are a closed list or a\n * Standard Schema; `on` names the operations that accept it (every operation\n * when absent). With `required`, a call on one of those operations that does\n * not pass it is refused, on the models the extension names in `rows`,\n * `data` or `deletion` only; an extension that names no model asks for it on\n * every model. A value held in a variable keeps its literal type only with\n * `as const`, as a held enum clause does.\n */\nexport type ControlDeclaration = (\n | { readonly oneOf: readonly (string | number | boolean)[] }\n | { readonly schema: StandardSchemaV1 }\n) & { readonly on?: ControlPlacement; readonly required?: boolean };\n\nexport type ControlsContribution = {\n readonly [name: string]: ControlDeclaration;\n};\n\n/** Constant scalar `where` or `data` fields of one model. */\ntype ScalarFields = { readonly [field: string]: unknown };\n\n/**\n * Which rows an operation sees. `control` names the call argument that picks\n * a mode; every model entry declares the same mode names, `default` among\n * them. `root` filters the call's own candidates, `related` rows reached\n * through a relation. Where a filter takes a value, `{ control: \"<name>\" }`\n * takes the value the call passed for that control; a call that passed none\n * drops that filter.\n */\nexport type RowsContribution = {\n readonly control: string;\n readonly default: string;\n readonly models: {\n readonly [model: string]: {\n readonly [mode: string]: {\n readonly root?: ScalarFields;\n readonly related?: ScalarFields;\n };\n };\n };\n};\n\n/**\n * What a delete does on the models named here: an update that stamps `at`\n * with the call's time and writes `assign`, unless the call's controls match\n * `removeWhen`.\n */\nexport type DeletionContribution = {\n readonly removeWhen?: {\n readonly [control: string]: string | number | boolean;\n };\n readonly models: {\n readonly [model: string]: {\n readonly at?: string;\n readonly assign?: ScalarFields;\n };\n };\n};\n\n/**\n * Fields an extension writes on the models named here: `create` on every\n * create of the model, `update` on every update of it, a soft delete's\n * included. A value is a constant, `{ control: \"<name>\" }` for the value the\n * call passed for that control (a call that passed none writes nothing\n * there), or, on `update`, one of the field's update operators\n * (`{ increment: 1 }`). A field is written only where the caller left it\n * out: a call that writes it itself, or writes the relation whose foreign key\n * holds it, keeps its own value there. A create may leave out such a field\n * even where the schema requires it: the call's data is checked with it\n * counted as given. When the model names here are known to the types\n * (written out, or kept by a `const` type parameter, not a plain\n * `string[]`), the extended client's types agree, nested creates included:\n * the field is optional on a create. When two extensions name a field, the\n * later one writes it, and a value the caller writes wins over both.\n */\nexport type DataContribution = {\n readonly models: {\n readonly [model: string]: {\n readonly create?: ScalarFields;\n readonly update?: ScalarFields;\n };\n };\n};\n\n// =============================================================================\n// CONTROL STATE: what a chain's controls add to each (model, operation)\n// =============================================================================\n\n/** Operations that select candidates: where a rows control is accepted. */\ntype CandidateOperations = Exclude<Operations, \"create\" | \"createMany\">;\n\n/** One declared control as the delegates see it. */\nexport interface PlacedControl<\n Value = unknown,\n Models = PropertyKey,\n Placed = Operations,\n> {\n readonly value: Value;\n readonly models: Models;\n readonly operations: Placed;\n}\n\nexport type NoControls = Record<never, never>;\n\ntype ControlValue<Declaration> = Declaration extends {\n readonly oneOf: readonly (infer Value)[];\n}\n ? Value\n : Declaration extends { readonly schema: StandardSchemaV1<infer Input> }\n ? Input\n : never;\n\ntype PlacementOperations<On> = On extends \"reads\"\n ? CacheableOperations\n : On extends \"writes\"\n ? MutationOperations\n : On extends readonly (infer Operation)[]\n ? Operation\n : Operations;\n\n/**\n * `deletion` places the control `removeWhen` names: on the deletes of the\n * models it manages, whatever the declaration's `on` says.\n */\ntype PlaceControl<Name, Declaration, Deletion> = Deletion extends {\n readonly removeWhen: infer RemoveWhen;\n readonly models: infer Managed;\n}\n ? Name extends keyof RemoveWhen\n ? PlacedControl<\n ControlValue<Declaration>,\n keyof Managed,\n \"delete\" | \"deleteMany\"\n >\n : PlaceFreeControl<Declaration>\n : PlaceFreeControl<Declaration>;\n\ntype PlaceFreeControl<Declaration> = PlacedControl<\n ControlValue<Declaration>,\n PropertyKey,\n PlacementOperations<\n Declaration extends { readonly on: infer On } ? On : \"all\"\n >\n>;\n\ntype DeclaredControls<Definition> = Definition extends {\n readonly controls: infer Controls extends ControlsContribution;\n}\n ? {\n readonly [Name in keyof Controls]: PlaceControl<\n Name,\n Controls[Name],\n Definition extends { readonly deletion: infer Deletion }\n ? Deletion\n : unknown\n >;\n }\n : NoControls;\n\n/** Every model entry declares the same mode names: those are the values. */\ntype RowsModes<Rows extends RowsContribution> =\n | Rows[\"default\"]\n | {\n [Model in keyof Rows[\"models\"]]: keyof Rows[\"models\"][Model];\n }[keyof Rows[\"models\"]];\n\n/** The rows control: every candidate-selecting operation of every model. */\ntype RowsControl<Definition> = Definition extends {\n readonly rows: infer Rows extends RowsContribution;\n}\n ? {\n readonly [Name in Rows[\"control\"]]: PlacedControl<\n RowsModes<Rows>,\n PropertyKey,\n CandidateOperations\n >;\n }\n : NoControls;\n\n/**\n * The models one definition's `rows` can hide from a relation read: its\n * entries' keys. A to-one relation that targets one of them reads `null` when\n * its target is hidden, so the result types widen it (`result-types.ts`).\n */\nexport type RowsModels<Definition> = Definition extends {\n readonly rows: infer Rows extends RowsContribution;\n}\n ? Extract<keyof Rows[\"models\"], string>\n : never;\n\n/** The controls one definition places, keyed by control name. */\nexport type DefinitionControls<Definition> = DeclaredControls<Definition> &\n RowsControl<Definition>;\n\n/** The optional control arguments one (model, operation) accepts. */\nexport type OperationControls<Controls, ModelName, Operation> = {\n readonly [Name in keyof Controls as Controls[Name] extends PlacedControl<\n unknown,\n infer Models,\n infer Placed\n >\n ? ModelName extends Models\n ? Operation extends Placed\n ? Name\n : never\n : never\n : never]?: Controls[Name] extends PlacedControl<infer Value>\n ? Value\n : never;\n};\n\n// =============================================================================\n// DATA STATE: the fields a chain's `data` writes, per model\n// =============================================================================\n\n/**\n * The fields one `data` entry writes on its models' creates: there they may\n * be left out even where the schema requires them. An update's fields need\n * nothing, as every field of an update is optional already.\n */\nexport interface StampedFields<Models = PropertyKey, Fields = PropertyKey> {\n readonly models: Models;\n readonly fields: Fields;\n}\n\ntype CreateStamps<Model, Entry> = \"create\" extends keyof Entry\n ? Entry extends { readonly create?: infer Fields }\n ? StampedFields<Model, keyof NonNullable<Fields>>\n : never\n : never;\n\n/**\n * What one definition's `data` writes on creates: one member per model. A\n * definition whose model names are lost (`{ [model: string]: ... }`, as a\n * recipe called with a plain `string[]` builds) writes nothing the types can\n * name: its required fields stay required in the payloads.\n */\nexport type DefinitionData<Definition> = Definition extends {\n readonly data: { readonly models: infer Models };\n}\n ? string extends keyof Models\n ? never\n : {\n [Model in keyof Models]: CreateStamps<Model, Models[Model]>;\n }[keyof Models]\n : never;\n\n/** The fields a chain writes on every create of one model. */\nexport type StampedFieldNames<Data, ModelName> =\n Data extends StampedFields<infer Models, infer Fields extends PropertyKey>\n ? ModelName extends Models\n ? Fields\n : never\n : never;\n\n// =============================================================================\n// PLACEMENT: where each declared control is accepted\n// =============================================================================\n\n/** Where a control goes when its declaration names a placement. */\nconst PLACEMENTS: Readonly<\n Record<\"reads\" | \"writes\" | \"all\", ReadonlySet<string>>\n> = {\n reads: new Set([...ROUTED_OPERATIONS].filter(isReadOperation)),\n writes: new Set([...ROUTED_OPERATIONS].filter(isWriteOperation)),\n all: ROUTED_OPERATIONS,\n};\n\n/** Every operation that selects candidates: where a `rows` control goes. */\nconst CANDIDATE_OPERATIONS: ReadonlySet<string> = new Set(\n [...ROUTED_OPERATIONS].filter(\n (operation) => operation !== \"create\" && operation !== \"createMany\"\n )\n);\n\n/** Where a `deletion.removeWhen` control goes, on the models it manages. */\nconst DELETE_OPERATIONS: ReadonlySet<string> = new Set([\n \"delete\",\n \"deleteMany\",\n]);\n\n/** One control of a chain: its owner, its placement and how a value is admitted. */\nexport interface ResolvedControl {\n readonly name: string;\n readonly extension: string;\n readonly declaration: ControlDeclaration;\n /** The operations that accept it. */\n readonly operations: ReadonlySet<string>;\n /** The models that accept it; every model when absent. */\n readonly models?: ReadonlySet<string>;\n /**\n * Where a call that does not pass it is refused: on every model that\n * accepts it (`true`), on these models only, or nowhere when absent.\n */\n readonly required?: true | ReadonlySet<string>;\n /** What an absent argument admits: the `rows` control's default mode. */\n readonly fallback?: ControlLiteral;\n}\n\n/**\n * Give every control of one definition its placement. A control\n * `deletion.removeWhen` names goes on the deletes of the models `deletion`\n * manages; the `rows` control on every candidate-selecting operation of every\n * model, its values the mode names; every other control where its own `on`\n * says (every operation without one), on every model. A `required` control\n * is asked for only on the models the definition names in `rows`, `data` or\n * `deletion`, and on every model when it names none.\n */\nexport function placeControls(\n definition: RuntimeExtensionDefinition\n): readonly ResolvedControl[] {\n const placed: ResolvedControl[] = [];\n const { name: extension, controls, rows, deletion, data } = definition;\n const removeWhen = deletion?.removeWhen ?? {};\n const managed = new Set(Object.keys(deletion?.models ?? {}));\n const named = new Set([\n ...managed,\n ...Object.keys(rows?.models ?? {}),\n ...Object.keys(data?.models ?? {}),\n ]);\n const requiredOn = named.size === 0 ? true : named;\n for (const [name, declaration] of Object.entries(controls ?? {})) {\n const removes = Object.hasOwn(removeWhen, name);\n placed.push({\n name,\n extension,\n declaration,\n operations: removes ? DELETE_OPERATIONS : placementOf(declaration.on),\n models: removes ? managed : undefined,\n required: declaration.required === true ? requiredOn : undefined,\n });\n }\n if (rows !== undefined) {\n placed.push({\n name: rows.control,\n extension,\n declaration: Object.freeze({ oneOf: Object.freeze(rowsModes(rows)) }),\n operations: CANDIDATE_OPERATIONS,\n fallback: rows.default,\n });\n }\n return placed;\n}\n\nfunction placementOf(on: ControlDeclaration[\"on\"]): ReadonlySet<string> {\n if (on === undefined) return ROUTED_OPERATIONS;\n return typeof on === \"string\" ? PLACEMENTS[on] : new Set<string>(on);\n}\n\n/**\n * The `rows` control's values: the mode names, which every model entry\n * declares alike, or the default alone when no model is named.\n */\nexport function rowsModes(rows: RowsContribution): readonly string[] {\n const [modes] = Object.values(rows.models);\n return modes === undefined ? [rows.default] : Object.keys(modes);\n}\n\n// =============================================================================\n// ADMISSION: one call's controls, removed and validated once\n// =============================================================================\n\n/**\n * The controls one call admitted, by name. A `rows` control is resolved to its\n * mode, so an absent one reads as its default; an absent plain control is not\n * here.\n */\nexport type AdmittedControls = Readonly<Record<string, unknown>>;\n\nexport interface ControlAdmission {\n /** The arguments without their controls; the input itself when none was given. */\n readonly args: Record<string, unknown>;\n /** `undefined` when the call admitted no value. */\n readonly controls: AdmittedControls | undefined;\n}\n\n/** The admitted values {@link snapshotControlValue} copied: the stable ones. */\nconst snapshots = new WeakSet<object>();\n\n/**\n * An admitted value as the call holds it from here on. Plain data is copied\n * once and frozen, so every reader of the call's controls (the rows its\n * filters bind, the key its cached read is stored under, its handlers) reads\n * the same value whatever the caller later does to its own. A value already\n * fixed all the way down is kept by identity. A value a copy would change\n * (a non-enumerable or symbol property, which `structuredClone` drops; a\n * getter, whose answer only calling it shows), one that resists inspection,\n * one with no canonical spelling, or one that cannot be copied (a Proxy), is\n * kept as given, as are bytes (an indexed write survives `freeze`); a copy\n * that still holds a `Date` is kept but not stable (`setTime` survives it). In\n * those cases the call binds the value for itself alone and its read is not\n * cached.\n */\nexport function snapshotControlValue(value: unknown): unknown {\n if (typeof value !== \"object\" || value === null) return value;\n if (!isCanonicalKeyData(value)) return value;\n let capture: ReturnType<typeof captureOf>;\n try {\n capture = captureOf(value, new WeakSet());\n } catch {\n // A Proxy may answer the canonical check and refuse a later reflection.\n return value;\n }\n if (capture === \"opaque\") return value;\n if (capture === \"fixed\") {\n snapshots.add(value);\n return value;\n }\n let copy: object;\n try {\n copy = structuredClone(value);\n } catch {\n return value;\n }\n if (freezeCopy(copy)) snapshots.add(copy);\n return copy;\n}\n\n/**\n * How an admitted value can be held: `fixed` when nothing reachable from it\n * can change (frozen own data properties only, no `Date`), `copy` when a\n * copy reproduces it (enumerable string-keyed data properties), `opaque`\n * when a copy might not (a non-enumerable or symbol property, or a getter,\n * never called here) or would not fix it (bytes).\n */\nfunction captureOf(\n value: object,\n seen: WeakSet<object>\n): \"fixed\" | \"copy\" | \"opaque\" {\n // Bytes are never stable (an indexed write survives `freeze`), and their\n // own properties are one per byte: kept as given, unread.\n if (ArrayBuffer.isView(value)) return \"opaque\";\n if (seen.has(value)) return \"fixed\";\n seen.add(value);\n let capture: \"fixed\" | \"copy\" =\n value instanceof Date || !Object.isFrozen(value) ? \"copy\" : \"fixed\";\n const array = Array.isArray(value);\n for (const key of Reflect.ownKeys(value)) {\n if (array && key === \"length\") continue;\n const descriptor = Object.getOwnPropertyDescriptor(value, key)!;\n if (\n typeof key === \"symbol\" ||\n !descriptor.enumerable ||\n !(\"value\" in descriptor)\n )\n return \"opaque\";\n const entry: unknown = descriptor.value;\n if (typeof entry !== \"object\" || entry === null) continue;\n const inner = captureOf(entry, seen);\n if (inner === \"opaque\") return \"opaque\";\n if (inner === \"copy\") capture = \"copy\";\n }\n return capture;\n}\n\n/** Freeze a private copy; answer whether nothing in it can still change. */\nfunction freezeCopy(value: object): boolean {\n if (value instanceof Date) return false;\n let fixed = true;\n for (const entry of Object.values(value))\n if (typeof entry === \"object\" && entry !== null && !freezeCopy(entry))\n fixed = false;\n Object.freeze(value);\n return fixed;\n}\n\n/**\n * Whether a control value is the one admission fixed: a primitive, or plain\n * data {@link snapshotControlValue} copied. Only such a value may key anything that\n * outlives the call (a bound-facts memo, a cache entry).\n */\nexport function isStableControlValue(value: unknown): boolean {\n return typeof value !== \"object\" || value === null || snapshots.has(value);\n}\n\n/**\n * Remove every control placed on this operation from its arguments and admit\n * each once, before any request handler runs. A key naming a control placed\n * elsewhere stays in the arguments, where core validation refuses it as an\n * unknown key. A control the call did not pass is refused here on the models\n * its placement requires it on.\n */\nexport function admitControls(\n model: string,\n operation: Operation,\n input: Record<string, unknown>,\n placed: readonly ResolvedControl[]\n): ControlAdmission {\n // Arguments that are not an object hold no control: core validation refuses\n // them as it does on a client without controls.\n if (typeof input !== \"object\" || input === null) {\n return { args: input, controls: undefined };\n }\n let keys: PropertyKey[];\n try {\n keys = Reflect.ownKeys(input);\n } catch (cause) {\n throw controlFailure(\n `The arguments of ${model}.${operation} could not be inspected for controls`,\n model,\n operation,\n cause\n );\n }\n const admitted: [string, unknown][] = [];\n let given: Set<PropertyKey> | undefined;\n for (const control of placed) {\n let raw: unknown;\n if (keys.includes(control.name)) {\n (given ??= new Set()).add(control.name);\n raw = readControl(input, control, model, operation);\n }\n const value =\n raw === undefined\n ? control.fallback\n : admitControl(control, raw, model, operation);\n const { required } = control;\n if (value !== undefined)\n admitted.push([control.name, snapshotControlValue(value)]);\n else if (required === true || required?.has(model)) {\n throw invalidControl(control, model, operation, [\"is required\"]);\n }\n }\n return {\n args:\n given === undefined\n ? input\n : withoutControls(input, keys, given, model, operation),\n controls:\n admitted.length === 0\n ? undefined\n : Object.freeze(Object.fromEntries(admitted)),\n };\n}\n\n/** One extension's own admitted controls, as its handlers see them. */\nexport function controlsOwnedBy(\n admitted: AdmittedControls | undefined,\n names: readonly string[]\n): AdmittedControls {\n const owned: [string, unknown][] = [];\n for (const name of names) {\n if (admitted !== undefined && Object.hasOwn(admitted, name)) {\n owned.push([name, admitted[name]]);\n }\n }\n return Object.freeze(Object.fromEntries(owned));\n}\n\nfunction readControl(\n input: Record<string, unknown>,\n control: ResolvedControl,\n model: string,\n operation: Operation\n): unknown {\n try {\n return Reflect.get(input, control.name);\n } catch (cause) {\n throw controlFailure(\n `Extension \"${control.extension}\" control \"${control.name}\" of ${model}.${operation} could not be read`,\n model,\n operation,\n cause\n );\n }\n}\n\n/** The caller's arguments minus the controls, every other descriptor kept. */\nfunction withoutControls(\n input: Record<string, unknown>,\n keys: readonly PropertyKey[],\n controls: ReadonlySet<PropertyKey>,\n model: string,\n operation: Operation\n): Record<string, unknown> {\n const args: Record<string, unknown> = {};\n try {\n for (const key of keys) {\n if (controls.has(key)) continue;\n const descriptor = Object.getOwnPropertyDescriptor(input, key);\n if (descriptor) Object.defineProperty(args, key, descriptor);\n }\n } catch (cause) {\n throw controlFailure(\n `The arguments of ${model}.${operation} could not be inspected for controls`,\n model,\n operation,\n cause\n );\n }\n return args;\n}\n\nfunction admitControl(\n control: ResolvedControl,\n value: unknown,\n model: string,\n operation: Operation\n): unknown {\n const { declaration } = control;\n if (\"oneOf\" in declaration) {\n if (declaration.oneOf.some((allowed) => allowed === value)) return value;\n throw invalidControl(control, model, operation, [\n `must be one of ${declaration.oneOf.map((allowed) => JSON.stringify(allowed)).join(\", \")}`,\n ]);\n }\n let result: unknown;\n try {\n result = declaration.schema[\"~standard\"].validate(value);\n } catch (cause) {\n // A validator may own its typed failure; anything else is a failure of\n // extension code, as a throwing request transform is.\n if (isVibORMFailure(cause)) throw cause;\n throw validatorFailure(control, model, operation, \"threw\", cause);\n }\n let shape: \"promise\" | \"malformed\" | \"issues\" | \"value\" = \"malformed\";\n let issues: readonly unknown[] = [];\n let admitted: unknown;\n try {\n if (isRecord(result)) {\n const then = \"then\" in result ? result.then : undefined;\n if (isFunction(then)) {\n shape = \"promise\";\n // The refused promise is still live; without a handler its rejection\n // would surface as an unhandled rejection (D-37).\n Reflect.apply(then, result, [undefined, () => undefined]);\n } else {\n const listed = result.issues;\n if (listed !== undefined) {\n if (Array.isArray(listed)) {\n shape = \"issues\";\n issues = listed;\n }\n } else if (\"value\" in result) {\n shape = \"value\";\n admitted = result.value;\n }\n }\n }\n } catch (cause) {\n throw validatorFailure(\n control,\n model,\n operation,\n \"returned an unreadable result\",\n cause\n );\n }\n switch (shape) {\n case \"value\":\n return admitted;\n case \"issues\":\n throw invalidControl(control, model, operation, issueMessages(issues));\n case \"promise\":\n throw validatorFailure(\n control,\n model,\n operation,\n \"returned a promise\",\n new TypeError(\"Control validators must return synchronously\")\n );\n default:\n throw validatorFailure(\n control,\n model,\n operation,\n \"returned a malformed result\",\n new TypeError(\"A Standard Schema result has a value or an issue list\")\n );\n }\n}\n\n/** Each issue's message; an issue that cannot be read still refuses. */\nfunction issueMessages(issues: readonly unknown[]): string[] {\n const messages: string[] = [];\n try {\n for (const issue of issues) {\n const message = isRecord(issue) ? issue.message : undefined;\n messages.push(typeof message === \"string\" ? message : \"is invalid\");\n }\n } catch {\n return [\"is invalid\"];\n }\n return messages.length === 0 ? [\"is invalid\"] : messages;\n}\n\n/** Contained: `instanceof` on a hostile thrown proxy is itself a throw site. */\nfunction isVibORMFailure(value: unknown): value is VibORMError {\n try {\n return value instanceof VibORMError;\n } catch {\n return false;\n }\n}\n\nfunction invalidControl(\n control: ResolvedControl,\n model: string,\n operation: Operation,\n messages: readonly string[]\n): ValidationError {\n return new ValidationError(\n { kind: \"operation\", operation, model },\n messages.map((message) => ({\n path: control.name,\n message: `Control \"${control.name}\" ${message}`,\n })),\n { meta: { model, extension: control.extension } }\n );\n}\n\nfunction validatorFailure(\n control: ResolvedControl,\n model: string,\n operation: Operation,\n failure: string,\n cause: unknown\n): QueryError {\n return controlFailure(\n `Extension \"${control.extension}\" control \"${control.name}\" validator for ${model}.${operation} ${failure}`,\n model,\n operation,\n cause\n );\n}\n\nfunction controlFailure(\n message: string,\n model: string,\n operation: Operation,\n cause: unknown\n): QueryError {\n return new QueryError(`${message}.`, {\n cause: errorCause(cause),\n meta: { model, operation },\n });\n}\n"],"mappings":"2OAmBA,MAAa,EAAsB,eAiCtB,EAA+C,OAAO,OAAO,CACxE,MAAO,OAAO,OAAO,CACnB,OAAQ,OAAO,OAAO,CACpB,YAAa,OAAO,OAAO,CACzB,QAAS,EACT,OAAQ,SACR,SAAW,GACT,OAAO,OAAO,CACZ,MAAO,sBAAsB,CAAC,0BAA0B,EAAM,CAC/D,CAAC,CACL,CAAC,CACH,CAAC,CACF,GAAI,SACL,CAAC,CACH,CAAC,CA4BI,EAAsB,IAAI,QAI1B,EAAqB,IAAI,QAIzB,EAAsB,IAAI,QAIhC,IAAI,EAGJ,SAAgB,2BACd,EACA,EACA,EACM,CACN,EAAU,EACV,EAAoB,IAAI,EAAO,EAAW,CAI5C,SAAgB,4BACd,EACM,CACN,EAAU,EAIZ,SAAgB,sBAA6C,CAC3D,GAAI,IAAY,IAAA,GACd,MAAU,MACR,8EACD,CACH,OAAO,EAGT,SAAgB,gCACd,EAC+C,CAC/C,OAAO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ht as TransactionOptionSupport, It as VibORMClient, L as LinkedClientConfig, On as QueryResult, Tn as CommittedBatchNotification, f as DriverResultParser, jt as DriverConfig, s as DatabaseAdapter, u as Driver, wn as BatchQuery } from "./index-T0YKKw66.mjs";
1
+ import { A as Schema, B as LinkedClientConfig, Dn as TransactionOptionSupport, Mn as QueryResult, On as BatchQuery, Pt as DriverConfig, Rt as NoExtraDriverConfigKeys, h as DriverResultParser, jn as QueryExecutionContext, kn as CommittedBatchNotification, s as DatabaseAdapter, u as Driver, zt as VibORMClient } from "./index-C_XLSTy2.mjs";
2
2
  import { D1Database, D1DatabaseSession } from "@cloudflare/workers-types";
3
3
 
4
4
  //#region src/drivers/d1/index.d.ts
package/dist/d1.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{f as t}from"./validation-Du6j0Q38.mjs";import{i as n,o as r}from"./bind-parameter-capacity-DzMcIB95.mjs";import{c as i}from"./transactions-gjmrWN5W.mjs";import{a,n as o,r as s}from"./client-tjSMPjeZ.mjs";import{t as c}from"./driver-yCYqzIQg.mjs";import{a as l,n as u,s as d}from"./sqlite-utils-D26BFuJJ.mjs";import{t as f}from"./sql-statement-tokens-CykxFmOJ.mjs";import{t as p}from"./sqlite-adapter-HqO3GpAK.mjs";const m=new Set([`EXPLAIN`,`SELECT`,`VALUES`]),h=new Set([`DELETE`,`INSERT`,`REPLACE`,`UPDATE`]),g=new Set([`ALTER`,`ANALYZE`,`ATTACH`,`BEGIN`,`COMMIT`,`CREATE`,`DETACH`,`DROP`,`END`,`REINDEX`,`RELEASE`,`ROLLBACK`,`SAVEPOINT`,`VACUUM`]),_=new Set([`CASE_SENSITIVE_LIKE`,`DEFER_FOREIGN_KEYS`,`FOREIGN_KEYS`,`IGNORE_CHECK_CONSTRAINTS`,`LEGACY_ALTER_TABLE`,`RECURSIVE_TRIGGERS`,`REVERSE_UNORDERED_SELECTS`]),v=new Set([`OPTIMIZE`]),y=new Set([...m,...h]);function classifySQLiteStatementResult(e){let t=f(e);if(!t)return`unknown`;let n=topLevelCommand(t),r=n?.value;return r?m.has(r)?`rows`:h.has(r)?t.slice(n.index+1).some(e=>e.kind===`word`&&e.value===`RETURNING`)?`rows`:`no-rows`:r===`PRAGMA`?classifyPragma(t):g.has(r)?`no-rows`:`unknown`:`unknown`}function isSQLiteInsertStatement(e){let t=topLevelCommand(f(e))?.value;return t===`INSERT`||t===`REPLACE`}function topLevelCommand(e){let t=e?.[0];if(!t||t.kind!==`word`)return;if(t.value!==`WITH`)return{index:0,value:t.value};let n=e.findIndex((e,t)=>t>0&&e.kind===`word`&&y.has(e.value)),r=e[n];return r?.kind===`word`?{index:n,value:r.value}:void 0}function classifyPragma(e){let t=e.findIndex(e=>e.kind===`symbol`&&e.value===`=`),n=e.findIndex(e=>e.kind===`symbol`&&e.value===`(`),r=t>=0?t:n,i=r<0?e.length:r,a;for(let t=i-1;t>0;--t){let n=e[t];if(n&&(n.kind===`word`||n.kind===`identifier`)){a=n.value;break}}return r<0?a&&v.has(a)?`no-rows`:`rows`:a&&_.has(a)?`no-rows`:`rows`}function convertD1Parameters(e){return u(e).map(e=>typeof e==`bigint`?e.toString():e)}const b=new Set([`aggregate`,`count`,`create`,`createManyAndReturn`,`delete`,`deleteManyAndReturn`,`exist`,`findFirst`,`findMany`,`findUnique`,`groupBy`,`update`,`updateManyAndReturn`,`upsert`]);function malformedD1Result(e,n){let r=e.operation??`execute`;return new t(`Driver "d1" returned a malformed result payload for operation "${r}": ${n}.`,{meta:{driver:`d1`,...e,operation:r}})}function assertD1BindingResult(e,t){if(!r(e)||e.success!==!0||e.results!==null&&!(Array.isArray(e.results)&&e.results.every(r))||!r(e.meta)||typeof e.meta.changes!=`number`||!Number.isFinite(e.meta.changes)||!Number.isSafeInteger(e.meta.changes)||e.meta.changes<0||typeof e.meta.last_row_id!=`number`||!Number.isFinite(e.meta.last_row_id)||!Number.isInteger(e.meta.last_row_id))throw malformedD1Result(t,`expected explicit object rows (or null), non-negative changes, and an integer last_row_id`)}function normalizeD1Result(e,t,n,r){let i=n.operation??`execute`;assertD1BindingResult(e,n);let a;if(e.results===null){if(r&&b.has(i)||classifySQLiteStatementResult(t)!==`no-rows`)throw malformedD1Result(n,`null results are not valid for a row-producing or unknown statement`);a=[]}else a=e.results;let o=isSQLiteInsertStatement(t)&&Number.isSafeInteger(e.meta.last_row_id)?e.meta.last_row_id:void 0;return{rows:a,rowCount:e.meta.changes===0?a.length:e.meta.changes,...o!==void 0&&o>0?{insertId:o}:{}}}var x=class D1Driver extends c{static canonicalExecuteEntry=D1Driver.prototype._execute;static canonicalExecute=D1Driver.prototype.execute;static canonicalTypedStatement=D1Driver.prototype.executeTypedStatement;static canonicalPositionalExecute=D1Driver.prototype.executePositional;adapter=new p({temporaryObjects:!1});maxBindParametersPerStatement=100;result=d;supportsTransactions=!1;supportsBatch=!0;supportsOrderedCommittedSegments=!0;driverOptions;canonicalAdapter=this.adapter;canonicalAdapterResult=this.adapter.result;canonicalAdapterParseField=this.adapter.result.parseField;canonicalAdapterParseRelation=this.adapter.result.parseRelation;canonicalAdapterParseResult=this.adapter.result.parseResult;constructor(e){super(`sqlite`,`d1`),this.driverOptions=e,this.client=e.database,a(this,(e,t)=>this.executePositional(e,t),D1Driver.isPositionalCandidate)}executePositional(e,t){return this.executeTypedStatement(e,t,async(e,t,r,i)=>{if(!D1Driver.isPositionalCandidate(this)){let a=await this.execute(e,t,r,i);return n(a,{provider:this.driverName,operation:i.operation??`execute`}),{kind:`borrowed`,result:a}}let a=convertD1Parameters(r),o=await e.prepare(t).bind(...a).raw({columnNames:!0}),[c,...l]=Array.isArray(o)?o:[],u=c??[];if(!(Array.isArray(o)&&Array.isArray(u)&&u.every(e=>typeof e==`string`)))throw malformedD1Result(i,`the positional rows are malformed`);return s(l,u,{provider:this.driverName,operation:i.operation??`execute`}),{kind:`positional`,rows:l,columns:u}})}static isPositionalCandidate(e){return e instanceof D1Driver?Object.getPrototypeOf(e)===D1Driver.prototype&&e._execute===D1Driver.canonicalExecuteEntry&&e.execute===D1Driver.canonicalExecute&&e.executeTypedStatement===D1Driver.canonicalTypedStatement&&e.executePositional===D1Driver.canonicalPositionalExecute&&e.result===d&&e.result.parseField===l&&e.result.parseRelation===void 0&&e.result.parseResult===void 0&&e.adapter===e.canonicalAdapter&&e.adapter.result===e.canonicalAdapterResult&&e.adapter.result.parseField===e.canonicalAdapterParseField&&e.adapter.result.parseRelation===e.canonicalAdapterParseRelation&&e.adapter.result.parseResult===e.canonicalAdapterParseResult:!1}async initClient(){return this.driverOptions.database}async closeClient(e){}async execute(e,t,n,r){return this.executeStatement(e,t,n,r??{operation:`execute`})}async executeStatement(e,t,n,r){let i=convertD1Parameters(n);return normalizeD1Result(await e.prepare(t).bind(...i).run(),t,r,!0)}async executeRaw(e,t,n,r){return this.executeStatement(e,t,n??[],r??{operation:`executeRaw`})}transactionOptionSupport(){return{isolationLevel:`unsupported`,isolationLevelReason:`D1 bindings execute batches through batch(), which opens no transaction VibORM can set an isolation level on`,timeout:!1,timeoutReason:`D1 bindings run a batch as one provider call with no interactive body to interrupt`,maxWait:`unsupported`,maxWaitReason:`D1 bindings submit the batch immediately with no connection to acquire`}}transaction(e,t){return Promise.reject(i(this.driverName))}async executeBatch(e,t,n,r){let i=n??{operation:`executeBatch`},a=[];for(let n of t){let t=n.context??i;try{let t=n.params?convertD1Parameters(n.params):[];a.push(e.prepare(n.sql).bind(...t))}catch(e){throw this.normalizeStatementFailure(e,n.sql,this.getBatchDiagnosticParameters(n),t,!0)}}let o=await e.batch(a);if(await r?.(),!Array.isArray(o)||o.length!==t.length){let e=Array.isArray(o)?o.length:0;throw malformedD1Result(i,`expected ${t.length} statement results but received ${e}`)}let s=[];for(let e=0;e<o.length;e+=1){let n=t[e];if(!n)throw malformedD1Result(i,`missing statement metadata at batch result index ${e}`);s.push(normalizeD1Result(o[e],n.sql,n.context??i,!1))}return s}};function createClient(e){let{database:t}=e;return o(e,new x({database:t}))}export{x as D1Driver,createClient};
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t,o as n}from"./bind-parameter-capacity-CjPgqnmx.mjs";import{m as r}from"./error-mapping-CnPCv1dm.mjs";import{f as i}from"./validation-Dk9Q_-C7.mjs";import{a,n as o,r as s}from"./client-BLiBmykn.mjs";import{c,t as l}from"./driver-BlnKXPFF.mjs";import{l as u,o as d,r as f}from"./sqlite-utils-DlgokMJN.mjs";import{t as p}from"./sql-statement-tokens-BBcoGmJb.mjs";import{t as m}from"./sqlite-adapter-CW_3l6ea.mjs";const h=new Set([`EXPLAIN`,`SELECT`,`VALUES`]),g=new Set([`DELETE`,`INSERT`,`REPLACE`,`UPDATE`]),_=new Set([`ALTER`,`ANALYZE`,`ATTACH`,`BEGIN`,`COMMIT`,`CREATE`,`DETACH`,`DROP`,`END`,`REINDEX`,`RELEASE`,`ROLLBACK`,`SAVEPOINT`,`VACUUM`]),v=new Set([`CASE_SENSITIVE_LIKE`,`DEFER_FOREIGN_KEYS`,`FOREIGN_KEYS`,`IGNORE_CHECK_CONSTRAINTS`,`LEGACY_ALTER_TABLE`,`RECURSIVE_TRIGGERS`,`REVERSE_UNORDERED_SELECTS`]),y=new Set([`OPTIMIZE`]),b=new Set([...h,...g]);function classifySQLiteStatementResult(e){let t=p(e);if(!t)return`unknown`;let n=topLevelCommand(t),r=n?.value;return r?h.has(r)?`rows`:g.has(r)?t.slice(n.index+1).some(e=>e.kind===`word`&&e.value===`RETURNING`)?`rows`:`no-rows`:r===`PRAGMA`?classifyPragma(t):_.has(r)?`no-rows`:`unknown`:`unknown`}function isSQLiteInsertStatement(e){let t=topLevelCommand(p(e))?.value;return t===`INSERT`||t===`REPLACE`}function topLevelCommand(e){let t=e?.[0];if(!t||t.kind!==`word`)return;if(t.value!==`WITH`)return{index:0,value:t.value};let n=e.findIndex((e,t)=>t>0&&e.kind===`word`&&b.has(e.value)),r=e[n];return r?.kind===`word`?{index:n,value:r.value}:void 0}function classifyPragma(e){let t=e.findIndex(e=>e.kind===`symbol`&&e.value===`=`),n=e.findIndex(e=>e.kind===`symbol`&&e.value===`(`),r=t>=0?t:n,i=r<0?e.length:r,a;for(let t=i-1;t>0;--t){let n=e[t];if(n&&(n.kind===`word`||n.kind===`identifier`)){a=n.value;break}}return r<0?a&&y.has(a)?`no-rows`:`rows`:a&&v.has(a)?`no-rows`:`rows`}const x={database:!0};function convertD1Parameters(e){return f(e).map(e=>typeof e==`bigint`?e.toString():e)}const S=new Set([`aggregate`,`count`,`create`,`createManyAndReturn`,`delete`,`deleteManyAndReturn`,`exist`,`findFirst`,`findMany`,`findUnique`,`groupBy`,`update`,`updateManyAndReturn`,`upsert`]);function malformedD1Result(e,t){let n=e.operation??`execute`;return new i(`Driver "d1" returned a malformed result payload for operation "${n}": ${t}.`,{meta:{driver:`d1`,...e,operation:n}})}function assertD1BindingResult(e,t){if(!n(e)||e.success!==!0||e.results!==null&&!(Array.isArray(e.results)&&e.results.every(n))||!n(e.meta)||typeof e.meta.changes!=`number`||!Number.isFinite(e.meta.changes)||!Number.isSafeInteger(e.meta.changes)||e.meta.changes<0||typeof e.meta.last_row_id!=`number`||!Number.isFinite(e.meta.last_row_id)||!Number.isInteger(e.meta.last_row_id))throw malformedD1Result(t,`expected explicit object rows (or null), non-negative changes, and an integer last_row_id`)}function normalizeD1Result(e,t,n,r){let i=n.operation??`execute`;assertD1BindingResult(e,n);let a;if(e.results===null){if(r&&S.has(i)||classifySQLiteStatementResult(t)!==`no-rows`)throw malformedD1Result(n,`null results are not valid for a row-producing or unknown statement`);a=[]}else a=e.results;let o=isSQLiteInsertStatement(t)&&Number.isSafeInteger(e.meta.last_row_id)?e.meta.last_row_id:void 0;return{rows:a,rowCount:e.meta.changes===0?a.length:e.meta.changes,...o!==void 0&&o>0?{insertId:o}:{}}}var C=class D1Driver extends l{static canonicalExecuteEntry=D1Driver.prototype._execute;static canonicalExecute=D1Driver.prototype.execute;static canonicalTypedStatement=D1Driver.prototype.executeTypedStatement;static canonicalPositionalExecute=D1Driver.prototype.executePositional;adapter=new m({temporaryObjects:!1});maxBindParametersPerStatement=100;result=u;supportsTransactions=!1;supportsBatch=!0;supportsOrderedCommittedSegments=!0;driverOptions;canonicalAdapter=this.adapter;canonicalAdapterResult=this.adapter.result;canonicalAdapterParseField=this.adapter.result.parseField;canonicalAdapterParseRelation=this.adapter.result.parseRelation;canonicalAdapterParseResult=this.adapter.result.parseResult;constructor(e){super(`sqlite`,`d1`),this.driverOptions=e,this.client=e.database,a(this,(e,t)=>this.executePositional(e,t),D1Driver.isPositionalCandidate)}executePositional(e,n){return this.executeTypedStatement(e,n,async(e,n,r,i)=>{if(!D1Driver.isPositionalCandidate(this)){let a=await this.execute(e,n,r,i);return t(a,{provider:this.driverName,operation:i.operation??`execute`}),{kind:`borrowed`,result:a}}let a=convertD1Parameters(r),o=await e.prepare(n).bind(...a).raw({columnNames:!0}),[c,...l]=Array.isArray(o)?o:[],u=c??[];if(!(Array.isArray(o)&&Array.isArray(u)&&u.every(e=>typeof e==`string`)))throw malformedD1Result(i,`the positional rows are malformed`);return s(l,u,{provider:this.driverName,operation:i.operation??`execute`}),{kind:`positional`,rows:l,columns:u}})}static isPositionalCandidate(e){return e instanceof D1Driver?Object.getPrototypeOf(e)===D1Driver.prototype&&e._execute===D1Driver.canonicalExecuteEntry&&e.execute===D1Driver.canonicalExecute&&e.executeTypedStatement===D1Driver.canonicalTypedStatement&&e.executePositional===D1Driver.canonicalPositionalExecute&&e.result===u&&e.result.parseField===d&&e.result.parseRelation===void 0&&e.result.parseResult===void 0&&e.adapter===e.canonicalAdapter&&e.adapter.result===e.canonicalAdapterResult&&e.adapter.result.parseField===e.canonicalAdapterParseField&&e.adapter.result.parseRelation===e.canonicalAdapterParseRelation&&e.adapter.result.parseResult===e.canonicalAdapterParseResult:!1}async initClient(){return this.driverOptions.database}async closeClient(e){}async execute(e,t,n,r){return this.executeStatement(e,t,n,r??{operation:`execute`})}async executeStatement(e,t,n,r){let i=convertD1Parameters(n);return normalizeD1Result(await e.prepare(t).bind(...i).run(),t,r,!0)}async executeRaw(e,t,n,r){return this.executeStatement(e,t,n??[],r??{operation:`executeRaw`})}transactionOptionSupport(){return{isolationLevel:`unsupported`,isolationLevelReason:`D1 bindings execute batches through batch(), which opens no transaction VibORM can set an isolation level on`,timeout:!1,timeoutReason:`D1 bindings run a batch as one provider call with no interactive body to interrupt`,maxWait:`unsupported`,maxWaitReason:`D1 bindings submit the batch immediately with no connection to acquire`}}transaction(e,t){return Promise.reject(r(this.driverName))}async executeBatch(e,t,n,r){let i=n??{operation:`executeBatch`},a=[];for(let n of t){let t=n.context??i;try{let t=n.params?convertD1Parameters(n.params):[];a.push(e.prepare(n.sql).bind(...t))}catch(e){throw this.normalizeStatementFailure(e,n.sql,this.getBatchDiagnosticParameters(n),t,!0)}}let o=await e.batch(a);if(await r?.(),!Array.isArray(o)||o.length!==t.length){let e=Array.isArray(o)?o.length:0;throw malformedD1Result(i,`expected ${t.length} statement results but received ${e}`)}let s=[];for(let e=0;e<o.length;e+=1){let n=t[e];if(!n)throw malformedD1Result(i,`missing statement metadata at batch result index ${e}`);s.push(normalizeD1Result(o[e],n.sql,n.context??i,!1))}return s}};function createClient(e){c(e,`d1`,x);let{database:t}=e;return o(e,new C({database:t}))}export{C as D1Driver,createClient};
2
2
  //# sourceMappingURL=d1.mjs.map
package/dist/d1.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"d1.mjs","names":[],"sources":["../src/drivers/shared/sqlite-statement-classifier.ts","../src/drivers/d1/index.ts"],"sourcesContent":["import {\n getTopLevelStatementTokens,\n type SQLStatementToken,\n} from \"./sql-statement-tokens\";\n\nexport type SQLiteStatementResultKind = \"rows\" | \"no-rows\" | \"unknown\";\n\nconst ROW_COMMANDS = new Set([\"EXPLAIN\", \"SELECT\", \"VALUES\"]);\nconst MUTATION_COMMANDS = new Set([\"DELETE\", \"INSERT\", \"REPLACE\", \"UPDATE\"]);\nconst NO_ROW_COMMANDS = new Set([\n \"ALTER\",\n \"ANALYZE\",\n \"ATTACH\",\n \"BEGIN\",\n \"COMMIT\",\n \"CREATE\",\n \"DETACH\",\n \"DROP\",\n \"END\",\n \"REINDEX\",\n \"RELEASE\",\n \"ROLLBACK\",\n \"SAVEPOINT\",\n \"VACUUM\",\n]);\nconst NO_ROW_PRAGMA_SETTERS = new Set([\n \"CASE_SENSITIVE_LIKE\",\n \"DEFER_FOREIGN_KEYS\",\n \"FOREIGN_KEYS\",\n \"IGNORE_CHECK_CONSTRAINTS\",\n \"LEGACY_ALTER_TABLE\",\n \"RECURSIVE_TRIGGERS\",\n \"REVERSE_UNORDERED_SELECTS\",\n]);\nconst NO_ROW_PRAGMA_COMMANDS = new Set([\"OPTIMIZE\"]);\nconst WITH_COMMANDS = new Set([...ROW_COMMANDS, ...MUTATION_COMMANDS]);\n\n/** Classify whether one SQLite statement is contractually row-producing. */\nexport function classifySQLiteStatementResult(\n sql: string\n): SQLiteStatementResultKind {\n const topLevel = getTopLevelStatementTokens(sql);\n if (!topLevel) return \"unknown\";\n const resolved = topLevelCommand(topLevel);\n const command = resolved?.value;\n if (!command) return \"unknown\";\n if (ROW_COMMANDS.has(command)) {\n return \"rows\";\n }\n if (MUTATION_COMMANDS.has(command)) {\n return topLevel\n .slice(resolved.index + 1)\n .some((token) => token.kind === \"word\" && token.value === \"RETURNING\")\n ? \"rows\"\n : \"no-rows\";\n }\n if (command === \"PRAGMA\") {\n return classifyPragma(topLevel);\n }\n return NO_ROW_COMMANDS.has(command) ? \"no-rows\" : \"unknown\";\n}\n\n/** Whether D1/SQLite's statement-local generated-row metadata belongs to this SQL. */\nexport function isSQLiteInsertStatement(sql: string): boolean {\n const command = topLevelCommand(getTopLevelStatementTokens(sql))?.value;\n return command === \"INSERT\" || command === \"REPLACE\";\n}\n\nfunction topLevelCommand(\n topLevel: SQLStatementToken[] | undefined\n): { readonly index: number; readonly value: string } | undefined {\n const first = topLevel?.[0];\n if (!first || first.kind !== \"word\") return undefined;\n if (first.value !== \"WITH\") return { index: 0, value: first.value };\n const index = topLevel.findIndex(\n (token, tokenIndex) =>\n tokenIndex > 0 && token.kind === \"word\" && WITH_COMMANDS.has(token.value)\n );\n const command = topLevel[index];\n return command?.kind === \"word\" ? { index, value: command.value } : undefined;\n}\n\nfunction classifyPragma(\n tokens: SQLStatementToken[]\n): SQLiteStatementResultKind {\n const assignmentIndex = tokens.findIndex(\n (token) => token.kind === \"symbol\" && token.value === \"=\"\n );\n const argumentIndex = tokens.findIndex(\n (token) => token.kind === \"symbol\" && token.value === \"(\"\n );\n const setterBoundaryIndex =\n assignmentIndex >= 0 ? assignmentIndex : argumentIndex;\n const pragmaNameBoundary =\n setterBoundaryIndex < 0 ? tokens.length : setterBoundaryIndex;\n\n let pragmaName: string | undefined;\n for (let index = pragmaNameBoundary - 1; index > 0; index -= 1) {\n const token = tokens[index];\n if (token && (token.kind === \"word\" || token.kind === \"identifier\")) {\n pragmaName = token.value;\n break;\n }\n }\n if (setterBoundaryIndex < 0) {\n return pragmaName && NO_ROW_PRAGMA_COMMANDS.has(pragmaName)\n ? \"no-rows\"\n : \"rows\";\n }\n return pragmaName && NO_ROW_PRAGMA_SETTERS.has(pragmaName)\n ? \"no-rows\"\n : \"rows\";\n}\n","/**\n * Cloudflare D1 Driver (Bindings)\n *\n * Driver implementation for Cloudflare D1 using Worker bindings.\n * Note: D1 does not support true transactions - batch() provides atomicity only.\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport { SQLiteAdapter } from \"@adapters/databases/sqlite/sqlite-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport type { D1Database, D1DatabaseSession } from \"@cloudflare/workers-types\";\nimport { QueryError } from \"@errors\";\nimport type { Sql } from \"@sql\";\nimport {\n type AnyDriver,\n Driver,\n type DriverResultParser,\n type QueryExecutionContext,\n} from \"../driver\";\nimport {\n assertNormalizedQueryResult,\n isNormalizedResultRow,\n} from \"../normalized-result\";\nimport {\n assertPositionalRows,\n type ProjectionExecutionResult,\n registerPositionalResultDriver,\n} from \"../positional-result\";\nimport {\n classifySQLiteStatementResult,\n convertValuesForSQLite,\n isSQLiteInsertStatement,\n sqliteResultParser,\n type TransactionOptionSupport,\n unsupportedCallbackTransactionError,\n} from \"../shared\";\nimport { parseSQLiteField } from \"../shared/sqlite-utils\";\nimport type {\n BatchQuery,\n CommittedBatchNotification,\n QueryResult,\n} from \"../types\";\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport interface D1DriverOptions {\n database: D1Database | D1DatabaseSession;\n}\n\nexport type D1ClientConfig<C extends DriverConfig> = D1DriverOptions & C;\n\ninterface D1BindingResult<T> {\n success: true;\n results: T[] | null;\n meta: { changes: number; last_row_id: number };\n}\n\nfunction convertD1Parameters(values: unknown[]): unknown[] {\n return convertValuesForSQLite(values).map((value) =>\n typeof value === \"bigint\" ? value.toString() : value\n );\n}\n\nconst ROW_PRODUCING_OPERATIONS = new Set([\n \"aggregate\",\n \"count\",\n \"create\",\n \"createManyAndReturn\",\n \"delete\",\n \"deleteManyAndReturn\",\n \"exist\",\n \"findFirst\",\n \"findMany\",\n \"findUnique\",\n \"groupBy\",\n \"update\",\n \"updateManyAndReturn\",\n \"upsert\",\n]);\n\nfunction malformedD1Result(\n context: QueryExecutionContext,\n reason: string\n): QueryError {\n const operation = context.operation ?? \"execute\";\n return new QueryError(\n `Driver \"d1\" returned a malformed result payload for operation \"${operation}\": ${reason}.`,\n { meta: { driver: \"d1\", ...context, operation } }\n );\n}\n\nfunction assertD1BindingResult<T>(\n result: unknown,\n context: QueryExecutionContext\n): asserts result is D1BindingResult<T> {\n if (\n !isNormalizedResultRow(result) ||\n result.success !== true ||\n (result.results !== null &&\n !(\n Array.isArray(result.results) &&\n result.results.every(isNormalizedResultRow)\n )) ||\n !isNormalizedResultRow(result.meta) ||\n typeof result.meta.changes !== \"number\" ||\n !Number.isFinite(result.meta.changes) ||\n !Number.isSafeInteger(result.meta.changes) ||\n result.meta.changes < 0 ||\n typeof result.meta.last_row_id !== \"number\" ||\n !Number.isFinite(result.meta.last_row_id) ||\n !Number.isInteger(result.meta.last_row_id)\n ) {\n throw malformedD1Result(\n context,\n \"expected explicit object rows (or null), non-negative changes, and an integer last_row_id\"\n );\n }\n}\n\nfunction normalizeD1Result<T>(\n result: unknown,\n sql: string,\n context: QueryExecutionContext,\n enforceOperationContract: boolean\n): QueryResult<T> {\n const operation = context.operation ?? \"execute\";\n assertD1BindingResult<T>(result, context);\n let rows: T[];\n if (result.results === null) {\n const operationRequiresRows =\n enforceOperationContract && ROW_PRODUCING_OPERATIONS.has(operation);\n if (\n operationRequiresRows ||\n classifySQLiteStatementResult(sql) !== \"no-rows\"\n ) {\n throw malformedD1Result(\n context,\n \"null results are not valid for a row-producing or unknown statement\"\n );\n }\n rows = [];\n } else {\n rows = result.results;\n }\n // D1 reports the connection's most recent row id on later statements too.\n // Publish it only for the INSERT/REPLACE statement that owns that identity.\n // D1 rounds 64-bit row ids in this numeric metadata. Exact RETURNING rows\n // remain authoritative; unusable optional metadata must never become a key.\n const insertId =\n isSQLiteInsertStatement(sql) &&\n Number.isSafeInteger(result.meta.last_row_id)\n ? result.meta.last_row_id\n : undefined;\n return {\n rows,\n rowCount: result.meta.changes === 0 ? rows.length : result.meta.changes,\n ...(insertId !== undefined && insertId > 0 ? { insertId } : {}),\n };\n}\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class D1Driver extends Driver<\n D1Database | D1DatabaseSession,\n D1Database | D1DatabaseSession\n> {\n private static readonly canonicalExecuteEntry = D1Driver.prototype._execute;\n private static readonly canonicalExecute = D1Driver.prototype.execute;\n private static readonly canonicalTypedStatement =\n D1Driver.prototype.executeTypedStatement;\n private static readonly canonicalPositionalExecute =\n D1Driver.prototype.executePositional;\n\n // D1's authorizer refuses temporary objects (`SQLITE_AUTH`, the whole batch\n // rejected), witnessed by `tests/providers/workers/d1.test.ts`.\n readonly adapter: DatabaseAdapter = new SQLiteAdapter({\n temporaryObjects: false,\n });\n readonly maxBindParametersPerStatement: number | undefined = 100;\n readonly result: DriverResultParser = sqliteResultParser;\n readonly supportsTransactions = false;\n readonly supportsBatch = true;\n readonly supportsOrderedCommittedSegments = true;\n\n private readonly driverOptions: D1DriverOptions;\n private readonly canonicalAdapter = this.adapter;\n private readonly canonicalAdapterResult = this.adapter.result;\n private readonly canonicalAdapterParseField = this.adapter.result.parseField;\n private readonly canonicalAdapterParseRelation =\n this.adapter.result.parseRelation;\n private readonly canonicalAdapterParseResult =\n this.adapter.result.parseResult;\n\n constructor(options: D1DriverOptions) {\n super(\"sqlite\", \"d1\");\n this.driverOptions = options;\n // D1 database is passed directly from Worker environment\n this.client = options.database;\n registerPositionalResultDriver(\n this,\n (query, context) => this.executePositional(query, context),\n D1Driver.isPositionalCandidate\n );\n }\n\n /**\n * A collection read as positional rows: D1's `raw({ columnNames: true })`\n * names the columns once instead of materializing every column name on\n * every row, which is the larger share of a read's CPU in a Worker.\n */\n private executePositional(\n query: Sql,\n context: QueryExecutionContext\n ): Promise<ProjectionExecutionResult> {\n return this.executeTypedStatement(\n query,\n context,\n async (\n client,\n sql,\n params,\n executionContext\n ): Promise<ProjectionExecutionResult> => {\n // Transforms and observers ran after admission and may have replaced\n // an execution surface: decide again at dispatch, and let a replaced\n // surface run as ordinary execution.\n if (!D1Driver.isPositionalCandidate(this)) {\n const result = await this.execute<unknown>(\n client,\n sql,\n params,\n executionContext\n );\n assertNormalizedQueryResult(result, {\n provider: this.driverName,\n operation: executionContext.operation ?? \"execute\",\n });\n return { kind: \"borrowed\", result };\n }\n const values = convertD1Parameters(params);\n const raw: unknown = await client\n .prepare(sql)\n .bind(...values)\n .raw({ columnNames: true });\n const [header, ...rows] = Array.isArray(raw) ? raw : [];\n const columns = header ?? [];\n if (\n !(\n Array.isArray(raw) &&\n Array.isArray(columns) &&\n columns.every((column: unknown) => typeof column === \"string\")\n )\n )\n throw malformedD1Result(\n executionContext,\n \"the positional rows are malformed\"\n );\n assertPositionalRows(rows, columns, {\n provider: this.driverName,\n operation: executionContext.operation ?? \"execute\",\n });\n return { kind: \"positional\", rows, columns };\n }\n );\n }\n\n /**\n * Positional rows skip the keyed result surface and dispatch to the binding\n * directly, so they are used only while both are the shipped ones: the stock\n * parsers, and this driver's own execution entry, provider execute and typed\n * statement lifecycle. Anything a caller replaced keeps keyed rows.\n */\n private static isPositionalCandidate(driver: AnyDriver): boolean {\n if (!(driver instanceof D1Driver)) return false;\n return (\n Object.getPrototypeOf(driver) === D1Driver.prototype &&\n driver._execute === D1Driver.canonicalExecuteEntry &&\n driver.execute === D1Driver.canonicalExecute &&\n driver.executeTypedStatement === D1Driver.canonicalTypedStatement &&\n driver.executePositional === D1Driver.canonicalPositionalExecute &&\n driver.result === sqliteResultParser &&\n driver.result.parseField === parseSQLiteField &&\n driver.result.parseRelation === undefined &&\n driver.result.parseResult === undefined &&\n driver.adapter === driver.canonicalAdapter &&\n driver.adapter.result === driver.canonicalAdapterResult &&\n driver.adapter.result.parseField === driver.canonicalAdapterParseField &&\n driver.adapter.result.parseRelation ===\n driver.canonicalAdapterParseRelation &&\n driver.adapter.result.parseResult === driver.canonicalAdapterParseResult\n );\n }\n\n protected async initClient(): Promise<D1Database | D1DatabaseSession> {\n // D1 database binding is passed in constructor\n return this.driverOptions.database;\n }\n\n protected async closeClient(\n _db: D1Database | D1DatabaseSession\n ): Promise<void> {\n // D1 bindings don't need to be closed\n }\n\n protected async execute<T>(\n client: D1Database | D1DatabaseSession,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeStatement<T>(\n client,\n sql,\n params,\n context ?? { operation: \"execute\" }\n );\n }\n\n private async executeStatement<T>(\n client: D1Database | D1DatabaseSession,\n sql: string,\n params: unknown[],\n context: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const values = convertD1Parameters(params);\n const stmt = client.prepare(sql).bind(...values);\n const result: unknown = await stmt.run<T>();\n return normalizeD1Result<T>(result, sql, context, true);\n }\n\n protected async executeRaw<T>(\n client: D1Database | D1DatabaseSession,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeStatement<T>(\n client,\n sql,\n params ?? [],\n context ?? { operation: \"executeRaw\" }\n );\n }\n\n /**\n * D1 bindings expose `batch()` and no callback transaction. There is no\n * BEGIN to configure, no interactive body to time out, and no slot to wait\n * for — every option is refused rather than quietly dropped.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"unsupported\",\n isolationLevelReason:\n \"D1 bindings execute batches through batch(), which opens no transaction VibORM can set an isolation level on\",\n timeout: false,\n timeoutReason:\n \"D1 bindings run a batch as one provider call with no interactive body to interrupt\",\n maxWait: \"unsupported\",\n maxWaitReason:\n \"D1 bindings submit the batch immediately with no connection to acquire\",\n };\n }\n\n protected transaction<T>(\n _client: D1Database | D1DatabaseSession,\n _fn: (tx: D1Database | D1DatabaseSession) => Promise<T>\n ): Promise<T> {\n return Promise.reject(unsupportedCallbackTransactionError(this.driverName));\n }\n\n /**\n * Execute multiple queries atomically using D1's native batch() API.\n * All queries succeed or all fail together.\n */\n protected async executeBatch<T>(\n client: D1Database | D1DatabaseSession,\n queries: BatchQuery[],\n context?: QueryExecutionContext,\n committed?: CommittedBatchNotification\n ): Promise<QueryResult<T>[]> {\n const batchContext = context ?? { operation: \"executeBatch\" };\n const statements: ReturnType<D1Database[\"prepare\"]>[] = [];\n for (const query of queries) {\n const statementContext = query.context ?? batchContext;\n try {\n const values = query.params ? convertD1Parameters(query.params) : [];\n statements.push(client.prepare(query.sql).bind(...values));\n } catch (error) {\n throw this.normalizeStatementFailure(\n error,\n query.sql,\n this.getBatchDiagnosticParameters(query),\n statementContext,\n true\n );\n }\n }\n\n // Execute all statements atomically\n const results: unknown = await client.batch<T>(statements);\n await committed?.();\n\n if (!Array.isArray(results) || results.length !== queries.length) {\n const actualResultCount = Array.isArray(results) ? results.length : 0;\n throw malformedD1Result(\n batchContext,\n `expected ${queries.length} statement results but received ${actualResultCount}`\n );\n }\n\n const normalized: QueryResult<T>[] = [];\n for (let index = 0; index < results.length; index += 1) {\n const query = queries[index];\n if (!query) {\n throw malformedD1Result(\n batchContext,\n `missing statement metadata at batch result index ${index}`\n );\n }\n normalized.push(\n normalizeD1Result<T>(\n results[index],\n query.sql,\n query.context ?? batchContext,\n false\n )\n );\n }\n return normalized;\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: D1ClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, D1DriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<C & { driver: D1Driver }>]: LinkedClientConfig<\n C & { driver: D1Driver }\n >[P];\n}> {\n const { database } = config;\n\n const driver = new D1Driver({ database });\n\n return createClientFromDriverConfig<S, C, D1Driver>(config, driver);\n}\n"],"mappings":"8cAOA,MAAM,EAAe,IAAI,IAAI,CAAC,UAAW,SAAU,SAAS,CAAC,CACvD,EAAoB,IAAI,IAAI,CAAC,SAAU,SAAU,UAAW,SAAS,CAAC,CACtE,EAAkB,IAAI,IAAI,CAC9B,QACA,UACA,SACA,QACA,SACA,SACA,SACA,OACA,MACA,UACA,UACA,WACA,YACA,SACD,CAAC,CACI,EAAwB,IAAI,IAAI,CACpC,sBACA,qBACA,eACA,2BACA,qBACA,qBACA,4BACD,CAAC,CACI,EAAyB,IAAI,IAAI,CAAC,WAAW,CAAC,CAC9C,EAAgB,IAAI,IAAI,CAAC,GAAG,EAAc,GAAG,EAAkB,CAAC,CAGtE,SAAgB,8BACd,EAC2B,CAC3B,IAAM,EAAW,EAA2B,EAAI,CAChD,GAAI,CAAC,EAAU,MAAO,UACtB,IAAM,EAAW,gBAAgB,EAAS,CACpC,EAAU,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A6C,EAFrC,IAAI,EAAS,CAAE,WAAU,CAAC,CAE0B"}
1
+ {"version":3,"file":"d1.mjs","names":[],"sources":["../src/drivers/shared/sqlite-statement-classifier.ts","../src/drivers/d1/index.ts"],"sourcesContent":["import {\n getTopLevelStatementTokens,\n type SQLStatementToken,\n} from \"./sql-statement-tokens\";\n\nexport type SQLiteStatementResultKind = \"rows\" | \"no-rows\" | \"unknown\";\n\nconst ROW_COMMANDS = new Set([\"EXPLAIN\", \"SELECT\", \"VALUES\"]);\nconst MUTATION_COMMANDS = new Set([\"DELETE\", \"INSERT\", \"REPLACE\", \"UPDATE\"]);\nconst NO_ROW_COMMANDS = new Set([\n \"ALTER\",\n \"ANALYZE\",\n \"ATTACH\",\n \"BEGIN\",\n \"COMMIT\",\n \"CREATE\",\n \"DETACH\",\n \"DROP\",\n \"END\",\n \"REINDEX\",\n \"RELEASE\",\n \"ROLLBACK\",\n \"SAVEPOINT\",\n \"VACUUM\",\n]);\nconst NO_ROW_PRAGMA_SETTERS = new Set([\n \"CASE_SENSITIVE_LIKE\",\n \"DEFER_FOREIGN_KEYS\",\n \"FOREIGN_KEYS\",\n \"IGNORE_CHECK_CONSTRAINTS\",\n \"LEGACY_ALTER_TABLE\",\n \"RECURSIVE_TRIGGERS\",\n \"REVERSE_UNORDERED_SELECTS\",\n]);\nconst NO_ROW_PRAGMA_COMMANDS = new Set([\"OPTIMIZE\"]);\nconst WITH_COMMANDS = new Set([...ROW_COMMANDS, ...MUTATION_COMMANDS]);\n\n/** Classify whether one SQLite statement is contractually row-producing. */\nexport function classifySQLiteStatementResult(\n sql: string\n): SQLiteStatementResultKind {\n const topLevel = getTopLevelStatementTokens(sql);\n if (!topLevel) return \"unknown\";\n const resolved = topLevelCommand(topLevel);\n const command = resolved?.value;\n if (!command) return \"unknown\";\n if (ROW_COMMANDS.has(command)) {\n return \"rows\";\n }\n if (MUTATION_COMMANDS.has(command)) {\n return topLevel\n .slice(resolved.index + 1)\n .some((token) => token.kind === \"word\" && token.value === \"RETURNING\")\n ? \"rows\"\n : \"no-rows\";\n }\n if (command === \"PRAGMA\") {\n return classifyPragma(topLevel);\n }\n return NO_ROW_COMMANDS.has(command) ? \"no-rows\" : \"unknown\";\n}\n\n/** Whether D1/SQLite's statement-local generated-row metadata belongs to this SQL. */\nexport function isSQLiteInsertStatement(sql: string): boolean {\n const command = topLevelCommand(getTopLevelStatementTokens(sql))?.value;\n return command === \"INSERT\" || command === \"REPLACE\";\n}\n\nfunction topLevelCommand(\n topLevel: SQLStatementToken[] | undefined\n): { readonly index: number; readonly value: string } | undefined {\n const first = topLevel?.[0];\n if (!first || first.kind !== \"word\") return undefined;\n if (first.value !== \"WITH\") return { index: 0, value: first.value };\n const index = topLevel.findIndex(\n (token, tokenIndex) =>\n tokenIndex > 0 && token.kind === \"word\" && WITH_COMMANDS.has(token.value)\n );\n const command = topLevel[index];\n return command?.kind === \"word\" ? { index, value: command.value } : undefined;\n}\n\nfunction classifyPragma(\n tokens: SQLStatementToken[]\n): SQLiteStatementResultKind {\n const assignmentIndex = tokens.findIndex(\n (token) => token.kind === \"symbol\" && token.value === \"=\"\n );\n const argumentIndex = tokens.findIndex(\n (token) => token.kind === \"symbol\" && token.value === \"(\"\n );\n const setterBoundaryIndex =\n assignmentIndex >= 0 ? assignmentIndex : argumentIndex;\n const pragmaNameBoundary =\n setterBoundaryIndex < 0 ? tokens.length : setterBoundaryIndex;\n\n let pragmaName: string | undefined;\n for (let index = pragmaNameBoundary - 1; index > 0; index -= 1) {\n const token = tokens[index];\n if (token && (token.kind === \"word\" || token.kind === \"identifier\")) {\n pragmaName = token.value;\n break;\n }\n }\n if (setterBoundaryIndex < 0) {\n return pragmaName && NO_ROW_PRAGMA_COMMANDS.has(pragmaName)\n ? \"no-rows\"\n : \"rows\";\n }\n return pragmaName && NO_ROW_PRAGMA_SETTERS.has(pragmaName)\n ? \"no-rows\"\n : \"rows\";\n}\n","/**\n * Cloudflare D1 Driver (Bindings)\n *\n * Driver implementation for Cloudflare D1 using Worker bindings.\n * Note: D1 does not support true transactions - batch() provides atomicity only.\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport { SQLiteAdapter } from \"@adapters/databases/sqlite/sqlite-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport type { D1Database, D1DatabaseSession } from \"@cloudflare/workers-types\";\nimport { QueryError } from \"@errors\";\nimport type { Sql } from \"@sql\";\nimport {\n type AnyDriver,\n Driver,\n type DriverResultParser,\n type QueryExecutionContext,\n} from \"../driver\";\nimport {\n assertNormalizedQueryResult,\n isNormalizedResultRow,\n} from \"../normalized-result\";\nimport {\n assertPositionalRows,\n type ProjectionExecutionResult,\n registerPositionalResultDriver,\n} from \"../positional-result\";\nimport {\n classifySQLiteStatementResult,\n convertValuesForSQLite,\n isSQLiteInsertStatement,\n sqliteResultParser,\n type TransactionOptionSupport,\n unsupportedCallbackTransactionError,\n} from \"../shared\";\nimport { refuseUnknownDriverConfigKeys } from \"../shared/driver-options\";\nimport { parseSQLiteField } from \"../shared/sqlite-utils\";\nimport type {\n BatchQuery,\n CommittedBatchNotification,\n QueryResult,\n} from \"../types\";\n\n// ============================================================\n// EXPORTED OPTIONS\n// ============================================================\n\nexport interface D1DriverOptions {\n database: D1Database | D1DatabaseSession;\n}\n\nexport type D1ClientConfig<C extends DriverConfig> = D1DriverOptions & C;\n\nconst D1_CONFIG_KEYS: Record<keyof D1DriverOptions, true> = { database: true };\n\ninterface D1BindingResult<T> {\n success: true;\n results: T[] | null;\n meta: { changes: number; last_row_id: number };\n}\n\nfunction convertD1Parameters(values: unknown[]): unknown[] {\n return convertValuesForSQLite(values).map((value) =>\n typeof value === \"bigint\" ? value.toString() : value\n );\n}\n\nconst ROW_PRODUCING_OPERATIONS = new Set([\n \"aggregate\",\n \"count\",\n \"create\",\n \"createManyAndReturn\",\n \"delete\",\n \"deleteManyAndReturn\",\n \"exist\",\n \"findFirst\",\n \"findMany\",\n \"findUnique\",\n \"groupBy\",\n \"update\",\n \"updateManyAndReturn\",\n \"upsert\",\n]);\n\nfunction malformedD1Result(\n context: QueryExecutionContext,\n reason: string\n): QueryError {\n const operation = context.operation ?? \"execute\";\n return new QueryError(\n `Driver \"d1\" returned a malformed result payload for operation \"${operation}\": ${reason}.`,\n { meta: { driver: \"d1\", ...context, operation } }\n );\n}\n\nfunction assertD1BindingResult<T>(\n result: unknown,\n context: QueryExecutionContext\n): asserts result is D1BindingResult<T> {\n if (\n !isNormalizedResultRow(result) ||\n result.success !== true ||\n (result.results !== null &&\n !(\n Array.isArray(result.results) &&\n result.results.every(isNormalizedResultRow)\n )) ||\n !isNormalizedResultRow(result.meta) ||\n typeof result.meta.changes !== \"number\" ||\n !Number.isFinite(result.meta.changes) ||\n !Number.isSafeInteger(result.meta.changes) ||\n result.meta.changes < 0 ||\n typeof result.meta.last_row_id !== \"number\" ||\n !Number.isFinite(result.meta.last_row_id) ||\n !Number.isInteger(result.meta.last_row_id)\n ) {\n throw malformedD1Result(\n context,\n \"expected explicit object rows (or null), non-negative changes, and an integer last_row_id\"\n );\n }\n}\n\nfunction normalizeD1Result<T>(\n result: unknown,\n sql: string,\n context: QueryExecutionContext,\n enforceOperationContract: boolean\n): QueryResult<T> {\n const operation = context.operation ?? \"execute\";\n assertD1BindingResult<T>(result, context);\n let rows: T[];\n if (result.results === null) {\n const operationRequiresRows =\n enforceOperationContract && ROW_PRODUCING_OPERATIONS.has(operation);\n if (\n operationRequiresRows ||\n classifySQLiteStatementResult(sql) !== \"no-rows\"\n ) {\n throw malformedD1Result(\n context,\n \"null results are not valid for a row-producing or unknown statement\"\n );\n }\n rows = [];\n } else {\n rows = result.results;\n }\n // D1 reports the connection's most recent row id on later statements too.\n // Publish it only for the INSERT/REPLACE statement that owns that identity.\n // D1 rounds 64-bit row ids in this numeric metadata. Exact RETURNING rows\n // remain authoritative; unusable optional metadata must never become a key.\n const insertId =\n isSQLiteInsertStatement(sql) &&\n Number.isSafeInteger(result.meta.last_row_id)\n ? result.meta.last_row_id\n : undefined;\n return {\n rows,\n rowCount: result.meta.changes === 0 ? rows.length : result.meta.changes,\n ...(insertId !== undefined && insertId > 0 ? { insertId } : {}),\n };\n}\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class D1Driver extends Driver<\n D1Database | D1DatabaseSession,\n D1Database | D1DatabaseSession\n> {\n private static readonly canonicalExecuteEntry = D1Driver.prototype._execute;\n private static readonly canonicalExecute = D1Driver.prototype.execute;\n private static readonly canonicalTypedStatement =\n D1Driver.prototype.executeTypedStatement;\n private static readonly canonicalPositionalExecute =\n D1Driver.prototype.executePositional;\n\n // D1's authorizer refuses temporary objects (`SQLITE_AUTH`, the whole batch\n // rejected), witnessed by `tests/providers/workers/d1.test.ts`.\n readonly adapter: DatabaseAdapter = new SQLiteAdapter({\n temporaryObjects: false,\n });\n readonly maxBindParametersPerStatement: number | undefined = 100;\n readonly result: DriverResultParser = sqliteResultParser;\n readonly supportsTransactions = false;\n readonly supportsBatch = true;\n readonly supportsOrderedCommittedSegments = true;\n\n private readonly driverOptions: D1DriverOptions;\n private readonly canonicalAdapter = this.adapter;\n private readonly canonicalAdapterResult = this.adapter.result;\n private readonly canonicalAdapterParseField = this.adapter.result.parseField;\n private readonly canonicalAdapterParseRelation =\n this.adapter.result.parseRelation;\n private readonly canonicalAdapterParseResult =\n this.adapter.result.parseResult;\n\n constructor(options: D1DriverOptions) {\n super(\"sqlite\", \"d1\");\n this.driverOptions = options;\n // D1 database is passed directly from Worker environment\n this.client = options.database;\n registerPositionalResultDriver(\n this,\n (query, context) => this.executePositional(query, context),\n D1Driver.isPositionalCandidate\n );\n }\n\n /**\n * A collection read as positional rows: D1's `raw({ columnNames: true })`\n * names the columns once instead of materializing every column name on\n * every row, which is the larger share of a read's CPU in a Worker.\n */\n private executePositional(\n query: Sql,\n context: QueryExecutionContext\n ): Promise<ProjectionExecutionResult> {\n return this.executeTypedStatement(\n query,\n context,\n async (\n client,\n sql,\n params,\n executionContext\n ): Promise<ProjectionExecutionResult> => {\n // Transforms and observers ran after admission and may have replaced\n // an execution surface: decide again at dispatch, and let a replaced\n // surface run as ordinary execution.\n if (!D1Driver.isPositionalCandidate(this)) {\n const result = await this.execute<unknown>(\n client,\n sql,\n params,\n executionContext\n );\n assertNormalizedQueryResult(result, {\n provider: this.driverName,\n operation: executionContext.operation ?? \"execute\",\n });\n return { kind: \"borrowed\", result };\n }\n const values = convertD1Parameters(params);\n const raw: unknown = await client\n .prepare(sql)\n .bind(...values)\n .raw({ columnNames: true });\n const [header, ...rows] = Array.isArray(raw) ? raw : [];\n const columns = header ?? [];\n if (\n !(\n Array.isArray(raw) &&\n Array.isArray(columns) &&\n columns.every((column: unknown) => typeof column === \"string\")\n )\n )\n throw malformedD1Result(\n executionContext,\n \"the positional rows are malformed\"\n );\n assertPositionalRows(rows, columns, {\n provider: this.driverName,\n operation: executionContext.operation ?? \"execute\",\n });\n return { kind: \"positional\", rows, columns };\n }\n );\n }\n\n /**\n * Positional rows skip the keyed result surface and dispatch to the binding\n * directly, so they are used only while both are the shipped ones: the stock\n * parsers, and this driver's own execution entry, provider execute and typed\n * statement lifecycle. Anything a caller replaced keeps keyed rows.\n */\n private static isPositionalCandidate(driver: AnyDriver): boolean {\n if (!(driver instanceof D1Driver)) return false;\n return (\n Object.getPrototypeOf(driver) === D1Driver.prototype &&\n driver._execute === D1Driver.canonicalExecuteEntry &&\n driver.execute === D1Driver.canonicalExecute &&\n driver.executeTypedStatement === D1Driver.canonicalTypedStatement &&\n driver.executePositional === D1Driver.canonicalPositionalExecute &&\n driver.result === sqliteResultParser &&\n driver.result.parseField === parseSQLiteField &&\n driver.result.parseRelation === undefined &&\n driver.result.parseResult === undefined &&\n driver.adapter === driver.canonicalAdapter &&\n driver.adapter.result === driver.canonicalAdapterResult &&\n driver.adapter.result.parseField === driver.canonicalAdapterParseField &&\n driver.adapter.result.parseRelation ===\n driver.canonicalAdapterParseRelation &&\n driver.adapter.result.parseResult === driver.canonicalAdapterParseResult\n );\n }\n\n protected async initClient(): Promise<D1Database | D1DatabaseSession> {\n // D1 database binding is passed in constructor\n return this.driverOptions.database;\n }\n\n protected async closeClient(\n _db: D1Database | D1DatabaseSession\n ): Promise<void> {\n // D1 bindings don't need to be closed\n }\n\n protected async execute<T>(\n client: D1Database | D1DatabaseSession,\n sql: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeStatement<T>(\n client,\n sql,\n params,\n context ?? { operation: \"execute\" }\n );\n }\n\n private async executeStatement<T>(\n client: D1Database | D1DatabaseSession,\n sql: string,\n params: unknown[],\n context: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const values = convertD1Parameters(params);\n const stmt = client.prepare(sql).bind(...values);\n const result: unknown = await stmt.run<T>();\n return normalizeD1Result<T>(result, sql, context, true);\n }\n\n protected async executeRaw<T>(\n client: D1Database | D1DatabaseSession,\n sql: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeStatement<T>(\n client,\n sql,\n params ?? [],\n context ?? { operation: \"executeRaw\" }\n );\n }\n\n /**\n * D1 bindings expose `batch()` and no callback transaction. There is no\n * BEGIN to configure, no interactive body to time out, and no slot to wait\n * for — every option is refused rather than quietly dropped.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"unsupported\",\n isolationLevelReason:\n \"D1 bindings execute batches through batch(), which opens no transaction VibORM can set an isolation level on\",\n timeout: false,\n timeoutReason:\n \"D1 bindings run a batch as one provider call with no interactive body to interrupt\",\n maxWait: \"unsupported\",\n maxWaitReason:\n \"D1 bindings submit the batch immediately with no connection to acquire\",\n };\n }\n\n protected transaction<T>(\n _client: D1Database | D1DatabaseSession,\n _fn: (tx: D1Database | D1DatabaseSession) => Promise<T>\n ): Promise<T> {\n return Promise.reject(unsupportedCallbackTransactionError(this.driverName));\n }\n\n /**\n * Execute multiple queries atomically using D1's native batch() API.\n * All queries succeed or all fail together.\n */\n protected async executeBatch<T>(\n client: D1Database | D1DatabaseSession,\n queries: BatchQuery[],\n context?: QueryExecutionContext,\n committed?: CommittedBatchNotification\n ): Promise<QueryResult<T>[]> {\n const batchContext = context ?? { operation: \"executeBatch\" };\n const statements: ReturnType<D1Database[\"prepare\"]>[] = [];\n for (const query of queries) {\n const statementContext = query.context ?? batchContext;\n try {\n const values = query.params ? convertD1Parameters(query.params) : [];\n statements.push(client.prepare(query.sql).bind(...values));\n } catch (error) {\n throw this.normalizeStatementFailure(\n error,\n query.sql,\n this.getBatchDiagnosticParameters(query),\n statementContext,\n true\n );\n }\n }\n\n // Execute all statements atomically\n const results: unknown = await client.batch<T>(statements);\n await committed?.();\n\n if (!Array.isArray(results) || results.length !== queries.length) {\n const actualResultCount = Array.isArray(results) ? results.length : 0;\n throw malformedD1Result(\n batchContext,\n `expected ${queries.length} statement results but received ${actualResultCount}`\n );\n }\n\n const normalized: QueryResult<T>[] = [];\n for (let index = 0; index < results.length; index += 1) {\n const query = queries[index];\n if (!query) {\n throw malformedD1Result(\n batchContext,\n `missing statement metadata at batch result index ${index}`\n );\n }\n normalized.push(\n normalizeD1Result<T>(\n results[index],\n query.sql,\n query.context ?? batchContext,\n false\n )\n );\n }\n return normalized;\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: D1ClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, D1DriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<C & { driver: D1Driver }>]: LinkedClientConfig<\n C & { driver: D1Driver }\n >[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"d1\", D1_CONFIG_KEYS);\n const { database } = config;\n\n const driver = new D1Driver({ database });\n\n return createClientFromDriverConfig<S, C, D1Driver>(config, driver);\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6B,EAAM,CACxC,EACA,GACD,EAKL,IAAM,EAAmB,MAAM,EAAO,MAAS,EAAW,CAG1D,GAFA,MAAM,KAAa,CAEf,CAAC,MAAM,QAAQ,EAAQ,EAAI,EAAQ,SAAW,EAAQ,OAAQ,CAChE,IAAM,EAAoB,MAAM,QAAQ,EAAQ,CAAG,EAAQ,OAAS,EACpE,MAAM,kBACJ,EACA,YAAY,EAAQ,OAAO,kCAAkC,IAC9D,CAGH,IAAM,EAA+B,EAAE,CACvC,IAAK,IAAI,EAAQ,EAAG,EAAQ,EAAQ,OAAQ,GAAS,EAAG,CACtD,IAAM,EAAQ,EAAQ,GACtB,GAAI,CAAC,EACH,MAAM,kBACJ,EACA,oDAAoD,IACrD,CAEH,EAAW,KACT,kBACE,EAAQ,GACR,EAAM,IACN,EAAM,SAAW,EACjB,GACD,CACF,CAEH,OAAO,IAQX,SAAgB,aACd,EAOC,CACD,EAA8B,EAAQ,KAAM,EAAe,CAC3D,GAAM,CAAE,YAAa,EAIrB,OAAO,EAA6C,EAFrC,IAAI,EAAS,CAAE,WAAU,CAAC,CAE0B"}
@@ -0,0 +1,2 @@
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{a as t,t as n}from"./value-guards-CK9guf2Z.mjs";import{d as r,f as i,p as a}from"./geo-point-codec-lhxH42SK.mjs";const o=864e5,s=2440587.5;function encodePostgresTemporal(e){return e.startsWith(`0000-`)?`0001${e.slice(4)} BC`:e}function physicalNumber(e){if(t(e))return Number.isFinite(e)?e:void 0;if(n(e)){let t=Number(e);return Number.isSafeInteger(t)?t:void 0}}function encodePhysicalDateTime(e,t){if(t===`text`)return e;let n=Date.parse(e);return t===`epochMillis`?n:n/o+s}function decodePhysicalDateTime(e,t){let n=physicalNumber(e);if(n===void 0)return;let r=t===`epochMillis`?n:Math.round((n-s)*o);if(i(r))return new Date(r)}const c=/^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?(?:(Z)|([+-])(\d{2})(?::?(\d{2}))?(?::?(\d{2}))?)?(?: (BC))?$/;function decodeProviderTimestamp(e){let t=c.exec(e);if(!t)return;let n=t[13]?1-Number(t[1]):Number(t[1]),o=Number(t[2]),s=Number(t[3]),l=Number(t[4]),u=Number(t[5]),d=Number(t[6]),f=Number(t[10]??0),p=Number(t[11]??0),m=Number(t[12]??0);if(!(a(n,o,s)&&r(l,u,d))||f>23||p>59||m>59)return;let h=new Date(0);h.setUTCFullYear(n,o-1,s),h.setUTCHours(l,u,d,Number((t[7]??``).padEnd(3,`0`).slice(0,3)));let g=(f*3600+p*60+m)*1e3,_=h.getTime()-(t[9]===`-`?-g:g);return i(_)?new Date(_):void 0}const encodeMySqlDateTime=e=>new Date(e).toISOString().slice(0,23).replace(`T`,` `);export{encodePostgresTemporal as a,encodePhysicalDateTime as i,decodeProviderTimestamp as n,encodeMySqlDateTime as r,decodePhysicalDateTime as t};
2
+ //# sourceMappingURL=datetime-physical-codec-oIhiYZEP.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"datetime-physical-codec-oIhiYZEP.mjs","names":[],"sources":["../src/validation/primitives/datetime-physical-codec.ts"],"sourcesContent":["/**\n * The ONE physical datetime codec.\n *\n * A datetime's LOGICAL value is an instant, and every layer above this one\n * spells it as a validated ISO-8601 string or a `Date`. Its PHYSICAL value is\n * whatever the column it lands in actually holds, and SQLite makes that a\n * DECLARED choice with three answers: timestamp TEXT, an INTEGER count of epoch\n * milliseconds, or a REAL Julian day. This module owns the conversion between\n * the two, so value lowering and result decoding cannot disagree about what a\n * column holds.\n *\n * The form is declared and never inferred, because a physical value cannot name\n * its own vocabulary: `2460324.9375` is 2024-01-15T10:30:00Z as a Julian day and\n * an instant in 1970 as milliseconds, and `1705314600000` is that same instant\n * as milliseconds and a date no calendar reaches as a Julian day.\n */\n\nimport { isBigInt, isNumber } from \"../value-guards\";\nimport {\n isDateTimeClock,\n isDateTimeInstant,\n isGregorianCalendarDate,\n} from \"./datetime-values\";\n\n/**\n * The three physical spellings a datetime column can hold.\n *\n * `text` is the timestamp text every dialect stores by default, and its\n * conversion is the identity — the ISO string IS the physical value. The other\n * two are numbers, and each has an exact arithmetic.\n */\nexport type DateTimePhysicalForm = \"text\" | \"epochMillis\" | \"julianDay\";\n\n/**\n * The two forms whose physical value is a NUMBER rather than timestamp text.\n *\n * Named separately because the decode entry accepts only these: the textual\n * grammar a provider timestamp is held to belongs to the result boundary that\n * already owns it for every dialect, and duplicating it here would give one\n * spelling two readers.\n */\nexport type DateTimeNumericForm = Exclude<DateTimePhysicalForm, \"text\">;\n\nconst MILLISECONDS_PER_DAY = 86_400_000;\n\n/** The Julian day of 1970-01-01T00:00:00Z, where the Unix epoch begins. */\nconst UNIX_EPOCH_JULIAN_DAY = 2_440_587.5;\n\n/** PostgreSQL uses historical years: the admitted ISO year 0000 is 1 BC. */\nexport function encodePostgresTemporal(iso: string): string {\n return iso.startsWith(\"0000-\") ? `0001${iso.slice(4)} BC` : iso;\n}\n\n/**\n * The number a provider returned for a numeric datetime column, or `undefined`\n * when it returned something else.\n *\n * `bigint` is admitted because the SQLite family reads INTEGER columns in a\n * BigInt mode so values past 2^53 survive — an epoch-millisecond column is read\n * through that same mode. Every public DateTime instant is a safe integer, so a\n * bigint that does not survive the round trip is already outside the domain and\n * is refused here rather than rounded into it.\n */\nfunction physicalNumber(value: unknown): number | undefined {\n if (isNumber(value)) return Number.isFinite(value) ? value : undefined;\n if (isBigInt(value)) {\n // `Number(bigint)` is exact for every magnitude below 2^53, so the safe\n // test alone decides survival — an unsafe result is already outside the\n // public DateTime domain and there is no second case to check.\n const asNumber = Number(value);\n return Number.isSafeInteger(asNumber) ? asNumber : undefined;\n }\n return undefined;\n}\n\n/**\n * The physical value one VALIDATED ISO-8601 timestamp lands in a column as.\n *\n * The ISO boundary (`validateIsoTimestamp`) already owns \"this string names an\n * instant\", and every value lowered here has crossed it. REAL/Julian storage\n * needs no second admission branch: every millisecond in the four-digit public\n * DateTime domain survives its Julian-day double round trip. Behavior on any\n * other string is unspecified rather than re-guarded — one guard per invariant.\n */\nexport function encodePhysicalDateTime(\n iso: string,\n form: DateTimePhysicalForm\n): string | number {\n if (form === \"text\") return iso;\n const epochMilliseconds = Date.parse(iso);\n return form === \"epochMillis\"\n ? epochMilliseconds\n : epochMilliseconds / MILLISECONDS_PER_DAY + UNIX_EPOCH_JULIAN_DAY;\n}\n\n/**\n * The instant one physical number holds, or `undefined` when the provider\n * returned a value this column's declared form cannot hold.\n *\n * A Julian day is a COUNT OF DAYS in a double, so its resolution near the\n * present is about fifty microseconds and a millisecond is not exactly\n * representable in it. The instant is therefore rounded to the nearest\n * millisecond — the same precision the logical value has — and then held to the\n * public four-digit instant range, so a day number outside the DateTime domain\n * is a malformed row rather than an extended-year `Date`.\n */\nexport function decodePhysicalDateTime(\n value: unknown,\n form: DateTimeNumericForm\n): Date | undefined {\n const physical = physicalNumber(value);\n if (physical === undefined) return undefined;\n const epochMilliseconds =\n form === \"epochMillis\"\n ? physical\n : Math.round((physical - UNIX_EPOCH_JULIAN_DAY) * MILLISECONDS_PER_DAY);\n if (!isDateTimeInstant(epochMilliseconds)) return undefined;\n return new Date(epochMilliseconds);\n}\n\nconst TIMESTAMP_TEXT =\n /^(\\d{4})-(\\d{2})-(\\d{2})[T ](\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d{1,6}))?(?:(Z)|([+-])(\\d{2})(?::?(\\d{2}))?(?::?(\\d{2}))?)?(?: (BC))?$/;\n\n/** The provider timestamp grammar; the domain rules are the codec's. */\nexport function decodeProviderTimestamp(value: string): Date | undefined {\n const match = TIMESTAMP_TEXT.exec(value);\n if (!match) return undefined;\n const year = match[13] ? 1 - Number(match[1]) : Number(match[1]);\n const month = Number(match[2]);\n const day = Number(match[3]);\n const hour = Number(match[4]);\n const minute = Number(match[5]);\n const second = Number(match[6]);\n const offsetHour = Number(match[10] ?? 0);\n const offsetMinute = Number(match[11] ?? 0);\n const offsetSecond = Number(match[12] ?? 0);\n if (\n !(\n isGregorianCalendarDate(year, month, day) &&\n isDateTimeClock(hour, minute, second)\n ) ||\n offsetHour > 23 ||\n offsetMinute > 59 ||\n offsetSecond > 59\n )\n return undefined;\n const parsed = new Date(0);\n // setUTCFullYear keeps years 0..99 literal; Date.UTC reinterprets them as 1900..1999.\n parsed.setUTCFullYear(year, month - 1, day);\n parsed.setUTCHours(\n hour,\n minute,\n second,\n Number((match[7] ?? \"\").padEnd(3, \"0\").slice(0, 3))\n );\n const offset = (offsetHour * 3600 + offsetMinute * 60 + offsetSecond) * 1000;\n const epoch = parsed.getTime() - (match[9] === \"-\" ? -offset : offset);\n return isDateTimeInstant(epoch) ? new Date(epoch) : undefined;\n}\n\n/** MySQL DATETIME stores the admitted instant as a naive UTC wall clock. */\nexport const encodeMySqlDateTime = (iso: string): string =>\n new Date(iso).toISOString().slice(0, 23).replace(\"T\", \" \");\n"],"mappings":"iKA2CA,MAAM,EAAuB,MAGvB,EAAwB,UAG9B,SAAgB,uBAAuB,EAAqB,CAC1D,OAAO,EAAI,WAAW,QAAQ,CAAG,OAAO,EAAI,MAAM,EAAE,CAAC,KAAO,EAa9D,SAAS,eAAe,EAAoC,CAC1D,GAAI,EAAS,EAAM,CAAE,OAAO,OAAO,SAAS,EAAM,CAAG,EAAQ,IAAA,GAC7D,GAAI,EAAS,EAAM,CAAE,CAInB,IAAM,EAAW,OAAO,EAAM,CAC9B,OAAO,OAAO,cAAc,EAAS,CAAG,EAAW,IAAA,IAcvD,SAAgB,uBACd,EACA,EACiB,CACjB,GAAI,IAAS,OAAQ,OAAO,EAC5B,IAAM,EAAoB,KAAK,MAAM,EAAI,CACzC,OAAO,IAAS,cACZ,EACA,EAAoB,EAAuB,EAcjD,SAAgB,uBACd,EACA,EACkB,CAClB,IAAM,EAAW,eAAe,EAAM,CACtC,GAAI,IAAa,IAAA,GAAW,OAC5B,IAAM,EACJ,IAAS,cACL,EACA,KAAK,OAAO,EAAW,GAAyB,EAAqB,CACtE,KAAkB,E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oXK.mjs";import{o as l}from"./execution-context-BKR3bgES.mjs";import{n as u}from"./v-D5Z06FKN.mjs";import{t as d}from"./clock-CK41KO7t.mjs";const f=`:reval`,p=3e4;function scheduleBackground(e,t){let n=e.catch(()=>void 0);if(t)try{t(n)}catch{}}const m={ms:1,millisecond:1,milliseconds:1,s:1e3,sec:1e3,second:1e3,seconds:1e3,m:60*1e3,min:60*1e3,minute:60*1e3,minutes:60*1e3,h:3600*1e3,hr:3600*1e3,hour:3600*1e3,hours:3600*1e3,d:1440*60*1e3,day:1440*60*1e3,days:1440*60*1e3,w:10080*60*1e3,week:10080*60*1e3,weeks:10080*60*1e3,month:720*60*60*1e3,months:720*60*60*1e3},h=Object.keys(m).join(`, `),g=/^(\d+(?:\.\d+)?)\s*([a-z]+)$/;function parseTTL(e){if(typeof e==`number`){if(!Number.isFinite(e)||e<=0||e>2**53-1)throw new n(`TTL must be positive, got: ${e}`);return e}let t=e.trim().toLowerCase().match(g);if(!t)throw new n(`Invalid TTL format: "${e}". Expected format: "<number> <unit>" (e.g., "1 hour", "20 seconds")`);let r=t[1],i=t[2],a=Number.parseFloat(r),o=m[i];if(o===void 0)throw new n(`Unknown time unit: "${i}". Valid units: ${h}`);let s=Math.floor(a*o);if(!Number.isSafeInteger(s)||s<=0)throw new n(`TTL must be positive, got: ${s}ms from "${e}"`);return s}const _=u.object({invalidate:u.string({array:!0,optional:!0}),autoInvalidate:u.boolean({optional:!0,default:!0})},{optional:!0,default:{autoInvalidate:!0}});function hasCacheInvalidationWork(e){return e===void 0||e.autoInvalidate===!0||e?.invalidate!==void 0&&e.invalidate.length>0}const v=300*1e3,y=u.object({ttl:u.coerce(u.optional(u.union([u.string(),u.number()]),v),e=>parseTTL(e)),swr:u.coerce(u.optional(u.union([u.boolean(),u.string(),u.number()])),e=>e===void 0||typeof e==`boolean`?e:parseTTL(e)),key:u.string({optional:!0}),bypass:u.boolean({optional:!0})},{optional:!0,default:{ttl:v,swr:!1,bypass:!1}});let executeCachedWithResultCodecFriend,invalidateOfficialCacheFriend;const b=new WeakMap,x=new WeakMap,completeWithoutFacts=()=>void 0;function createCacheOutcome(e,t,n){return{event:e,status:t,at:Date.now(),error:n}}function recordCacheOutcome(e,t,n,r){if(e===void 0||c(l(e))?.wants(`cache-outcomes`)!==!0)return;let i=x.get(e);i===void 0&&(i={outcomes:[],completed:!1},x.set(e,i)),i.outcomes.push(createCacheOutcome(t,n,r))}function placeCacheSetFailure(e,t){let n=createCacheOutcome(`miss`,`cache-set-failed`,t),r=x.get(e);if(r!==void 0&&!r.completed){r.outcomes.push(n);return}return Object.freeze({kind:`cache`,outcomes:[n]})}function readCacheExecutionOutcomes(e){let t=x.get(e);if(t!==void 0)return()=>(t.completed=!0,Object.freeze([...t.outcomes]))}function createOfficialCacheScope(e){let t=Object.freeze({});return b.set(t,e),t}function readOfficialCacheNamespace(e){let n=b.get(e);if(n===void 0)throw new t(`Official cache scope is not authentic for this cache execution.`);return n}function refuseExternalScope(e){if(e!==void 0)throw new t(`Cache driver methods do not accept an external cache scope.`)}var CacheDriver=class{#e=0;driverName;clock;static{executeCachedWithResultCodecFriend=(e,t,n,r,i,a,o,s)=>{let c=readOfficialCacheNamespace(s);return e.#t(t,n,r,i,a,o,c)},invalidateOfficialCacheFriend=(e,t,n,r,i)=>e.#d(t,n,r,readOfficialCacheNamespace(i))}constructor(e,t=d){this.driverName=e,this.clock=t}async#t(e,t,n,r,a,o,s){let c=i(e,t,n),l=`${c.key}${a.key===void 0?``:`:${a.key}`}`,u=JSON.stringify([c.identity,a.key]),d=this.#e,executeCore=async()=>{if(a.bypass){let e=await r();return this.#r(l,e,a,o,s,u,d),recordCacheOutcome(a.executionContext,`bypass`),e}let n=await this.#n(l,a.executionContext,s,o,u);if(n){let i=this.clock.now()-n.createdAt;if(!(i>=n.ttl))return recordCacheOutcome(a.executionContext,`hit`),n.value;let c=a.swr;if(c!==!1&&i<c&&(n.expiresAt===void 0||this.clock.now()<n.expiresAt))return scheduleBackground(this.#a(e,t,l,r,a,c,o,s,u,d),a.waitUntil),recordCacheOutcome(a.executionContext,`hit`,`stale`),n.value}let i=await r();return this.#r(l,i,a,o,s,u,d),recordCacheOutcome(a.executionContext,`miss`),i};return executeCore()}async#n(e,t,n,r,i){let a=await this.#s(e,t,n);return a===null||a.identity!==i||!Number.isFinite(a.createdAt)||!Number.isFinite(a.ttl)||a.ttl<=0||a.expiresAt===void 0||!Number.isFinite(a.expiresAt)||a.expiresAt<a.createdAt?null:{createdAt:a.createdAt,ttl:a.ttl,expiresAt:a.expiresAt,value:r.materialize(a.value)}}#r(e,t,n,r,i,a,o){if(o!==this.#e)return;let s;try{s=r.snapshot(t)}catch(e){recordCacheOutcome(n.executionContext,`miss`,`cache-set-failed`,e);return}this.#i(e,s,n,i,a,o)}#i(e,t,n,r,i,a){scheduleBackground(this.#c(e,t,{ttl:n.ttlMs,swrTtl:n.swr===!1?void 0:n.swr},n.executionContext,r,n.executionContext,i,a).catch(()=>void 0),n.waitUntil)}async#a(e,t,n,r,i,a,s,c,u,d){let f;try{f=await this.#l(n,c)}catch{return}if(!f)return;let p=l(i.executionContext)?.observe,m=p===void 0||p.length===0?void 0:{failed:!1,error:void 0},h,doRevalidate=async()=>{let e;try{let t=await r(),o=s.snapshot(t);await this.#c(n,o,{ttl:i.ttlMs,swrTtl:a},i.executionContext,c,void 0,u,d),e=createCacheOutcome(`revalidate`,`success`)}catch(t){m!==void 0&&(m.failed=!0,m.error=t),e=createCacheOutcome(`revalidate`,`error`,t)}finally{if(m===void 0)await this.#u(n,c).catch(()=>void 0);else try{await this.#u(n,c)}catch(e){if(m.failed){let t=m.error;m.error=AggregateError([t,e],`Cache revalidation work and cleanup both failed.`,{cause:t})}else m.failed=!0,m.error=e}}return e};await(m===void 0?doRevalidate():o({kind:`cache`,operation:`revalidate`},p,async()=>{if(h=Object.freeze({kind:`cache`,outcomes:[await doRevalidate()]}),m.failed)throw m.error},void 0,()=>Object.freeze({kind:`cache`,context:i.executionContext,read:Object.freeze({model:e,operation:t,identity:i.driverIdentity}),complete:()=>h})))}#o(e,t,n,r=completeWithoutFacts,i){let a=l(t)?.observe;if(a===void 0||a.length===0)return n();let c=e===`clear`||e===`delete`;return o({kind:`cache`,operation:c?`invalidate`:e},c?s(a):a,n,void 0,()=>Object.freeze(c?{kind:`cache-backend`,boundary:e,driverName:this.driverName,complete:completeWithoutFacts}:{kind:`cache`,context:t,driverName:this.driverName,...i===void 0?{}:{ttl:i},complete:r}))}async _get(e,t,n){return refuseExternalScope(n),this.#s(e,t)}async#s(e,t,n){let r=this.#m(e,n),i;return this.#o(`get`,t,async()=>{let e=await this.get(r);return i=e?this.clock.now()-e.createdAt>e.ttl?`stale`:`hit`:`miss`,e},()=>i===void 0?void 0:Object.freeze({kind:`cache`,result:i}))}async _set(e,t,n,r,i){return refuseExternalScope(i),this.#c(e,t,n,r)}async#c(e,t,n,r,i,a,o,s){if(s!==void 0&&s!==this.#e)return;let c=this.#m(e,i),l={value:t,createdAt:this.clock.now(),ttl:n.ttl,...o===void 0?{}:{identity:o,expiresAt:this.clock.now()+(n.swrTtl??n.ttl)}},u=n.swrTtl??n.ttl;return this.#o(`set`,r,async()=>{await this.set(c,u,l),s!==void 0&&s!==this.#e&&await this.delete([c])},a===void 0?void 0:e=>e.status===`failure`?placeCacheSetFailure(a,e.failure):void 0,n.ttl)}async _delete(e,t,n){refuseExternalScope(n);let r=this.#m(e);return this.#f(r,t)}async _clear(e,t,n){refuseExternalScope(n);let r=this.#m(e??``);return this.#p(r,t)}async _markRevalidating(e,t){return refuseExternalScope(t),this.#l(e)}async#l(e,t){let n=`${this.#m(e,t)}${f}`,r=await this.get(n);if(r&&this.clock.now()-r.createdAt<r.ttl)return!1;let i={value:!0,createdAt:this.clock.now(),ttl:p};return await this.set(n,p,i),!0}async _clearRevalidating(e,t){return refuseExternalScope(t),this.#u(e)}async#u(e,t){let n=`${this.#m(e,t)}${f}`;await this.delete([n])}async _invalidate(e,t,n,r){return refuseExternalScope(r),this.#d(e,t,n)}async#d(e,t,n,r){if(!hasCacheInvalidationWork(t))return;this.#e+=1;let i=[];if((t===void 0||t.autoInvalidate===!0)&&i.push({kind:`clear`,prefixedKey:this.#m(r===void 0?`${e}:`:``,r)}),t?.invalidate)for(let e of t.invalidate){let t=e.endsWith(`*`),n=t?e.slice(0,-1):e;i.push({kind:t?`clear`:`delete`,prefixedKey:this.#m(n,r)})}return this.#o(`invalidate`,n,async()=>{let e=[];for(let t of i)e.push(t.kind===`clear`?this.#p(t.prefixedKey,n):this.#f(t.prefixedKey,n));await Promise.all(e)})}#f(e,t){this.#e+=1;let n=[e,`${e}${f}`];return this.#o(`delete`,t,()=>this.delete(n))}#p(e,t){return this.#e+=1,this.#o(`clear`,t,()=>this.clear(e))}#m(e,n){if(n!==void 0){if(e.startsWith(`${a}:`))throw new t(`Official cache keys and prefixes must be relative and cannot begin with 'viborm:'.`);return`${n}:${e}`}let i=e.startsWith(`${a}:`)?e:e?`${a}:${e}`:a;if(i===r||i.startsWith(`${r}:`))throw new t(`The official cache namespace requires an authenticated cache extension.`);return i}};function executeCachedWithResultCodec(e,t,n,r,i,a,o,s){return executeCachedWithResultCodecFriend(e,t,n,r,i,a,o,s)}function invalidateOfficialCache(e,t,n,r,i){return invalidateOfficialCacheFriend(e,t,n,r,i)}export{readCacheExecutionOutcomes as a,invalidateOfficialCache as i,createOfficialCacheScope as n,_ as o,executeCachedWithResultCodec as r,y as s,CacheDriver as t};
2
+ //# sourceMappingURL=driver-B19QlFqn.mjs.map