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
@@ -1,2 +0,0 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{C as t,T as n,f as r,t as i}from"./validation-Du6j0Q38.mjs";import{b as a,t as o}from"./base-vfur-DaU.mjs";import{a as s}from"./key-DKaqPb8w.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)}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 o}catch{return!1}}function invalidControl(e,t,n,r){return new i({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 r(`${e}.`,{cause:a(i)?i:Error(`A non-Error value was thrown.`,{cause:i}),meta:{model:t,operation:n}})}export{officialCacheRuntime as _,rowsModes as a,setOfficialCacheChainCapability as b,isWriteOperation as c,getOfficialCacheChainCapability as d,getOfficialCacheChainDefinition as f,l as g,isCacheManagedExecution as h,placeControls as i,c as l,installOfficialCacheRuntime as m,controlsOwnedBy as n,h as o,getOfficialCacheQueryCapability as p,isStableControlValue as r,isReadOperation as s,admitControls as t,bindOfficialCacheChain as u,registerOfficialCacheChain as v,registerOfficialCacheQuery as y};
2
- //# sourceMappingURL=controls-BhxRnPYS.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"controls-BhxRnPYS.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","/**\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","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 { isError } 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: isError(cause)\n ? cause\n : new Error(\"A non-Error value was thrown.\", { cause }),\n meta: { model, operation },\n });\n}\n"],"mappings":"kMAmBA,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,EAAW,EAAM,CAAG,EAAoB,IAAI,EAAM,CAAG,IAAA,GAS9D,SAAgB,gCACd,EAC+C,CAC/C,OAAO,IAAU,IAAA,GAAY,IAAA,GAAY,EAAmB,IAAI,EAAM,CAIxE,SAAgB,gCACd,EACqC,CACrC,OAAO,IAAU,IAAA,GAAY,IAAA,GAAY,EAAoB,IAAI,EAAM,CAGzE,SAAgB,2BACd,EACA,EACM,CACN,EAAmB,IAAI,EAAO,EAAW,CAI3C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M,QAAU,IAAA,GAClD,EAAS,KAAK,OAAO,GAAY,SAAW,EAAU,aAAa,OAE/D,CACN,MAAO,CAAC,aAAa,CAEvB,OAAO,EAAS,SAAW,EAAI,CAAC,aAAa,CAAG,EAIlD,SAAS,gBAAgB,EAAsC,CAC7D,GAAI,CACF,OAAO,aAAiB,OAClB,CACN,MAAO,IAIX,SAAS,eACP,EACA,EACA,EACA,EACiB,CACjB,OAAO,IAAI,EACT,CAAE,KAAM,YAAa,YAAW,QAAO,CACvC,EAAS,IAAK,IAAa,CACzB,KAAM,EAAQ,KACd,QAAS,YAAY,EAAQ,KAAK,IAAI,IACvC,EAAE,CACH,CAAE,KAAM,CAAE,QAAO,UAAW,EAAQ,UAAW,CAAE,CAClD,CAGH,SAAS,iBACP,EACA,EACA,EACA,EACA,EACY,CACZ,OAAO,eACL,cAAc,EAAQ,UAAU,aAAa,EAAQ,KAAK,kBAAkB,EAAM,GAAG,EAAU,GAAG,IAClG,EACA,EACA,EACD,CAGH,SAAS,eACP,EACA,EACA,EACA,EACY,CACZ,OAAO,IAAI,EAAW,GAAG,EAAQ,GAAI,CACnC,MAAO,EAAQ,EAAM,CACjB,EACI,MAAM,gCAAiC,CAAE,QAAO,CAAC,CACzD,KAAM,CAAE,QAAO,YAAW,CAC3B,CAAC"}
@@ -1,3 +0,0 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-vfur-DaU.mjs";import{t as n}from"./migrations-BWZSBMZh.mjs";import{D as r,E as i,N as a,l as o,u as s,v as c}from"./geo-point-codec-DUTTtlav.mjs";import{t as l}from"./identifiers-By-JRCb5.mjs";function decimalDialectOf(e){return e===`postgresql`?`pg`:e===`mysql`?`mysql`:`sqlite`}function findDecimalProviderLimitRefusal(e,t){let n=decimalDialectOf(t);for(let[i,a]of Object.entries(e)){let e=a[`~`].state.scalars;for(let[a,o]of Object.entries(e)){let e=o[`~`].state;if(e.type!==`decimal`||e.decimal===void 0)continue;let s=r(n,e.decimal);if(s!==void 0)return{modelName:i,fieldName:a,dialect:t,descriptor:e.decimal,reason:s}}}}function describeDecimalProviderLimitRefusal(e){return`Decimal field '${e.modelName}.${e.fieldName}' cannot be stored by the '${e.dialect}' driver: ${e.reason}.`}const u=864e5,d=2440587.5,f=`-9223372036854775808`,p=`[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]`,m=`[0-9][0-9]:[0-9][0-9]:[0-9][0-9]`,h=`[+-][0-9][0-9]:[0-9][0-9]`,g=[`${p}T${m}Z`,`${p}T${m}.[0-9]Z`,`${p}T${m}.[0-9][0-9]Z`,`${p}T${m}.[0-9][0-9][0-9]Z`,`${p}T${m}${h}`,`${p}T${m}.[0-9]${h}`,`${p}T${m}.[0-9][0-9]${h}`,`${p}T${m}.[0-9][0-9][0-9]${h}`];function sqliteDateTimeTargetRequiresRecreation(e,t){return t!==void 0&&e!==t}function roundToInteger(e){let t=`CAST(${e} AS INTEGER)`,n=`(${e} - ${t})`;return`(${t} + CASE WHEN ${n} >= 0.5 THEN 1 WHEN ${n} < -0.5 THEN -1 ELSE 0 END)`}function julianToEpochMilliseconds(e){return roundToInteger(`((${e} - ${d}) * ${u})`)}function epochMillisecondsToJulian(e){return`((${e} / ${u}.0) + ${d})`}function textFractionMilliseconds(e){return`(CASE WHEN substr(${e}, 20, 1) <> '.' THEN 0 ELSE ${`CAST(substr(${e}, 21, 1) AS INTEGER)`} * 100 + CASE WHEN substr(${e}, 22, 1) GLOB '[0-9]' THEN ${`CAST(substr(${e}, 22, 1) AS INTEGER)`} * 10 + CASE WHEN substr(${e}, 23, 1) GLOB '[0-9]' THEN ${`CAST(substr(${e}, 23, 1) AS INTEGER)`} ELSE 0 END ELSE 0 END END)`}function textOffsetMilliseconds(e){let t=`((CAST(substr(${e}, -5, 2) AS INTEGER) * 60 + CAST(substr(${e}, -2, 2) AS INTEGER)) * 60000)`;return`(CASE WHEN substr(${e}, -1, 1) = 'Z' THEN 0 WHEN substr(${e}, -6, 1) = '+' THEN ${t} ELSE -${t} END)`}function textToEpochMilliseconds(e){return`(${`(${julianToEpochMilliseconds(`julianday(substr(${e}, 1, 10) || 'T00:00:00Z')`)} + CAST(substr(${e}, 12, 2) AS INTEGER) * 3600000 + CAST(substr(${e}, 15, 2) AS INTEGER) * 60000 + CAST(substr(${e}, 18, 2) AS INTEGER) * 1000 + ${textFractionMilliseconds(e)})`} - ${textOffsetMilliseconds(e)})`}function epochMillisecondsToText(e){return`(strftime('%Y-%m-%dT%H:%M:%S', ${`(CASE WHEN ${e} < 0 AND ${e} % 1000 <> 0 THEN ${e} / 1000 - 1 ELSE ${e} / 1000 END)`}, 'unixepoch') || printf('.%03dZ', ${`(((${e} % 1000) + 1000) % 1000)`}))`}function epochMilliseconds(e,t){return t===`epochMillis`?e:t===`julianDay`?julianToEpochMilliseconds(e):textToEpochMilliseconds(e)}function isIsoTimestamp(e){return`(${g.map(t=>`${e} GLOB '${t}'`).join(` OR `)})`}function isAdmittedIsoTimestamp(e){let t=`CAST(substr(${e}, 1, 4) AS INTEGER)`,n=`CAST(substr(${e}, 6, 2) AS INTEGER)`,r=`CAST(substr(${e}, 9, 2) AS INTEGER)`,i=`CAST(substr(${e}, 12, 2) AS INTEGER)`,a=`CAST(substr(${e}, 15, 2) AS INTEGER)`,o=`CAST(substr(${e}, 18, 2) AS INTEGER)`,s=`substr(${e}, -1, 1) = 'Z'`,c=`CAST(substr(${e}, -5, 2) AS INTEGER)`,l=`CAST(substr(${e}, -2, 2) AS INTEGER)`,u=`(CASE ${n} WHEN 2 THEN CASE WHEN ${`(${t} % 4 = 0 AND (${t} % 100 <> 0 OR ${t} % 400 = 0))`} THEN 29 ELSE 28 END WHEN 4 THEN 30 WHEN 6 THEN 30 WHEN 9 THEN 30 WHEN 11 THEN 30 ELSE 31 END)`;return`${isIsoTimestamp(e)} AND ${n} BETWEEN 1 AND 12 AND ${r} BETWEEN 1 AND ${u} AND ${i} BETWEEN 0 AND 23 AND ${a} BETWEEN 0 AND 59 AND ${o} BETWEEN 0 AND 59 AND (${s} OR (${c} BETWEEN 0 AND 23 AND ${l} BETWEEN 0 AND 59)) AND julianday(substr(${e}, 1, 10) || 'T00:00:00Z') IS NOT NULL`}function sourceIsExact(e,t,n){return t===`text`?`typeof(${e}) = 'text' AND ${isAdmittedIsoTimestamp(e)} AND ${n} BETWEEN ${s} AND ${o}`:t===`epochMillis`?`typeof(${e}) = 'integer' AND ${n} BETWEEN ${s} AND ${o}`:`typeof(${e}) = 'real' AND ${n} BETWEEN ${s} AND ${o} AND ${epochMillisecondsToJulian(n)} = ${e}`}function targetValue(e,t){return t===`text`?epochMillisecondsToText(e):t===`epochMillis`?e:epochMillisecondsToJulian(e)}function targetIsExact(e,t,n){return t===`text`?`${n} IS NOT NULL AND ${isIsoTimestamp(n)}`:t===`epochMillis`?`1`:`${julianToEpochMilliseconds(n)} = ${e}`}function sqliteDateTimeCopyExpression(e,t,n,r){if(t===n&&r)return e;let i=epochMilliseconds(e,t),a=t===n?e:targetValue(i,n);return`CASE WHEN ${e} IS NULL THEN NULL WHEN ${t===n?sourceIsExact(e,t,i):`${sourceIsExact(e,t,i)} AND ${targetIsExact(i,n,a)}`} THEN ${a} ELSE abs(${f}) END`}function sqliteCanonicalDateTimeExpression(e){let t=l(`"`)(e),n=textToEpochMilliseconds(t),r=epochMillisecondsToText(n);return`CASE WHEN ${t} IS NULL THEN NULL WHEN ${sourceIsExact(t,`text`,n)} AND ${targetIsExact(n,`text`,r)} THEN ${r} ELSE abs(${f}) END`}function timeSource(e){return{valid:`typeof(${e}) = 'text' AND (${[m,`${m}.[0-9]`,`${m}.[0-9][0-9]`,`${m}.[0-9][0-9][0-9]`].map(t=>`${e} GLOB '${t}'`).join(` OR `)}) AND CAST(substr(${e},1,2) AS INTEGER) BETWEEN 0 AND 23 AND CAST(substr(${e},4,2) AS INTEGER) BETWEEN 0 AND 59 AND CAST(substr(${e},7,2) AS INTEGER) BETWEEN 0 AND 59`,value:`substr(${e},1,8) || '.' || substr(CASE WHEN length(${e}) = 8 THEN '000' ELSE substr(${e},10) || '000' END,1,3)`}}function sqliteCanonicalTimeExpression(e){let t=l(`"`)(e),{valid:n,value:r}=timeSource(t);return`CASE WHEN ${t} IS NULL THEN NULL WHEN ${n} THEN ${r} ELSE abs(${f}) END`}function sqliteCanonicalDateTimePredicate(e){let t=l(`"`)(e),n=textToEpochMilliseconds(t),r=epochMillisecondsToText(n);return`CASE WHEN ${t} IS NULL THEN 1 WHEN ${sourceIsExact(t,`text`,n)} AND ${targetIsExact(n,`text`,r)} AND ${t} = ${r} THEN 1 ELSE 0 END`}function sqliteCanonicalTimePredicate(e){let t=l(`"`)(e),{valid:n,value:r}=timeSource(t);return`CASE WHEN ${t} IS NULL THEN 1 WHEN ${n} AND ${t} = ${r} THEN 1 ELSE 0 END`}const _={'"':`"`,"`":"`","[":`]`},v=/[A-Za-z0-9_$]/,y=/\s/;function isSqliteBareIdentifierCharacter(e){return v.test(e)}function readSqliteIdentifier(e,t){let n=t;for(;n<e.length;){for(;n<e.length&&y.test(e.charAt(n));)n++;if(!(e[n]===`-`&&e[n+1]===`-`||e[n]===`/`&&e[n+1]===`*`))break;n=skipSqlNonStructuralRegion(e,n)}let r=e[n];if(r===void 0)return;let i=_[r];if(i!==void 0){let t=``;for(n++;n<e.length;){if(e[n]===i){if(e[n+1]===i&&i!==`]`){t+=i,n+=2;continue}return{value:t,quoted:!0,end:n+1}}t+=e[n],n++}return}let a=n;for(;n<e.length&&isSqliteBareIdentifierCharacter(e.charAt(n));)n++;if(n!==a)return{value:e.slice(a,n),quoted:!1,end:n}}function skipSqlNonStructuralRegion(e,t){let n=e[t];if(n===void 0)return t;if(n===`-`&&e[t+1]===`-`){let n=e.indexOf(`
2
- `,t+2);return n===-1?e.length:n}if(n===`/`&&e[t+1]===`*`){let n=e.indexOf(`*/`,t+2);return n===-1?e.length:n+2}let r=n===`'`?`'`:_[n];if(r===void 0)return t;let i=t+1;for(;i<e.length;){if(e[i]===r){if(e[i+1]===r&&r!==`]`){i+=2;continue}return i+1}i++}return e.length}const b=new Set([`CONSTRAINT`,`PRIMARY`,`UNIQUE`,`CHECK`,`FOREIGN`]);function sqliteTableDefinitions(e){let t=-1,n=0;for(;n<e.length;){let r=skipSqlNonStructuralRegion(e,n);if(r!==n){n=r;continue}if(e[n]===`(`){t=n;break}n++}if(t===-1)return[];let r=[],i=1,a=t+1,o=a;for(;o<e.length;){let t=skipSqlNonStructuralRegion(e,o);if(t!==o){o=t;continue}let n=e[o];if(n===`(`)i++;else if(n===`)`){if(i--,i===0)break}else n===`,`&&i===1&&(r.push(describeDefinition(e.slice(a,o))),a=o+1);o++}return r.push(describeDefinition(e.slice(a,o))),r}function describeDefinition(e){let t=e.trim(),n=readSqliteIdentifier(t,0);return n===void 0?{text:t,columnName:void 0}:n.quoted?{text:t,columnName:n.value}:{text:t,columnName:b.has(n.value.toUpperCase())?void 0:n.value}}function sqliteConstraintClauses(e){let t=[],n=0,r=0;for(;r<e.length;){let i=skipSqlNonStructuralRegion(e,r);if(i!==r){r=i;continue}let a=e.charAt(r),o=isSqliteBareIdentifierCharacter(a)?readSqliteIdentifier(e,r):void 0;if(o!==void 0){if(n===0&&o.value.toUpperCase()===`CONSTRAINT`){let n=readSqliteIdentifier(e,o.end);if(n){t.push({name:n.value,offset:r}),r=n.end;continue}}r=o.end;continue}a===`(`?n++:a===`)`&&n--,r++}return t}function sqliteDefinitionKeywords(e){let t=[],n=0,r=0;for(;r<e.length;){let i=skipSqlNonStructuralRegion(e,r);if(i!==r){r=i;continue}let a=readSqliteIdentifier(e,r);if(a&&!a.quoted){n===0&&t.push(a.value.toUpperCase()),r=a.end;continue}e[r]===`(`?n++:e[r]===`)`&&n--,r++}return t}function sqliteDecimalStorageKind(e){if(e.decimal===void 0)return;let t=e.type.toUpperCase();return t===c(`sqlite`,e.decimal)?`scalar`:t===`TEXT`?`list`:void 0}function sqliteDecimalConstraintName(e,t){return`viborm_decimal_${e}_${t.precision}_${t.scale}`}const x=`viborm_decimal_`,S=/^(\d+)_(\d+)$/;function readSqliteDecimalConstraint(e,r,a){if(!e||!e.includes(x))return;let o;for(let s of sqliteTableDefinitions(e))for(let e of sqliteConstraintClauses(s.text)){if(!e.name.startsWith(x)||s.columnName!==void 0&&s.columnName!==r.name)continue;let c=ownedDescriptor(s,e,r,a);if(c===void 0)throw new n(`The stored definition carries a constraint named "${e.name}", which is inside the namespace VibORM reserves for the fixed-decimal descriptor it writes itself, but it is not a constraint VibORM wrote. A reserved constraint is the ONLY place a SQLite column's declared precision and scale survive — the storage class is INTEGER or TEXT at every domain — so reading this one as a descriptor would plan conversions between domains the schema never declared, and ignoring it would re-plan the same alteration on every push. Rename or drop the constraint, or restore the definition VibORM wrote for this column.`,t.INVALID_INPUT,{meta:{constraint:e.name,...s.columnName===void 0?{}:{column:s.columnName}}});if(o!==void 0)throw new n(`The stored definition carries more than one fixed-decimal descriptor for column "${r.name}": ${i(o)} and ${i(c)}. One physical column can have only one logical decimal domain, so introspection refuses the ambiguous reserved carriers instead of choosing one by order.`,t.INVALID_INPUT,{meta:{column:r.name}});o=c}return o}function ownedDescriptor(e,t,n,r){let i=e.columnName;if(i===void 0)return;let o=`${x}${i}_`;if(!t.name.startsWith(o))return;let s=S.exec(t.name.slice(o.length));if(!s)return;let c=a(s[1],s[2],`sqlite`);if(c===void 0)return;let l=sqliteDecimalStorageKind({...n,decimal:c});if(l===void 0)return;let u=sqliteDecimalCheck(n,c,l,r);if(e.text.startsWith(u,t.offset))return c}function maxCoefficient(e){return 10n**BigInt(e)-1n}function sqliteDecimalCheck(e,t,n,r){let i=r(e.name),a=r(sqliteDecimalConstraintName(e.name,t)),o=maxCoefficient(t.precision).toString(),s=n===`list`?`typeof(${i}) = 'text' AND json_valid(${i}) AND json_type(${i}) = 'array'`:`typeof(${i}) = 'integer' AND ${i} BETWEEN -${o} AND ${o}`;return`CONSTRAINT ${a} CHECK (${e.nullable?`${i} IS NULL OR (${s})`:s})`}const C=`'viborm:decimal-list-out-of-domain'`;function rescale(e,t){let n=maxCoefficient(t.precision),r=e?maxCoefficient(e.precision):n,i=t.scale-(e?.scale??0);if(i===0)return{factor:`1`,direction:`none`,bound:min(r,n).toString()};if(i>0){let e=10n**BigInt(i);return{factor:e.toString(),direction:`up`,bound:min(r,n/e).toString()}}let a=10n**BigInt(-i);return{factor:a.toString(),direction:`down`,bound:min(r,n*a).toString()}}function min(e,t){return e<t?e:t}function sqliteDecimalCopyExpression(e,t,n,r){let{factor:i,direction:a,bound:o}=rescale(t,n),s=a===`down`?` AND ${e} % ${i} = 0`:``;return r===`scalar`?`CASE WHEN ${e} IS NULL THEN NULL WHEN typeof(${e}) = 'integer' AND ${e} BETWEEN -${o} AND ${o}${s} THEN ${convertedCoefficient(e,a,i)} ELSE 'viborm:decimal-out-of-domain' END`:listCopyExpression(e,a,i,o)}function convertedCoefficient(e,t,n){return t===`up`?`${e} * ${n}`:t===`down`?`${e} / ${n}`:e}function listCopyExpression(e,t,n,r){let i=`"m"."value"`,a=`CAST(${i} AS INTEGER)`;return`CASE WHEN ${e} IS NULL THEN NULL WHEN typeof(${e}) = 'text' AND json_valid(${e}) = 1 THEN CASE WHEN json_type(${e}) = 'array' THEN CASE WHEN (SELECT count(*) FROM json_each(${e}) AS "m" WHERE NOT (${`"m"."type" = 'text' AND CAST(${a} AS TEXT) = ${i} AND ${a} BETWEEN -${r} AND ${r}${t===`down`?` AND ${a} % ${n} = 0`:``}`})) = 0 THEN (SELECT json_group_array(${`CAST(${convertedCoefficient(`CAST("value" AS INTEGER)`,t,n)} AS TEXT)`}) FROM (SELECT "value" FROM json_each(${e}) AS "m" ORDER BY "m"."key")) ELSE ${C} END ELSE ${C} END ELSE ${C} END`}export{sqliteConstraintClauses as a,skipSqlNonStructuralRegion as c,sqliteCanonicalTimeExpression as d,sqliteCanonicalTimePredicate as f,findDecimalProviderLimitRefusal as g,describeDecimalProviderLimitRefusal as h,sqliteDecimalStorageKind as i,sqliteCanonicalDateTimeExpression as l,sqliteDateTimeTargetRequiresRecreation as m,sqliteDecimalCheck as n,sqliteDefinitionKeywords as o,sqliteDateTimeCopyExpression as p,sqliteDecimalCopyExpression as r,sqliteTableDefinitions as s,readSqliteDecimalConstraint as t,sqliteCanonicalDateTimePredicate as u};
3
- //# sourceMappingURL=decimal-12NERGYZ.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"decimal-12NERGYZ.mjs","names":["epochMilliseconds","factor"],"sources":["../src/schema/scalars/decimal/provider-limits.ts","../src/adapters/databases/sqlite/storage/datetime.ts","../src/adapters/databases/sqlite/storage/sql-lexing.ts","../src/adapters/databases/sqlite/storage/column-constraints.ts","../src/adapters/databases/sqlite/storage/decimal.ts"],"sourcesContent":["/**\n * The ONE schema-plus-provider fixed-decimal admission decision.\n *\n * A decimal descriptor is a valid schema fact independently of provider\n * limits. The first boundary that combines a complete model map with a chosen\n * provider asks this pure owner whether every declared scalar or list fits.\n * It returns one structured refusal and performs no boundary-specific throw;\n * client and migration composition roots retain their own error classes.\n */\n\nimport type { AnyModel } from \"@schema/model\";\nimport type { Scalar } from \"@schema/scalars/base\";\nimport {\n type DecimalDescriptor,\n type DecimalDialect,\n describeProviderLimitRefusal,\n} from \"@validation/primitives/decimal-codec\";\n\ntype ProviderDialect = \"postgresql\" | \"mysql\" | \"sqlite\";\n\nexport interface DecimalProviderLimitRefusal {\n readonly modelName: string;\n readonly fieldName: string;\n readonly dialect: ProviderDialect;\n readonly descriptor: DecimalDescriptor;\n readonly reason: string;\n}\n\n/** The driver's dialect in the decimal codec's physical vocabulary. */\nfunction decimalDialectOf(dialect: ProviderDialect): DecimalDialect {\n if (dialect === \"postgresql\") return \"pg\";\n if (dialect === \"mysql\") return \"mysql\";\n return \"sqlite\";\n}\n\n/** Return the first declared decimal domain the selected provider cannot hold. */\nexport function findDecimalProviderLimitRefusal(\n schema: Record<string, AnyModel>,\n dialect: ProviderDialect\n): DecimalProviderLimitRefusal | undefined {\n const decimalDialect = decimalDialectOf(dialect);\n for (const [modelName, model] of Object.entries(schema)) {\n const scalars: Record<string, Scalar> = model[\"~\"].state.scalars;\n for (const [fieldName, scalar] of Object.entries(scalars)) {\n const state = scalar[\"~\"].state;\n if (state.type !== \"decimal\" || state.decimal === undefined) continue;\n const reason = describeProviderLimitRefusal(\n decimalDialect,\n state.decimal\n );\n if (reason === undefined) continue;\n return {\n modelName,\n fieldName,\n dialect,\n descriptor: state.decimal,\n reason,\n };\n }\n }\n return undefined;\n}\n\n/** The shared diagnostic body; each composition root chooses its error model. */\nexport function describeDecimalProviderLimitRefusal(\n refusal: DecimalProviderLimitRefusal\n): string {\n return `Decimal field '${refusal.modelName}.${refusal.fieldName}' cannot be stored by the '${refusal.dialect}' driver: ${refusal.reason}.`;\n}\n","import type { DateTimePhysicalForm } from \"@validation/primitives/datetime-physical-codec\";\nimport {\n MAX_DATETIME_EPOCH_MILLISECONDS,\n MIN_DATETIME_EPOCH_MILLISECONDS,\n} from \"@validation/primitives/datetime-values\";\nimport { createIdentifierQuoter } from \"../../../../sql/identifiers\";\n\nconst MILLISECONDS_PER_DAY = 86_400_000;\nconst UNIX_EPOCH_JULIAN_DAY = 2_440_587.5;\n/** SQL literals mirroring the public four-digit UTC DateTime domain. */\nconst SQLITE_MIN_INTEGER = \"-9223372036854775808\";\n\nconst ISO_DATE = \"[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]\";\nconst ISO_TIME = \"[0-9][0-9]:[0-9][0-9]:[0-9][0-9]\";\nconst ISO_OFFSET = \"[+-][0-9][0-9]:[0-9][0-9]\";\nconst ISO_TIMESTAMP_SHAPES = [\n `${ISO_DATE}T${ISO_TIME}Z`,\n `${ISO_DATE}T${ISO_TIME}.[0-9]Z`,\n `${ISO_DATE}T${ISO_TIME}.[0-9][0-9]Z`,\n `${ISO_DATE}T${ISO_TIME}.[0-9][0-9][0-9]Z`,\n `${ISO_DATE}T${ISO_TIME}${ISO_OFFSET}`,\n `${ISO_DATE}T${ISO_TIME}.[0-9]${ISO_OFFSET}`,\n `${ISO_DATE}T${ISO_TIME}.[0-9][0-9]${ISO_OFFSET}`,\n `${ISO_DATE}T${ISO_TIME}.[0-9][0-9][0-9]${ISO_OFFSET}`,\n];\n\nexport function sqliteDateTimeTargetRequiresRecreation(\n from: DateTimePhysicalForm | undefined,\n to: DateTimePhysicalForm | undefined\n): boolean {\n return to !== undefined && from !== to;\n}\n\n/** SQLite spelling of JavaScript's `Math.round`, including negative halves. */\nfunction roundToInteger(expression: string): string {\n const integer = `CAST(${expression} AS INTEGER)`;\n const fraction = `(${expression} - ${integer})`;\n return (\n `(${integer} + CASE ` +\n `WHEN ${fraction} >= 0.5 THEN 1 ` +\n `WHEN ${fraction} < -0.5 THEN -1 ELSE 0 END)`\n );\n}\n\nfunction julianToEpochMilliseconds(julianDay: string): string {\n return roundToInteger(\n `((${julianDay} - ${UNIX_EPOCH_JULIAN_DAY}) * ${MILLISECONDS_PER_DAY})`\n );\n}\n\nfunction epochMillisecondsToJulian(epochMilliseconds: string): string {\n return (\n `((${epochMilliseconds} / ${MILLISECONDS_PER_DAY}.0) + ` +\n `${UNIX_EPOCH_JULIAN_DAY})`\n );\n}\n\nfunction textFractionMilliseconds(source: string): string {\n const first = `CAST(substr(${source}, 21, 1) AS INTEGER)`;\n const second = `CAST(substr(${source}, 22, 1) AS INTEGER)`;\n const third = `CAST(substr(${source}, 23, 1) AS INTEGER)`;\n return (\n `(CASE WHEN substr(${source}, 20, 1) <> '.' THEN 0 ELSE ` +\n `${first} * 100 + ` +\n `CASE WHEN substr(${source}, 22, 1) GLOB '[0-9]' THEN ${second} * 10 + ` +\n `CASE WHEN substr(${source}, 23, 1) GLOB '[0-9]' THEN ${third} ELSE 0 END ` +\n \"ELSE 0 END END)\"\n );\n}\n\nfunction textOffsetMilliseconds(source: string): string {\n const magnitude =\n `((CAST(substr(${source}, -5, 2) AS INTEGER) * 60 + ` +\n `CAST(substr(${source}, -2, 2) AS INTEGER)) * 60000)`;\n return (\n `(CASE WHEN substr(${source}, -1, 1) = 'Z' THEN 0 ` +\n `WHEN substr(${source}, -6, 1) = '+' THEN ${magnitude} ` +\n `ELSE -${magnitude} END)`\n );\n}\n\n/** Epoch milliseconds without SQLite's narrower timezone-offset parser. */\nfunction textToEpochMilliseconds(source: string): string {\n const day = julianToEpochMilliseconds(\n `julianday(substr(${source}, 1, 10) || 'T00:00:00Z')`\n );\n const local =\n `(${day} + CAST(substr(${source}, 12, 2) AS INTEGER) * 3600000 + ` +\n `CAST(substr(${source}, 15, 2) AS INTEGER) * 60000 + ` +\n `CAST(substr(${source}, 18, 2) AS INTEGER) * 1000 + ` +\n `${textFractionMilliseconds(source)})`;\n return `(${local} - ${textOffsetMilliseconds(source)})`;\n}\n\n/** Canonical ISO text for an admitted SQLite-range epoch millisecond. */\nfunction epochMillisecondsToText(epochMilliseconds: string): string {\n const wholeSeconds =\n `(CASE WHEN ${epochMilliseconds} < 0 AND ` +\n `${epochMilliseconds} % 1000 <> 0 ` +\n `THEN ${epochMilliseconds} / 1000 - 1 ` +\n `ELSE ${epochMilliseconds} / 1000 END)`;\n const milliseconds = `(((${epochMilliseconds} % 1000) + 1000) % 1000)`;\n return (\n \"(\" +\n `strftime('%Y-%m-%dT%H:%M:%S', ${wholeSeconds}, 'unixepoch') || ` +\n `printf('.%03dZ', ${milliseconds})` +\n \")\"\n );\n}\n\nfunction epochMilliseconds(source: string, form: DateTimePhysicalForm): string {\n if (form === \"epochMillis\") return source;\n if (form === \"julianDay\") return julianToEpochMilliseconds(source);\n return textToEpochMilliseconds(source);\n}\n\n/** SQL transcription of `validateIsoTimestamp`'s accepted string grammar. */\nfunction isIsoTimestamp(source: string): string {\n return `(${ISO_TIMESTAMP_SHAPES.map((shape) => `${source} GLOB '${shape}'`).join(\" OR \")})`;\n}\n\n/** Component rules used by the public ISO timestamp admission boundary. */\nfunction isAdmittedIsoTimestamp(source: string): string {\n const year = `CAST(substr(${source}, 1, 4) AS INTEGER)`;\n const month = `CAST(substr(${source}, 6, 2) AS INTEGER)`;\n const day = `CAST(substr(${source}, 9, 2) AS INTEGER)`;\n const hour = `CAST(substr(${source}, 12, 2) AS INTEGER)`;\n const minute = `CAST(substr(${source}, 15, 2) AS INTEGER)`;\n const second = `CAST(substr(${source}, 18, 2) AS INTEGER)`;\n const zulu = `substr(${source}, -1, 1) = 'Z'`;\n const offsetHour = `CAST(substr(${source}, -5, 2) AS INTEGER)`;\n const offsetMinute = `CAST(substr(${source}, -2, 2) AS INTEGER)`;\n const isLeapYear = `(${year} % 4 = 0 AND (${year} % 100 <> 0 OR ${year} % 400 = 0))`;\n const lastDay =\n `(CASE ${month} ` +\n `WHEN 2 THEN CASE WHEN ${isLeapYear} THEN 29 ELSE 28 END ` +\n \"WHEN 4 THEN 30 WHEN 6 THEN 30 WHEN 9 THEN 30 WHEN 11 THEN 30 \" +\n \"ELSE 31 END)\";\n return (\n `${isIsoTimestamp(source)} AND ${month} BETWEEN 1 AND 12 AND ` +\n `${day} BETWEEN 1 AND ${lastDay} AND ${hour} BETWEEN 0 AND 23 AND ` +\n `${minute} BETWEEN 0 AND 59 AND ${second} BETWEEN 0 AND 59 AND ` +\n `(${zulu} OR (${offsetHour} BETWEEN 0 AND 23 AND ${offsetMinute} BETWEEN 0 AND 59)) AND ` +\n `julianday(substr(${source}, 1, 10) || 'T00:00:00Z') IS NOT NULL`\n );\n}\n\nfunction sourceIsExact(\n source: string,\n form: DateTimePhysicalForm,\n epoch: string\n): string {\n if (form === \"text\") {\n return (\n `typeof(${source}) = 'text' AND ${isAdmittedIsoTimestamp(source)} AND ` +\n `${epoch} BETWEEN ${MIN_DATETIME_EPOCH_MILLISECONDS} AND ${MAX_DATETIME_EPOCH_MILLISECONDS}`\n );\n }\n if (form === \"epochMillis\") {\n return (\n `typeof(${source}) = 'integer' AND ` +\n `${epoch} BETWEEN ${MIN_DATETIME_EPOCH_MILLISECONDS} AND ${MAX_DATETIME_EPOCH_MILLISECONDS}`\n );\n }\n return (\n `typeof(${source}) = 'real' AND ` +\n `${epoch} BETWEEN ${MIN_DATETIME_EPOCH_MILLISECONDS} AND ${MAX_DATETIME_EPOCH_MILLISECONDS} AND ` +\n `${epochMillisecondsToJulian(epoch)} = ${source}`\n );\n}\n\nfunction targetValue(epoch: string, form: DateTimePhysicalForm): string {\n if (form === \"text\") return epochMillisecondsToText(epoch);\n if (form === \"epochMillis\") return epoch;\n return epochMillisecondsToJulian(epoch);\n}\n\nfunction targetIsExact(\n epoch: string,\n form: DateTimePhysicalForm,\n value: string\n): string {\n if (form === \"text\") {\n return `${value} IS NOT NULL AND ${isIsoTimestamp(value)}`;\n }\n if (form === \"epochMillis\") return \"1\";\n return `${julianToEpochMilliseconds(value)} = ${epoch}`;\n}\n\n/**\n * Converts one copied SQLite DateTime between its declared physical forms.\n *\n * The guard is the sole integrity boundary. It accepts only a value that is an\n * exact member of the source vocabulary and whose target representation\n * decodes to the same millisecond. `abs(INT64_MIN)` is SQLite's built-in,\n * deterministic error expression; it makes malformed, out-of-range, and\n * inexact rows abort the recreation instead of being rounded or reinterpreted.\n * An authenticated snapshot proves a same-form source and can retain it\n * unchanged. A live-introspected source has no logical marker, so even a\n * same-physical-form adoption crosses this guard before it becomes DateTime.\n */\nexport function sqliteDateTimeCopyExpression(\n source: string,\n from: DateTimePhysicalForm,\n to: DateTimePhysicalForm,\n isDeclaredSource: boolean\n): string {\n if (from === to && isDeclaredSource) return source;\n const epoch = epochMilliseconds(source, from);\n const value = from === to ? source : targetValue(epoch, to);\n const exact =\n from === to\n ? sourceIsExact(source, from, epoch)\n : `${sourceIsExact(source, from, epoch)} AND ${targetIsExact(epoch, to, value)}`;\n return (\n `CASE WHEN ${source} IS NULL THEN NULL ` +\n `WHEN ${exact} THEN ${value} ` +\n `ELSE abs(${SQLITE_MIN_INTEGER}) END`\n );\n}\n\n/** A reviewed manual-migration expression; the argument is a physical column name. */\nexport function sqliteCanonicalDateTimeExpression(columnName: string): string {\n const source = createIdentifierQuoter('\"')(columnName);\n const epoch = textToEpochMilliseconds(source);\n const value = epochMillisecondsToText(epoch);\n return `CASE WHEN ${source} IS NULL THEN NULL WHEN ${sourceIsExact(source, \"text\", epoch)} AND ${targetIsExact(epoch, \"text\", value)} THEN ${value} ELSE abs(${SQLITE_MIN_INTEGER}) END`;\n}\n\n/** The Time writer and both admission/repair consumers share one physical grammar. */\nfunction timeSource(source: string): { valid: string; value: string } {\n const shapes = [\n ISO_TIME,\n `${ISO_TIME}.[0-9]`,\n `${ISO_TIME}.[0-9][0-9]`,\n `${ISO_TIME}.[0-9][0-9][0-9]`,\n ];\n const valid = `typeof(${source}) = 'text' AND (${shapes.map((shape) => `${source} GLOB '${shape}'`).join(\" OR \")}) AND CAST(substr(${source},1,2) AS INTEGER) BETWEEN 0 AND 23 AND CAST(substr(${source},4,2) AS INTEGER) BETWEEN 0 AND 59 AND CAST(substr(${source},7,2) AS INTEGER) BETWEEN 0 AND 59`;\n const value = `substr(${source},1,8) || '.' || substr(CASE WHEN length(${source}) = 8 THEN '000' ELSE substr(${source},10) || '000' END,1,3)`;\n return { valid, value };\n}\n\n/** Canonical millisecond Time storage; malformed source rows abort the statement. */\nexport function sqliteCanonicalTimeExpression(columnName: string): string {\n const source = createIdentifierQuoter('\"')(columnName);\n const { valid, value } = timeSource(source);\n return `CASE WHEN ${source} IS NULL THEN NULL WHEN ${valid} THEN ${value} ELSE abs(${SQLITE_MIN_INTEGER}) END`;\n}\n\n/** Exact canonical runtime carrier predicates: NULL passes, unknown/malformed does not. */\nexport function sqliteCanonicalDateTimePredicate(columnName: string): string {\n const source = createIdentifierQuoter('\"')(columnName);\n const epoch = textToEpochMilliseconds(source);\n const value = epochMillisecondsToText(epoch);\n return `CASE WHEN ${source} IS NULL THEN 1 WHEN ${sourceIsExact(source, \"text\", epoch)} AND ${targetIsExact(epoch, \"text\", value)} AND ${source} = ${value} THEN 1 ELSE 0 END`;\n}\n\nexport function sqliteCanonicalTimePredicate(columnName: string): string {\n const source = createIdentifierQuoter('\"')(columnName);\n const { valid, value } = timeSource(source);\n return `CASE WHEN ${source} IS NULL THEN 1 WHEN ${valid} AND ${source} = ${value} THEN 1 ELSE 0 END`;\n}\n","/** SQLite token boundaries shared by stored-DDL readers. */\n\n/** An identifier token and where it ends. */\nexport interface SqliteIdentifierToken {\n readonly value: string;\n readonly quoted: boolean;\n readonly end: number;\n}\n\nconst IDENTIFIER_CLOSERS: Readonly<Record<string, string>> = {\n '\"': '\"',\n \"`\": \"`\",\n \"[\": \"]\",\n};\n\nconst BARE_IDENTIFIER_CHARACTER = /[A-Za-z0-9_$]/;\nconst WHITESPACE = /\\s/;\n\n/** Whether one character can occur in SQLite's bare identifier spelling. */\nexport function isSqliteBareIdentifierCharacter(character: string): boolean {\n return BARE_IDENTIFIER_CHARACTER.test(character);\n}\n\n/**\n * Read the identifier at or after `index`, in any of SQLite's four spellings.\n *\n * A doubled quote inside a `\"…\"` or a `` `…` `` token is an escaped one.\n */\nexport function readSqliteIdentifier(\n text: string,\n index: number\n): SqliteIdentifierToken | undefined {\n let cursor = index;\n while (cursor < text.length) {\n while (cursor < text.length && WHITESPACE.test(text.charAt(cursor))) {\n cursor++;\n }\n const isComment =\n (text[cursor] === \"-\" && text[cursor + 1] === \"-\") ||\n (text[cursor] === \"/\" && text[cursor + 1] === \"*\");\n if (!isComment) break;\n cursor = skipSqlNonStructuralRegion(text, cursor);\n }\n const opener = text[cursor];\n if (opener === undefined) return undefined;\n\n const closer = IDENTIFIER_CLOSERS[opener];\n if (closer !== undefined) {\n let value = \"\";\n cursor++;\n while (cursor < text.length) {\n if (text[cursor] === closer) {\n if (text[cursor + 1] === closer && closer !== \"]\") {\n value += closer;\n cursor += 2;\n continue;\n }\n return { value, quoted: true, end: cursor + 1 };\n }\n value += text[cursor];\n cursor++;\n }\n return undefined;\n }\n\n const start = cursor;\n while (\n cursor < text.length &&\n isSqliteBareIdentifierCharacter(text.charAt(cursor))\n ) {\n cursor++;\n }\n if (cursor === start) return undefined;\n return { value: text.slice(start, cursor), quoted: false, end: cursor };\n}\n\n/**\n * The offset just past the quoted token or SQL comment starting at `index`, or\n * `index` itself when structural SQL starts there.\n */\nexport function skipSqlNonStructuralRegion(\n text: string,\n index: number\n): number {\n const opener = text[index];\n if (opener === undefined) return index;\n if (opener === \"-\" && text[index + 1] === \"-\") {\n const end = text.indexOf(\"\\n\", index + 2);\n return end === -1 ? text.length : end;\n }\n if (opener === \"/\" && text[index + 1] === \"*\") {\n const end = text.indexOf(\"*/\", index + 2);\n return end === -1 ? text.length : end + 2;\n }\n const closer = opener === \"'\" ? \"'\" : IDENTIFIER_CLOSERS[opener];\n if (closer === undefined) return index;\n\n let cursor = index + 1;\n while (cursor < text.length) {\n if (text[cursor] === closer) {\n // A doubled quote is an escaped one, not the end of the token. `]` has\n // no escape in SQLite's bracket spelling.\n if (text[cursor + 1] === closer && closer !== \"]\") {\n cursor += 2;\n continue;\n }\n return cursor + 1;\n }\n cursor++;\n }\n return text.length;\n}\n","import {\n isSqliteBareIdentifierCharacter,\n readSqliteIdentifier,\n skipSqlNonStructuralRegion,\n} from \"./sql-lexing\";\n\n/** One top-level entry of a `CREATE TABLE` definition list. */\nexport interface SqliteTableDefinition {\n readonly text: string;\n /** The column this entry defines, or `undefined` for a table constraint. */\n readonly columnName: string | undefined;\n}\n\n/** A `CONSTRAINT <name>` at the top level of one definition. */\nexport interface SqliteConstraintClause {\n readonly name: string;\n /** Where the `CONSTRAINT` keyword starts inside the definition text. */\n readonly offset: number;\n}\n\n/** Keywords that open a table constraint rather than a column definition. */\nconst TABLE_CONSTRAINT_KEYWORDS = new Set([\n \"CONSTRAINT\",\n \"PRIMARY\",\n \"UNIQUE\",\n \"CHECK\",\n \"FOREIGN\",\n]);\n\n/**\n * Every top-level entry of the definition list, with the column each one\n * defines. Quoted tokens and comments are skipped before structural commas and\n * parentheses are interpreted.\n */\nexport function sqliteTableDefinitions(sql: string): SqliteTableDefinition[] {\n let open = -1;\n let scan = 0;\n while (scan < sql.length) {\n const skipped = skipSqlNonStructuralRegion(sql, scan);\n if (skipped !== scan) {\n scan = skipped;\n continue;\n }\n if (sql[scan] === \"(\") {\n open = scan;\n break;\n }\n scan++;\n }\n if (open === -1) return [];\n\n const definitions: SqliteTableDefinition[] = [];\n let depth = 1;\n let start = open + 1;\n let cursor = start;\n while (cursor < sql.length) {\n const skipped = skipSqlNonStructuralRegion(sql, cursor);\n if (skipped !== cursor) {\n cursor = skipped;\n continue;\n }\n const char = sql[cursor];\n if (char === \"(\") depth++;\n else if (char === \")\") {\n depth--;\n if (depth === 0) break;\n } else if (char === \",\" && depth === 1) {\n definitions.push(describeDefinition(sql.slice(start, cursor)));\n start = cursor + 1;\n }\n cursor++;\n }\n definitions.push(describeDefinition(sql.slice(start, cursor)));\n return definitions;\n}\n\nfunction describeDefinition(raw: string): SqliteTableDefinition {\n const text = raw.trim();\n const first = readSqliteIdentifier(text, 0);\n if (first === undefined) return { text, columnName: undefined };\n if (first.quoted) return { text, columnName: first.value };\n return {\n text,\n columnName: TABLE_CONSTRAINT_KEYWORDS.has(first.value.toUpperCase())\n ? undefined\n : first.value,\n };\n}\n\n/** Every structural `CONSTRAINT <name>` at depth zero of one definition. */\nexport function sqliteConstraintClauses(\n definition: string\n): SqliteConstraintClause[] {\n const clauses: SqliteConstraintClause[] = [];\n let depth = 0;\n let cursor = 0;\n while (cursor < definition.length) {\n const skipped = skipSqlNonStructuralRegion(definition, cursor);\n if (skipped !== cursor) {\n cursor = skipped;\n continue;\n }\n const char = definition.charAt(cursor);\n const word = isSqliteBareIdentifierCharacter(char)\n ? readSqliteIdentifier(definition, cursor)\n : undefined;\n if (word !== undefined) {\n if (depth === 0 && word.value.toUpperCase() === \"CONSTRAINT\") {\n const name = readSqliteIdentifier(definition, word.end);\n if (name) {\n clauses.push({ name: name.value, offset: cursor });\n cursor = name.end;\n continue;\n }\n }\n cursor = word.end;\n continue;\n }\n if (char === \"(\") depth++;\n else if (char === \")\") depth--;\n cursor++;\n }\n return clauses;\n}\n\n/** Structural keywords outside expression bodies, quoted tokens and comments. */\nexport function sqliteDefinitionKeywords(definition: string): string[] {\n const words: string[] = [];\n let depth = 0;\n let cursor = 0;\n while (cursor < definition.length) {\n const skipped = skipSqlNonStructuralRegion(definition, cursor);\n if (skipped !== cursor) {\n cursor = skipped;\n continue;\n }\n const word = readSqliteIdentifier(definition, cursor);\n if (word && !word.quoted) {\n if (depth === 0) words.push(word.value.toUpperCase());\n cursor = word.end;\n continue;\n }\n if (definition[cursor] === \"(\") depth++;\n else if (definition[cursor] === \")\") depth--;\n cursor++;\n }\n return words;\n}\n","/**\n * SQLite fixed-decimal migration storage.\n *\n * SQLite cannot carry a decimal descriptor in its declared storage type, so\n * this module owns the reserved CHECK carrier, its structural reader, and the\n * exact table-rebuild expressions that rescale scalar and list coefficients.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../../../../errors\";\nimport {\n type DecimalDescriptor,\n decimalColumnType,\n describeDecimalDomain,\n readStoredDecimalDescriptor,\n} from \"../../../../validation/primitives/decimal-codec\";\nexport type DecimalStorageKind = \"scalar\" | \"list\";\ninterface PhysicalColumn {\n readonly name: string;\n readonly type: string;\n readonly nullable: boolean;\n readonly decimal?: DecimalDescriptor | undefined;\n}\nexport function sqliteDecimalStorageKind(\n column: Pick<PhysicalColumn, \"type\" | \"decimal\">\n): DecimalStorageKind | undefined {\n if (column.decimal === undefined) return undefined;\n const type = column.type.toUpperCase();\n if (type === decimalColumnType(\"sqlite\", column.decimal)) return \"scalar\";\n return type === \"TEXT\" ? \"list\" : undefined;\n}\n\nimport {\n type SqliteConstraintClause,\n type SqliteTableDefinition,\n sqliteConstraintClauses,\n sqliteTableDefinitions,\n} from \"./column-constraints\";\n\n/**\n * The reserved SQLite constraint name for one decimal column.\n *\n * SQLite's declared type is the wrong carrier twice over: it stores `INTEGER`\n * (or `TEXT` for a list) whatever the domain is, and a CHECK written INTO the\n * type string never reads back — `PRAGMA table_info.type` reports only the\n * `type-name` production, so the desired `TEXT CHECK(...)` can never equal the\n * introspected `TEXT` and a full table recreation is planned on every push,\n * forever. (That is measured behaviour of the enum column type, not a\n * hypothetical.) So the descriptor rides in a NAMED constraint, and\n * introspection recovers it from the name.\n */\nexport function sqliteDecimalConstraintName(\n columnName: string,\n descriptor: DecimalDescriptor\n): string {\n return `viborm_decimal_${columnName}_${descriptor.precision}_${descriptor.scale}`;\n}\n\n/** The namespace VibORM reserves for the constraints it writes itself. */\nconst RESERVED_CONSTRAINT_PREFIX = \"viborm_decimal_\";\n\n/** `<precision>_<scale>`: what follows the column name in a reserved name. */\nconst RESERVED_CONSTRAINT_TAIL = /^(\\d+)_(\\d+)$/;\n\n/**\n * The declared domain of one column, read back out of the `CREATE TABLE` text\n * SQLite stored — or `undefined` when this column carries no reserved\n * constraint. The matching PRAGMA type and nullability travel with the column:\n * the stored clause is owned only when it is the exact writer rendering for\n * those physical facts.\n *\n * This PARSES, it does not search. The name alone is not evidence: SQLite\n * stores the statement verbatim, so any string literal a user can write — an\n * enum value, a string default, an index predicate — appears in the same text\n * and can spell VibORM's reserved prefix. A first-hit substring scan therefore\n * reads a user's data as a descriptor, and with an earlier offset it OVERRIDES\n * the real constraint: the next push plans a conversion between two domains\n * neither side declared and rewrites every stored coefficient. So the reader\n * walks the column-definition list the same quote-aware way\n * `partialIndexPredicate` walks a `CREATE INDEX` (`introspect.ts`), finds real\n * `CONSTRAINT <name> CHECK (…)` clauses, and binds each to the column definition\n * it actually sits in.\n *\n * A reserved name the module could not have written is REFUSED, not ignored.\n * Ignoring it is not the safe reading: the name is in a namespace only this\n * module writes, so its presence means either a corrupted carrier or a\n * collision, and both make every later push either wrong (a conversion between\n * invented domains) or non-convergent (a descriptor the desired side can never\n * match). The refusal names the constraint so the estate can be repaired.\n *\n * Ownership is proved by RE-RENDERING: the clause must be, byte for byte, what\n * {@link sqliteDecimalCheck} would emit for this column at the descriptor the\n * name declares. That is the only test that cannot be forged by a name alone,\n * and it is exact because SQLite re-spells nothing it stores.\n */\nexport function readSqliteDecimalConstraint(\n tableSql: string | null | undefined,\n column: Pick<PhysicalColumn, \"name\" | \"type\" | \"nullable\">,\n escapeIdentifier: (name: string) => string\n): DecimalDescriptor | undefined {\n if (!tableSql) return undefined;\n // The reserved namespace has to appear at all before the statement is worth\n // parsing: introspection reads every column of every table, and the\n // overwhelming majority carry no decimal.\n if (!tableSql.includes(RESERVED_CONSTRAINT_PREFIX)) return undefined;\n\n let found: DecimalDescriptor | undefined;\n for (const definition of sqliteTableDefinitions(tableSql)) {\n for (const clause of sqliteConstraintClauses(definition.text)) {\n if (!clause.name.startsWith(RESERVED_CONSTRAINT_PREFIX)) continue;\n // This reader is invoked once for every PRAGMA column. A reserved\n // column constraint is adjudicated when its own physical column is in\n // hand, because only that invocation knows the type and nullability the\n // database actually reported. TABLE constraints have no such invocation\n // and are always namespace squatters.\n if (\n definition.columnName !== undefined &&\n definition.columnName !== column.name\n ) {\n continue;\n }\n const descriptor = ownedDescriptor(\n definition,\n clause,\n column,\n escapeIdentifier\n );\n if (descriptor === undefined) {\n throw new MigrationError(\n `The stored definition carries a constraint named \"${clause.name}\", which is inside the namespace VibORM reserves for the fixed-decimal descriptor it writes itself, but it is not a constraint VibORM wrote. ` +\n \"A reserved constraint is the ONLY place a SQLite column's declared precision and scale survive — the storage class is INTEGER or TEXT at every domain — so reading this one as a descriptor would plan conversions between domains the schema never declared, and ignoring it would re-plan the same alteration on every push. \" +\n \"Rename or drop the constraint, or restore the definition VibORM wrote for this column.\",\n VibORMErrorCode.INVALID_INPUT,\n {\n meta: {\n constraint: clause.name,\n // Absent for a TABLE constraint, which belongs to no column.\n ...(definition.columnName === undefined\n ? {}\n : { column: definition.columnName }),\n },\n }\n );\n }\n if (found !== undefined) {\n throw new MigrationError(\n `The stored definition carries more than one fixed-decimal descriptor for column \"${column.name}\": ${describeDecimalDomain(found)} and ${describeDecimalDomain(descriptor)}. ` +\n \"One physical column can have only one logical decimal domain, so introspection refuses the ambiguous reserved carriers instead of choosing one by order.\",\n VibORMErrorCode.INVALID_INPUT,\n { meta: { column: column.name } }\n );\n }\n found = descriptor;\n }\n }\n return found;\n}\n\n/** One top-level entry of a `CREATE TABLE`'s parenthesized definition list. */\n/**\n * The reserved constraint this clause carries, or `undefined` when the clause\n * is one this module could not have written.\n *\n * Three things must hold together, and each is a way the namespace gets\n * squatted: the clause sits in a COLUMN definition (never a table constraint,\n * which VibORM never writes); its name is this column's name followed by the\n * two numbers; and the whole clause re-renders byte for byte.\n */\nfunction ownedDescriptor(\n definition: SqliteTableDefinition,\n clause: SqliteConstraintClause,\n physicalColumn: Pick<PhysicalColumn, \"name\" | \"type\" | \"nullable\">,\n escapeIdentifier: (name: string) => string\n): DecimalDescriptor | undefined {\n const column = definition.columnName;\n if (column === undefined) return undefined;\n const prefix = `${RESERVED_CONSTRAINT_PREFIX}${column}_`;\n if (!clause.name.startsWith(prefix)) return undefined;\n const match = RESERVED_CONSTRAINT_TAIL.exec(clause.name.slice(prefix.length));\n if (!match) return undefined;\n const descriptor = readStoredDecimalDescriptor(match[1], match[2], \"sqlite\");\n if (descriptor === undefined) return undefined;\n // PRAGMA owns the physical type and nullability. Re-render ONLY the shape\n // those facts permit; trying all four writer spellings lets an impossible\n // INTEGER/list or nullable/non-null carrier masquerade as a valid domain.\n const kind = sqliteDecimalStorageKind({\n ...physicalColumn,\n decimal: descriptor,\n });\n if (kind === undefined) return undefined;\n const rendered = sqliteDecimalCheck(\n physicalColumn,\n descriptor,\n kind,\n escapeIdentifier\n );\n if (definition.text.startsWith(rendered, clause.offset)) {\n return descriptor;\n }\n return undefined;\n}\n\n/**\n * Whether one generated table definition carries this column's reserved\n * decimal descriptor name in the structural column clause that owns it.\n *\n * Apply uses this only after it has proved the surrounding statement sequence\n * is VibORM's exact generated table-recreation program. It distinguishes the\n * decimal-column rename variant, whose copy expression needs no conversion\n * sentinel, from an unrelated recreation of a table that merely contains some\n * other decimal column.\n */\nexport function sqliteColumnDefinitionCarriesDecimalDescriptor(\n tableSql: string,\n columnName: string\n): boolean {\n const prefix = `${RESERVED_CONSTRAINT_PREFIX}${columnName}_`;\n for (const definition of sqliteTableDefinitions(tableSql)) {\n if (definition.columnName !== columnName) continue;\n for (const clause of sqliteConstraintClauses(definition.text)) {\n if (!clause.name.startsWith(prefix)) continue;\n const match = RESERVED_CONSTRAINT_TAIL.exec(\n clause.name.slice(prefix.length)\n );\n if (\n match &&\n readStoredDecimalDescriptor(match[1], match[2], \"sqlite\") !== undefined\n ) {\n return true;\n }\n }\n }\n return false;\n}\n\n/** `10^precision - 1`: the widest coefficient the domain can hold. */\nfunction maxCoefficient(precision: number): bigint {\n return 10n ** BigInt(precision) - 1n;\n}\n\n/**\n * The reserved CHECK a SQLite decimal column carries, as a complete column\n * constraint (`CONSTRAINT <name> CHECK (<body>)`).\n *\n * A scalar is the signed integer coefficient. A list is TEXT holding a JSON\n * array of coefficient strings. NULL passes only for a nullable column.\n */\nexport function sqliteDecimalCheck(\n column: { readonly name: string; readonly nullable: boolean },\n descriptor: DecimalDescriptor,\n kind: DecimalStorageKind,\n escapeIdentifier: (name: string) => string\n): string {\n const col = escapeIdentifier(column.name);\n const name = escapeIdentifier(\n sqliteDecimalConstraintName(column.name, descriptor)\n );\n const bound = maxCoefficient(descriptor.precision).toString();\n const body =\n kind === \"list\"\n ? `typeof(${col}) = 'text' AND json_valid(${col}) AND json_type(${col}) = 'array'`\n : `typeof(${col}) = 'integer' AND ${col} BETWEEN -${bound} AND ${bound}`;\n const guarded = column.nullable ? `${col} IS NULL OR (${body})` : body;\n return `CONSTRAINT ${name} CHECK (${guarded})`;\n}\n\n/**\n * The value a row lands in the rebuilt table when it does not fit the target\n * domain. It fails the target column's own reserved CHECK and aborts the whole\n * recreation atomically.\n */\nconst SCALAR_SENTINEL = \"'viborm:decimal-out-of-domain'\";\nconst LIST_SENTINEL = \"'viborm:decimal-list-out-of-domain'\";\n\ninterface Rescale {\n /** `10^|scale delta|`, as an integer literal. */\n readonly factor: string;\n readonly direction: \"up\" | \"down\" | \"none\";\n /** The inclusive absolute bound the SOURCE coefficient must satisfy. */\n readonly bound: string;\n}\n\n/** The one arithmetic decision behind every SQLite conversion expression. */\nfunction rescale(\n from: DecimalDescriptor | undefined,\n to: DecimalDescriptor\n): Rescale {\n const targetMax = maxCoefficient(to.precision);\n const sourceMax = from ? maxCoefficient(from.precision) : targetMax;\n const delta = to.scale - (from?.scale ?? 0);\n if (delta === 0) {\n return {\n factor: \"1\",\n direction: \"none\",\n bound: min(sourceMax, targetMax).toString(),\n };\n }\n if (delta > 0) {\n const factor = 10n ** BigInt(delta);\n return {\n factor: factor.toString(),\n direction: \"up\",\n bound: min(sourceMax, targetMax / factor).toString(),\n };\n }\n const factor = 10n ** BigInt(-delta);\n return {\n factor: factor.toString(),\n direction: \"down\",\n bound: min(sourceMax, targetMax * factor).toString(),\n };\n}\n\nfunction min(a: bigint, b: bigint): bigint {\n return a < b ? a : b;\n}\n\n/**\n * The per-column source expression used by SQLite table recreation. It\n * converts stored values from `from`'s physical spelling to `to`'s without a\n * REAL intermediate and routes every malformed or out-of-domain value to the\n * target CHECK's sentinel.\n */\nexport function sqliteDecimalCopyExpression(\n source: string,\n from: DecimalDescriptor | undefined,\n to: DecimalDescriptor,\n kind: DecimalStorageKind\n): string {\n const { factor, direction, bound } = rescale(from, to);\n const exact = direction === \"down\" ? ` AND ${source} % ${factor} = 0` : \"\";\n if (kind === \"scalar\") {\n const converted = convertedCoefficient(source, direction, factor);\n return (\n `CASE WHEN ${source} IS NULL THEN NULL WHEN typeof(${source}) = 'integer' ` +\n `AND ${source} BETWEEN -${bound} AND ${bound}${exact} THEN ${converted} ` +\n `ELSE ${SCALAR_SENTINEL} END`\n );\n }\n return listCopyExpression(source, direction, factor, bound);\n}\n\nfunction convertedCoefficient(\n operand: string,\n direction: Rescale[\"direction\"],\n factor: string\n): string {\n if (direction === \"up\") return `${operand} * ${factor}`;\n if (direction === \"down\") return `${operand} / ${factor}`;\n return operand;\n}\n\n/** Convert a SQLite JSON coefficient-string list without losing order. */\nfunction listCopyExpression(\n source: string,\n direction: Rescale[\"direction\"],\n factor: string,\n bound: string\n): string {\n const member = `\"m\".\"value\"`;\n const asInteger = `CAST(${member} AS INTEGER)`;\n const exact = direction === \"down\" ? ` AND ${asInteger} % ${factor} = 0` : \"\";\n const admissible =\n `\"m\".\"type\" = 'text' AND CAST(${asInteger} AS TEXT) = ${member} ` +\n `AND ${asInteger} BETWEEN -${bound} AND ${bound}${exact}`;\n const converted = `CAST(${convertedCoefficient(`CAST(\"value\" AS INTEGER)`, direction, factor)} AS TEXT)`;\n return (\n `CASE WHEN ${source} IS NULL THEN NULL WHEN typeof(${source}) = 'text' AND json_valid(${source}) = 1 THEN ` +\n `CASE WHEN json_type(${source}) = 'array' THEN CASE WHEN ` +\n `(SELECT count(*) FROM json_each(${source}) AS \"m\" WHERE NOT (${admissible})) = 0 THEN ` +\n `(SELECT json_group_array(${converted}) FROM (SELECT \"value\" FROM json_each(${source}) AS \"m\" ORDER BY \"m\".\"key\")) ` +\n `ELSE ${LIST_SENTINEL} END ELSE ${LIST_SENTINEL} END ELSE ${LIST_SENTINEL} END`\n );\n}\n"],"mappings":"oQA6BA,SAAS,iBAAiB,EAA0C,CAGlE,OAFI,IAAY,aAAqB,KACjC,IAAY,QAAgB,QACzB,SAIT,SAAgB,gCACd,EACA,EACyC,CACzC,IAAM,EAAiB,iBAAiB,EAAQ,CAChD,IAAK,GAAM,CAAC,EAAW,KAAU,OAAO,QAAQ,EAAO,CAAE,CACvD,IAAM,EAAkC,EAAM,KAAK,MAAM,QACzD,IAAK,GAAM,CAAC,EAAW,KAAW,OAAO,QAAQ,EAAQ,CAAE,CACzD,IAAM,EAAQ,EAAO,KAAK,MAC1B,GAAI,EAAM,OAAS,WAAa,EAAM,UAAY,IAAA,GAAW,SAC7D,IAAM,EAAS,EACb,EACA,EAAM,QACP,CACG,OAAW,IAAA,GACf,MAAO,CACL,YACA,YACA,UACA,WAAY,EAAM,QAClB,SACD,GAOP,SAAgB,oCACd,EACQ,CACR,MAAO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Aa,GAAG,EAAQ,KAAK,IAC3C,IAAc,OAAe,GAAG,EAAQ,KAAK,IAC1C,EAIT,SAAS,mBACP,EACA,EACA,EACA,EACQ,CACR,IAAM,EAAS,cACT,EAAY,QAAQ,EAAO,cAMjC,MACE,aAAa,EAAO,iCAAiC,EAAO,4BAA4B,EAAO,iCACxE,EAAO,6DACK,EAAO,sBAN1C,gCAAgC,EAAU,cAAc,EAAO,OACxD,EAAU,YAAY,EAAM,OAAO,IAH9B,IAAc,OAAS,QAAQ,EAAU,KAAK,EAAO,MAAQ,KAQE,uCAJ3D,QAAQ,qBAAqB,2BAA4B,EAAW,EAAO,CAAC,WAKtD,wCAAwC,EAAO,qCAC7E,EAAc,YAAY,EAAc,YAAY,EAAc"}
@@ -1,2 +0,0 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{d as t,f as n,h as r,m as i,t as a}from"./observation-CLp8ylmL.mjs";import{n as o,r as s,t as c}from"./key-DKaqPb8w.mjs";import{o as l}from"./execution-context-BPk0YLhd.mjs";import{n as u}from"./v-B2WwtcRz.mjs";import{t as d}from"./clock-W8H2Khng.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 r(`TTL must be positive, got: ${e}`);return e}let t=e.trim().toLowerCase().match(g);if(!t)throw new r(`Invalid TTL format: "${e}". Expected format: "<number> <unit>" (e.g., "1 hour", "20 seconds")`);let n=t[1],i=t[2],a=Number.parseFloat(n),o=m[i];if(o===void 0)throw new r(`Unknown time unit: "${i}". Valid units: ${h}`);let s=Math.floor(a*o);if(!Number.isSafeInteger(s)||s<=0)throw new r(`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||a(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 t=b.get(e);if(t===void 0)throw new i(`Official cache scope is not authentic for this cache execution.`);return t}function refuseExternalScope(e){if(e!==void 0)throw new i(`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,i,a,o){let c=s(e,t,n),l=`${c.key}${i.key===void 0?``:`:${i.key}`}`,u=JSON.stringify([c.identity,i.key]),d=this.#e,executeCore=async()=>{if(i.bypass){let e=await r();return this.#r(l,e,i,a,o,u,d),recordCacheOutcome(i.executionContext,`bypass`),e}let n=await this.#n(l,i.executionContext,o,a,u);if(n){let s=this.clock.now()-n.createdAt;if(!(s>=n.ttl))return recordCacheOutcome(i.executionContext,`hit`),n.value;let c=i.swr;if(c!==!1&&s<c&&(n.expiresAt===void 0||this.clock.now()<n.expiresAt))return scheduleBackground(this.#a(e,t,l,r,i,c,a,o,u,d),i.waitUntil),recordCacheOutcome(i.executionContext,`hit`,`stale`),n.value}let s=await r();return this.#r(l,s,i,a,o,u,d),recordCacheOutcome(i.executionContext,`miss`),s};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,n,r,i,a,o,s,c,u,d){let f;try{f=await this.#l(r,c)}catch{return}if(!f)return;let p=l(a.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 i(),n=s.snapshot(t);await this.#c(r,n,{ttl:a.ttlMs,swrTtl:o},a.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(r,c).catch(()=>void 0);else try{await this.#u(r,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():t({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:a.executionContext,read:Object.freeze({model:e,operation:n,identity:a.driverIdentity}),complete:()=>h})))}#o(e,r,i,a=completeWithoutFacts,o){let s=l(r)?.observe;if(s===void 0||s.length===0)return i();let c=e===`clear`||e===`delete`;return t({kind:`cache`,operation:c?`invalidate`:e},c?n(s):s,i,void 0,()=>Object.freeze(c?{kind:`cache-backend`,boundary:e,driverName:this.driverName,complete:completeWithoutFacts}:{kind:`cache`,context:r,driverName:this.driverName,...o===void 0?{}:{ttl:o},complete:a}))}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,t){if(t!==void 0){if(e.startsWith(`${c}:`))throw new i(`Official cache keys and prefixes must be relative and cannot begin with 'viborm:'.`);return`${t}:${e}`}let n=e.startsWith(`${c}:`)?e:e?`${c}:${e}`:c;if(n===o||n.startsWith(`${o}:`))throw new i(`The official cache namespace requires an authenticated cache extension.`);return n}};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-CRaDT4B7.mjs.map
@@ -1,2 +0,0 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{r as t}from"./validation-Du6j0Q38.mjs";import{b as n}from"./base-vfur-DaU.mjs";const r=`non-redirecting`;function errorCause(e){return n(e)?e:Error(`A non-Error value was thrown.`,{cause:e})}function readOptionOnce(e,n){try{return Object.hasOwn(e,n)?Reflect.get(e,n):void 0}catch(e){throw new t(`The "${n}" option could not be read.`,{cause:errorCause(e)})}}function resolveNamespaceOption(e){let n=readOptionOnce(e,`namespace`);if(n===void 0||typeof n==`string`)return n;throw new t(`The "namespace" option must be a string; received type "${typeof n}".`)}function resolveMigrationNamespaceAttestationOption(e){let n=readOptionOnce(e,`migrationNamespaceAttestation`);if(n!==void 0){if(n===r)return r;throw new t(`The "migrationNamespaceAttestation" option admits only "${r}".`)}}function defineImmutableDriverFact(e,t,n){Object.defineProperty(e,t,{value:n,writable:!1,enumerable:!0,configurable:!1})}export{resolveNamespaceOption as i,errorCause as n,resolveMigrationNamespaceAttestationOption as r,defineImmutableDriverFact as t};
2
- //# sourceMappingURL=driver-options-DxlB1tms.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"driver-options-DxlB1tms.mjs","names":[],"sources":["../src/drivers/shared/driver-options.ts"],"sourcesContent":["/**\n * The driver-option boundary.\n *\n * Every public `namespace` and MySQL2's `migrationNamespaceAttestation` reach\n * VibORM through a caller-owned object, which may be a proxy or carry an\n * accessor. This module is the one place those properties are read: exactly\n * once, with a thrown accessor turned into the client-construction failure the\n * rest of the surface already raises. A second read is what would let a value\n * that passed validation be swapped for one that did not before it is used.\n *\n * Convenience wrappers read the caller's configuration here and hand their\n * driver a plain primitive; direct driver construction reads its own options\n * object here. Both entries reach this owner, and neither reaches a provider\n * before it answers.\n */\n\nimport { ClientInitializationError } from \"@errors\";\nimport { isError } from \"../../errors/diagnostic-safety\";\n\n/**\n * MySQL2's transport assertion. It selects nothing: it states that qualified\n * `database.table` references and the pinned migration session's `USE` cannot\n * be remapped by VTGate schema-routing rules or an equivalent proxy.\n */\nexport type MigrationNamespaceAttestation = \"non-redirecting\";\n\nconst MIGRATION_NAMESPACE_ATTESTATION: MigrationNamespaceAttestation =\n \"non-redirecting\";\n\n/**\n * The ONE normalizer for a thrown value that has to become an error's cause.\n *\n * A thrown `Error` stays the cause. Anything else becomes one deterministic\n * `Error` that keeps the thrown value as its own cause and never renders it —\n * rendering runs `toString` on a value chosen by whoever wrote the accessor.\n *\n * TOTAL, which a bare `thrown instanceof Error` is not: `instanceof` walks the\n * prototype chain through `[[GetPrototypeOf]]`, so a Proxy trap that throws\n * makes the TEST fail rather than the value. Every caller runs this inside the\n * `catch` that is building a typed error, so a throw here does not lose the\n * cause — it replaces the typed boundary with the trap's own error, and a\n * caller catching that boundary catches nothing. `isError` is the project's\n * existing guarded predicate; this is its one driver-side consumer, so the\n * option boundary, the pinned session's condemnation and the migration reset\n * all normalize the same way rather than each writing the test again.\n */\nexport function errorCause(thrown: unknown): Error {\n if (isError(thrown)) return thrown;\n return new Error(\"A non-Error value was thrown.\", { cause: thrown });\n}\n\n/** Read one caller-owned option, exactly once, from the object itself. */\nfunction readOptionOnce(source: object, key: string): unknown {\n try {\n // Own properties only. An inherited value is `Object.prototype` pollution\n // or a carrier's prototype, never a request this caller wrote down, and\n // honouring one forges the target and the transport assertion for every\n // driver constructed with no options at all. The presence test shares this\n // `try` so a hostile trap fails exactly like a hostile accessor, and it is\n // not a second read of the value: it consults the descriptor, not the\n // getter.\n if (!Object.hasOwn(source, key)) return undefined;\n return Reflect.get(source, key);\n } catch (thrown) {\n throw new ClientInitializationError(\n `The \"${key}\" option could not be read.`,\n { cause: errorCause(thrown) }\n );\n }\n}\n\n/**\n * The namespace this configuration asks for, or `undefined` when it asks for\n * none. An explicit `undefined` and an absent property are the same request.\n *\n * The value is narrowed here, not validated: the name's grammar, length limit,\n * and system names have one owner — `installAdapterNamespace` — which every\n * value returned here reaches through its adapter constructor. What the\n * `typeof` test uniquely buys is this function's declared `string | undefined`\n * return, which is what lets seven driver constructors hand the value to an\n * adapter without a cast; a value that cannot be narrowed also cannot be\n * dropped, because dropping it would silently turn `namespace: 5` into\n * PostgreSQL's `public` default.\n */\nexport function resolveNamespaceOption(source: object): string | undefined {\n const value = readOptionOnce(source, \"namespace\");\n if (value === undefined || typeof value === \"string\") return value;\n throw new ClientInitializationError(\n `The \"namespace\" option must be a string; received type \"${typeof value}\".`\n );\n}\n\n/**\n * The attestation this configuration makes, or `undefined` when it makes none.\n * Only the exact literal is admitted: a truthy value, a near-miss spelling, or\n * any other literal is a refusal, because this is a safety claim and a\n * mistyped claim must not read as an approximate one.\n */\nexport function resolveMigrationNamespaceAttestationOption(\n source: object\n): MigrationNamespaceAttestation | undefined {\n const value = readOptionOnce(source, \"migrationNamespaceAttestation\");\n if (value === undefined) return undefined;\n if (value === MIGRATION_NAMESPACE_ATTESTATION) {\n return MIGRATION_NAMESPACE_ATTESTATION;\n }\n throw new ClientInitializationError(\n `The \"migrationNamespaceAttestation\" option admits only \"${MIGRATION_NAMESPACE_ATTESTATION}\".`\n );\n}\n\n/**\n * Install one driver fact as an own, non-writable, non-configurable property.\n *\n * `readonly` is erased at run time, and query rendering, migrations, cache\n * scope and instrumentation all re-read these members per operation: a\n * writable adapter reference is a swap vector between binding a cache scope and\n * executing the statement, and a writable attestation is a migration-admission\n * bypass. An absent attestation is installed too, so it cannot be added later.\n */\nexport function defineImmutableDriverFact(\n driver: object,\n key: string,\n value: unknown\n): void {\n Object.defineProperty(driver, key, {\n value,\n writable: false,\n enumerable: true,\n configurable: false,\n });\n}\n"],"mappings":"+HA0BA,MAAM,EACJ,kBAmBF,SAAgB,WAAW,EAAwB,CAEjD,OADI,EAAQ,EAAO,CAAS,EACjB,MAAM,gCAAiC,CAAE,MAAO,EAAQ,CAAC,CAItE,SAAS,eAAe,EAAgB,EAAsB,CAC5D,GAAI,CASF,OADK,OAAO,OAAO,EAAQ,EAAI,CACxB,QAAQ,IAAI,EAAQ,EAAI,CADE,aAE1B,EAAQ,CACf,MAAM,IAAI,EACR,QAAQ,EAAI,6BACZ,CAAE,MAAO,WAAW,EAAO,CAAE,CAC9B,EAiBL,SAAgB,uBAAuB,EAAoC,CACzE,IAAM,EAAQ,eAAe,EAAQ,YAAY,CACjD,GAAI,IAAU,IAAA,IAAa,OAAO,GAAU,SAAU,OAAO,EAC7D,MAAM,IAAI,EACR,2DAA2D,OAAO,EAAM,IACzE,CASH,SAAgB,2CACd,EAC2C,CAC3C,IAAM,EAAQ,eAAe,EAAQ,gCAAgC,CACjE,OAAU,IAAA,GACd,IAAI,IAAU,EACZ,OAAO,EAET,MAAM,IAAI,EACR,2DAA2D,EAAgC,IAC5F,EAYH,SAAgB,0BACd,EACA,EACA,EACM,CACN,OAAO,eAAe,EAAQ,EAAK,CACjC,QACA,SAAU,GACV,WAAY,GACZ,aAAc,GACf,CAAC"}
@@ -1,2 +0,0 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{C as t,T as n,f as r,i,p as a}from"./validation-Du6j0Q38.mjs";import{_ as o,d as s,f as c,g as l,h as u,i as d,l as f,n as p,p as m,r as h,t as g}from"./bind-parameter-capacity-DzMcIB95.mjs";import{b as _,i as v,n as y,p as b,t as x}from"./base-vfur-DaU.mjs";import{a as S,r as C,t as w}from"./observation-CLp8ylmL.mjs";import{l as ee,n as T,r as E,s as D}from"./error-mapping-BWzb-l02.mjs";import{n as O}from"./transaction-oskVwmsf.mjs";import{r as k,t as A}from"./sql--69HUgel.mjs";import{n as j}from"./suppressed-failure-BPxfHTMc.mjs";import{c as M,i as N,n as P,o as F,t as I}from"./transactions-gjmrWN5W.mjs";import{a as L,c as R,o as z,t as B}from"./execution-context-BPk0YLhd.mjs";import{t as V}from"./driver-options-DxlB1tms.mjs";import{t as H}from"./clock-W8H2Khng.mjs";function applyStatementTransforms(e,n,r,i){if(i===void 0||i.length===0)return e;let a=e;for(let e of i){let i=Object.freeze({statement:a,model:n,operation:r}),o;try{o=Reflect.apply(e.handler,void 0,[i])}catch(t){throw statementTransformFailure(e.extension,n,r,`threw`,normalizeThrown(t))}try{if(k(o)){let e=Reflect.get(o,`toStatement`);if(!t(e))throw TypeError(`Statement transform returned a Sql value without a callable toStatement method`);if(typeof Reflect.apply(e,o,[`?`])!=`string`)throw TypeError(`Statement transform returned a Sql value whose toStatement method did not return a string`);a=o;continue}}catch(t){throw statementTransformFailure(e.extension,n,r,`returned an unreadable value`,normalizeUnreadableReturn(t))}let s;try{s=isThenable(o)}catch(t){throw statementTransformFailure(e.extension,n,r,`returned an unreadable value`,normalizeUnreadableReturn(t))}let c=s?`returned a promise or thenable`:`returned a non-Sql value`;throw statementTransformFailure(e.extension,n,r,c,TypeError(`Statement transform ${c}`))}return a}function isThenable(e){return n(e)||t(e)?t(Reflect.get(e,`then`)):!1}function normalizeThrown(e){return _(e)?e:Error(`Statement transform threw a non-Error value`)}function normalizeUnreadableReturn(e){return _(e)?e:Error(`Statement transform returned an unreadable value`)}function statementTransformFailure(e,t,n,i,a){return new r(`Extension "${e}" statement handler for ${t===void 0?n:`${t}.${n}`} ${i}.`,{cause:a,meta:{method:`statement`,model:t,operation:n}})}const U=Symbol(`viborm.batchDiagnosticParams`),W=[];Object.freeze(W);function snapshotDiagnosticParameters(e){let t=b(e,{includeParams:!0,includeSql:!0});return Object.freeze(t),t}function findUniqueExecutionContextIndex(e,t){if(!v(e))return t.length===1?0:void 0;let n=readTrustedErrorExecutionContext(e);if(!n?.correlationId)return t.length===1?0:void 0;let r;for(let e=0;e<t.length;e+=1){let i=t[e]?.context;if(i&&i.correlationId===n.correlationId&&i.model===n.model&&i.operation===n.operation){if(r!==void 0)return;r=e}}return r}function findUniqueErrorLogDetails(e,t){if(!t)return;let n=findUniqueExecutionContextIndex(e,t);return n===void 0?void 0:t[n]}function getErrorExecutionContext(e,t){return v(e)?R(readTrustedErrorExecutionContext(e),t,t.operation):t}function readTrustedErrorExecutionContext(e){let t=x.prototype.toJSON.call(e).meta;if(n(t))return{model:typeof t.model==`string`?t.model:void 0,operation:typeof t.operation==`string`?t.operation:void 0,correlationId:typeof t.correlationId==`string`?t.correlationId:void 0}}var SavepointQueue=class{queue=[];head=0;processing=!1;enqueue(e,t){return new Promise((n,r)=>{let i=!1,a;t&&(a=setTimeout(()=>{i=!0,r(t.onMaxWaitExceeded())},t.maxWaitMs)),this.queue.push(async()=>{if(a&&clearTimeout(a),!i)try{n(await e())}catch(e){r(e)}}),this.scheduleFlush()})}run(e,t){if(this.processing)return this.enqueue(e,t);this.processing=!0;let n=e(),release=()=>this.flush();return n.then(release,release),n}scheduleFlush(){this.processing||(this.processing=!0,queueMicrotask(()=>this.flush()))}async flush(){for(;this.head<this.queue.length;){let e=this.queue[this.head++];e&&await e()}this.queue=[],this.head=0,this.processing=!1}};const G=Object.freeze({includeParams:!1,includeSql:!1}),K=Object.freeze({execute:(e,t)=>t()}),q=Object.freeze({execute:e=>e()});function createDeferredDispatch(){let e,t=new Promise(t=>{e=t}),n=!1,settleDispatch=t=>{n||(n=!0,e?.(t))},execute=(e,t)=>{let n,r,i=new Promise((e,t)=>{n=e,r=t}),a=!1,start=()=>{if(a)return;a=!0;let e;try{e=t()}catch(e){r?.(e);return}e.then(n,r)};return settleDispatch(e(start)),i};return Object.freeze({dispatch:t,execute,settleSkipped:()=>settleDispatch(void 0)})}var J=class DriverInstrumentationBase{supportsTransactions=!0;supportsBatch=!1;supportsOrderedCommittedSegments=!1;maxBindParametersPerStatement=void 0;driverName;result;client=null;inTransaction=!1;serializeTransactions=!1;connectionQueue=new SavepointQueue;initPromise=null;closeRetryClient=null;isDisconnecting=!1;transactionPoisonError;boundContext;transactionOptionSupport(){return{isolationLevel:`unsupported`,isolationLevelReason:`this driver has not declared an isolation-level contract`,timeout:!1,timeoutReason:`this driver has not declared a timeout contract`,maxWait:`unsupported`,maxWaitReason:`this driver has not declared a maxWait contract`}}constructor(e,t,n={},r){V(this,`dialect`,e),this.driverName=t,this.boundContext=R(n),V(this,`migrationNamespaceAttestation`,r)}applyTrustedStatementTransforms(e,t,n){let r=(z(t)??z(this.boundContext))?.statement,i=e;if(r!==void 0&&r.length>0){let a=this.resolveExecutionContext(t,n);a.model!==`$schema`&&(i=applyStatementTransforms(e,a.model,a.operation??n,r))}return g(i,this.driverName,p(this.maxBindParametersPerStatement),`operation`),i}hasTrustedObservers(e){return((z(e)??z(this.boundContext))?.observe.length??0)>0}observeTrustedStatement(e,t,n){let r=z(e)?.observe;if(r===void 0||r.length===0)return t(void 0);let i=this.createOfficialStatementExecutionGate(e);return S(r,e.operation,e.model,()=>t(i),n,i?.readFacts)}observeTrustedDriverLifecycle(e,t,n,r,i){let a=z(t)?.observe;if(a===void 0||a.length===0)return r(void 0);let o=readOfficialCapability(t),s=o?.observesLifecycle===!0&&o.wants(n)?this.createOfficialDriverLifecycleExecutionGate(t,n):void 0;return C(e,a,t.operation,()=>r(s),i,s?.readFacts)}materializeTrustedBatchQuery(e,t){let n=s(e);if(n===void 0)return e;let r=this.applyTrustedStatementTransforms(n,t,`executeBatch`);return{sql:this.buildStatement(r),params:f(r.values,t),...e.context===void 0?{}:{context:e.context}}}observeTrustedBatchStatements(e,t,n,r){let i=z(t)?.observe;if(i===void 0||i.length===0)return n(e.map(e=>this.materializeTrustedBatchQuery(e,e.context??t)),void 0);let a=this.createOfficialStatementExecutionGate(t),o=!1,s=[],startAt=c=>{for(let n=c;n<e.length;n+=1){let c=e[n];if(c===void 0)continue;let l=c.context??t,u=o?void 0:a?.readFacts;return o=!0,S(i,l.operation,l.model,()=>(s.push(this.materializeTrustedBatchQuery(c,l)),startAt(n+1)),r,u)}return n(s,a)};return startAt(0)}createOfficialStatementExecutionGate(e){let t=readOfficialCapability(e);if(t?.observesLifecycle!==!0||!(t.wants(`statement`)||t.wants(`query-log`)||t.wants(`error-log`)))return;let n=createDeferredDispatch(),r,i=Object.freeze({kind:`statement`,dispatch:n.dispatch,complete:e=>{if(r===void 0){n.settleSkipped();return}let t=e.status===`failure`&&e.failure instanceof Error?e.failure:void 0;if(e.status===`failure`&&t===void 0)return;let i=t===void 0||r.forceErrorContext?void 0:findUniqueErrorLogDetails(t,r.members),a=i?.context??(t===void 0||r.forceErrorContext?r.context:getErrorExecutionContext(t,r.context)),o=readOfficialCapability(a);if(o===void 0)return;let s=o.wants(t===void 0?`query-log`:`error-log`);if(s||t&&o.wants(`statement`))return t!==void 0&&s&&ee(t),Object.freeze({kind:`statement`,endedAt:Date.now(),capability:o,...s?{}:{skipLog:!0},context:a,sql:i?.sql??r.sql,params:i?.params??r.params,...t===void 0?{}:{failure:t}})}});return Object.freeze({readFacts:()=>i,execute:(e,t)=>n.execute(t=>(r=Object.freeze({...e,driver:this,startedAt:Date.now(),start:t}),r),t)})}createOfficialDriverLifecycleExecutionGate(e,t){let n=createDeferredDispatch(),r=Object.freeze({kind:`driver-lifecycle`,dispatch:n.dispatch,complete:e=>(n.settleSkipped(),e.status===`failure`&&e.failure instanceof Error?Object.freeze({kind:`driver-lifecycle`,failure:e.failure}):void 0)});return Object.freeze({readFacts:()=>r,execute:r=>n.execute(n=>Object.freeze({driver:this,context:e,boundary:t,start:n}),r)})}buildStatement(e){switch(this.dialect){case`postgresql`:return e.toStatement(`$n`);case`sqlite`:case`mysql`:return e.toStatement(`?`);default:return e.toStatement()}}getBatchDiagnosticParameters(e){try{let t=Reflect.get(e,U);return Array.isArray(t)?t:this.getDiagnosticParameters(e.params??[],e.context)}catch{return this.getDiagnosticParameters(e.params??[],e.context)}}getDiagnosticParameters(e,t,n){return this.canDiscloseParameters(t)||n!==void 0&&n!==t&&this.canDiscloseParameters(n)?snapshotDiagnosticParameters(e):W}connectedClient(){if(!(this.getClient!==DriverInstrumentationBase.prototype.getClient||this.transactionPoisonError||this.isDisconnecting||this.closeRetryClient!==null))return this.client??void 0}async getClient(e={}){if(this.transactionPoisonError||this.isDisconnecting||this.closeRetryClient!==null)throw this.unavailableClientError(e);return this.client?this.client:await this.initializeClient(e)}unavailableClientError(e){return this.transactionPoisonError?new O(`Driver "${this.driverName}" is unavailable after transaction cleanup failed.`,{cause:this.transactionPoisonError,meta:{driver:this.driverName,model:e.model,operation:e.operation,correlationId:e.correlationId}}):this.connectionClosedError(this.isDisconnecting?`Database connection is closing`:`Database connection cleanup is incomplete`,e)}connectionClosedError(e,t){return new i(e,{code:y.CONNECTION_CLOSED,diagnostics:this.getErrorDisclosure(t),meta:{driver:this.driverName,model:t.model,operation:t.operation,correlationId:t.correlationId}})}async initializeClient(e){this.initPromise||=Promise.resolve().then(()=>this.initClient()).then(e=>(this.client=e,e));try{return await this.initPromise}catch(t){throw T(t,{driverName:this.driverName,model:e.model,operation:e.operation,correlationId:e.correlationId,callsite:L(e),diagnostics:this.getErrorDisclosure(e)})}}normalizeStatementFailure(e,t,n,r,i){return E(e,{driverName:this.driverName,dialect:this.dialect,model:r.model,operation:r.operation,correlationId:r.correlationId,callsite:L(r),query:t,params:n,diagnostics:this.getErrorDisclosure(r),forceContext:i})}async executeNormalizedStatement(e,t,n,r,i){try{return await r()}catch(r){throw this.normalizeStatementFailure(r,e,t,n,i)}}resolveExecutionContext(e,t){return R(e,this.boundContext,t)}canDiscloseParameters(e){let t=readOfficialCapability(e);return t!==void 0&&(t.diagnostics.includeParams===!0||t.wants(`parameters`))}getErrorDisclosure(e){return readOfficialCapability(e)?.diagnostics??G}};function readOfficialCapability(e){return w(z(e))}const Y=[`ReadUncommitted`,`ReadCommitted`,`RepeatableRead`,`Serializable`],methodForForm=e=>e===`batch`?`$transaction([...])`:`$transaction(callback)`;function invalidTransactionOptions(e,t){return new O(e,{code:y.INVALID_TRANSACTION_INPUT,meta:{driver:t.driverName,method:methodForForm(t.form)}})}function refuseTransactionOption(e,t,n){return new a(`Driver "${n.driverName}" cannot honor the "${e}" transaction option on ${methodForForm(n.form)}: ${t}`,{meta:{driver:n.driverName,method:methodForForm(n.form)}})}function transactionTimeoutError(e,t){return new O(`Transaction on driver "${t.driverName}" exceeded its timeout of ${e}ms and was rolled back.`,{code:y.TRANSACTION_TIMEOUT,meta:{driver:t.driverName,method:methodForForm(t.form)}})}function transactionMaxWaitError(e,t){return new O(`Transaction on driver "${t.driverName}" waited longer than maxWait (${e}ms) for a transaction slot and never started.`,{code:y.TRANSACTION_TIMEOUT,meta:{driver:t.driverName,method:methodForForm(t.form)}})}const isIsolationLevel=e=>Y.includes(e);function readDurationOption(e,t,n){if(typeof e!=`number`||!Number.isFinite(e)||e<=0)throw invalidTransactionOptions(`Transaction option "${t}" must be a positive finite number of milliseconds.`,n);return e}function parseTransactionOptions(e,t){if(e===void 0)return;if(!n(e))throw invalidTransactionOptions(`Transaction options must be an object.`,t);let r=t.form===`batch`?[`isolationLevel`]:[`isolationLevel`,`timeout`,`maxWait`];for(let n of Reflect.ownKeys(e))if(!(typeof n==`string`&&r.includes(n)))throw t.form===`batch`&&(n===`timeout`||n===`maxWait`)?invalidTransactionOptions(`Transaction option "${n}" is not available on $transaction([...]): an array of operations has no interactive window to bound. Use the callback form.`,t):invalidTransactionOptions(`Unknown transaction option "${String(n)}". Supported options are ${r.map(e=>`"${e}"`).join(`, `)}.`,t);let i={};if(e.isolationLevel!==void 0){if(!isIsolationLevel(e.isolationLevel))throw invalidTransactionOptions(`Unknown isolation level ${JSON.stringify(e.isolationLevel)}. Supported levels are ${Y.map(e=>`"${e}"`).join(`, `)}.`,t);i.isolationLevel=e.isolationLevel}return e.timeout!==void 0&&(i.timeout=readDurationOption(e.timeout,`timeout`,t)),e.maxWait!==void 0&&(i.maxWait=readDurationOption(e.maxWait,`maxWait`,t)),i}const X={ReadUncommitted:`READ UNCOMMITTED`,ReadCommitted:`READ COMMITTED`,RepeatableRead:`REPEATABLE READ`,Serializable:`SERIALIZABLE`};function isolationLevelStatement(e){return`SET TRANSACTION ISOLATION LEVEL ${X[e]}`}function resolveIsolationLevel(e,t,n){switch(t.isolationLevel){case`provider`:return{placement:`provider`};case`post-begin`:case`pre-begin`:return{placement:t.isolationLevel,statement:isolationLevelStatement(e)};case`serializable-only`:if(e===`Serializable`)return{placement:`serializable-only`};throw refuseTransactionOption(`isolationLevel`,`${e} is not available — ${t.isolationLevelReason??`this driver offers Serializable only`}.`,n);default:throw refuseTransactionOption(`isolationLevel`,t.isolationLevelReason??`this driver does not open a transaction that can be configured`,n)}}function resolveTransactionPlan(e,t,n){if(!e||e.isolationLevel===void 0&&e.timeout===void 0&&e.maxWait===void 0)return;let r=`unsupported`,i;if(e.isolationLevel!==void 0){let a=resolveIsolationLevel(e.isolationLevel,t,n);r=a.placement,i=a.statement}if(e.timeout!==void 0&&!t.timeout)throw refuseTransactionOption(`timeout`,t.timeoutReason??`this driver does not run an interactive callback that could be interrupted`,n);if(e.maxWait!==void 0&&t.maxWait===`unsupported`)throw refuseTransactionOption(`maxWait`,t.maxWaitReason??`this driver has no transaction-slot wait that VibORM can bound`,n);let a={};return r===`pre-begin`&&e.isolationLevel!==void 0&&(a.isolationLevel=e.isolationLevel),t.maxWait===`acquisition`&&e.maxWait!==void 0&&(a.maxWaitMs=e.maxWait),{...e.isolationLevel===void 0?{}:{isolationLevel:e.isolationLevel},...i===void 0?{}:{isolationStatement:i},isolationPlacement:r,...e.timeout===void 0?{}:{timeoutMs:e.timeout},...e.maxWait===void 0?{}:{maxWaitMs:e.maxWait},maxWaitMode:t.maxWait,...Object.keys(a).length===0?{}:{driverOptions:a}}}async function runWithTransactionTimeout(e,t,n,r=H){let i,a=new Promise((e,a)=>{i=r.setTimeout(()=>a(transactionTimeoutError(t,n)),t)}),o=e();o.catch(()=>void 0);try{return await Promise.race([o,a])}finally{i?.cancel()}}async function acquireWithMaxWait(e,t,n,r,i=H){let a=e();if(n===void 0)return a;let o,s=!1,c=new Promise((e,t)=>{o=i.setTimeout(()=>{s=!0,t(transactionMaxWaitError(n,r))},n)});a.catch(()=>void 0);try{return await Promise.race([a,c])}catch(e){throw s&&a.then(e=>{try{t(e)}catch{}},()=>void 0),e}finally{o?.cancel()}}const Z=new WeakMap;let Q,$;function physicalConnectionQueue(e){let t=Z.get(e);return t||(t=new SavepointQueue,Z.set(e,t)),t}function isConnectionScope(e){let t=Q?.getStore();return t!==void 0&&t.queue===e&&t.active}function connectionQueueWait(e,t){let n=e??(Q===null?5e3:void 0);return n===void 0?void 0:{maxWaitMs:n,onMaxWaitExceeded:()=>transactionMaxWaitError(n,t)}}async function withConnectionScope(e,t){if($??=import(`node:async_hooks`).then(({AsyncLocalStorage:e})=>{Q=new e}).catch(()=>{Q=null}),await $,Q===null)return t();if(!Q)throw Error(`Connection scope failed to initialize`);let n={queue:e,active:!0};return Q.run(n,async()=>{try{return await t()}finally{n.active=!1}})}function prepareAtomicBatch(e,t,n,r){let i=[],a=e.map(e=>{let r=e.params,a=R(e.context,t,`executeBatch`),o=r?f(r,a):void 0;o&&Object.freeze(o);let s={sql:e.sql,...o?{params:o}:{},context:a};u(e)&&(s=l(s)),m(e,s,o??[]);let c=n(o??[],a);return i.push(c),Object.defineProperty(s,U,{configurable:!1,enumerable:!1,value:c,writable:!1}),Object.freeze(s)}),o=a.map((e,n)=>({context:e.context??t,params:i[n]??W,sql:e.sql})),s=r?i:W;return r&&Object.freeze(s),{queries:a,diagnosticParams:s,members:o}}function toTransactionOperationError(e){return e instanceof Error?e:new O(`Transaction operation failed`,{cause:Error(`A transaction operation rejected without an Error`)})}function normalizeTransactionLifecycleError(e,t){try{if(!(e instanceof AggregateError))return t(e);let n=e.cause;return e.errors[0]===n?P(t(n),e.errors.slice(1).map(e=>t(e))):t(e)}catch{return t(e)}}function withoutTimeout(e){if(!e)return e;let{timeout:t,...n}=e;return n}var DriverTransactionBase=class extends J{runTransactionBody(e){return e()}assertBaseOperationAllowedDuringTransaction(e){if(isConnectionScope(this.connectionQueue))throw this.transactionBoundError(e)}transactionBoundError(e){return new O(`Driver "${this.driverName}" cannot use the originating client while its single connection is transaction-bound. Use the transaction client supplied to the callback.`,{meta:{driver:this.driverName,model:e.model,operation:e.operation,correlationId:e.correlationId,method:`$transaction(callback)`}})}async runConnectionTransactionLease(e){return withConnectionScope(this.connectionQueue,e)}resolveTransactionOptions(e,t){let n={driverName:this.driverName,form:t};return resolveTransactionPlan(parseTransactionOptions(e,n),this.transactionOptionSupport(),n)}assertTransactionOptionsSupported(e,t){this.resolveTransactionOptions(e,t)}readPostBeginIsolationStatement(e){if(e?.isolationPlacement===`post-begin`)return e.isolationStatement}_execute(e,t){return this.executeTypedStatement(e,t,this.executeNormalizedProvider)}async executeNormalizedProvider(e,t,n,r,i=!1){let a=i?await this.executeRaw(e,t,n,r):await this.execute(e,t,n,r);return d(a,{provider:this.driverName,operation:r.operation??(i?`executeRaw`:`execute`)}),a}async executeTypedStatement(e,t,n){let r=this.resolveExecutionContext(t,`execute`),i=this.hasTrustedObservers(r),a=i?void 0:this.applyTrustedStatementTransforms(e,r,`execute`);return this.dispatchStatement(r,i,t=>{try{return a??=this.applyTrustedStatementTransforms(e,r,`execute`),this.sendStatement(this.buildStatement(a),a.values,r,n,t)}catch(e){return Promise.reject(e)}})}dispatchStatement(e,t,n){let r=t?()=>this.observeTrustedStatement(e,n):n;return this.serializeTransactions&&!this.inTransaction?(this.assertBaseOperationAllowedDuringTransaction(e),this.connectionQueue.run(r,connectionQueueWait(void 0,{driverName:this.driverName,form:`callback`}))):r()}async sendStatement(e,t,n,r,i=K){let a=f(t,n),o=this.getDiagnosticParameters(a,n),s=this.connectedClient()??await this.getClient(n);return i.execute({context:n,forceErrorContext:!0,params:o,sql:e},()=>this.executeNormalizedStatement(e,o,n,()=>r.call(this,s,e,a,n),!0))}_prepare(e,t){let n=new A([...e.strings],[...e.values]),r={sql:this.buildStatement(n),params:[...n.values]};return c(r,n),r}async _executeRaw(e,t,n){let r=this.resolveExecutionContext(n,`executeRaw`);return this.dispatchStatement(r,this.hasTrustedObservers(r),n=>this.sendStatement(e,t??[],r,(e,t,n)=>this.executeNormalizedProvider(e,t,n,r,!0),n))}runProviderTransactionCore(e,t,n,r=q){let i=Symbol(`noCallbackFailure`),a=i,o=t?.timeoutMs===void 0?e:n=>runWithTransactionTimeout(()=>e(n),t.timeoutMs,{driverName:this.driverName,form:`callback`}),trackedCallback=async e=>{try{return await o(e)}catch(e){throw a=e,e}},s=this.readPostBeginIsolationStatement(t),providerCallback=async e=>(s&&await this.executeRaw(e,s,void 0,{...n,operation:`transaction`}),trackedCallback(e)),runTransaction=async()=>{let e=await this.getClient(n);try{return await this.transaction(e,providerCallback,n,t?.driverOptions)}catch(e){let normalizeTransactionFailure=e=>E(e,{driverName:this.driverName,dialect:this.dialect,model:n.model,operation:n.operation,correlationId:n.correlationId,diagnostics:this.getErrorDisclosure(n)});if(a!==i){if(e===a)throw e;let t=N(e,a).map(normalizeTransactionFailure),n=P(a,t);throw this.transactionCleanupFailed(n),n}let t=normalizeTransactionLifecycleError(e,normalizeTransactionFailure);throw(this.inTransaction||e instanceof I||e instanceof AggregateError&&e.errors[0]===e.cause&&e.errors.length>1)&&this.transactionCleanupFailed(t),t}};return r.execute(runTransaction)}observeTransactionLifecycle(e,t,n){let r=e===`transaction`?{phase:`pending`}:void 0,i=r?B(t,{readyToCommit:()=>{r.phase=`ready`},committed:()=>{r.phase=`committed`}}):t;return this.observeTrustedDriverLifecycle(e,t,e,async e=>{let t=await n(i,e);return r&&(r.phase=`committed`),t},r===void 0?void 0:()=>r.phase===`pending`?void 0:{commitCertainty:r.phase===`committed`?`committed`:`may-have-committed`})}async _transaction(e,t,n){let r=this.resolveTransactionOptions(t,`callback`);if(!this.supportsTransactions)throw M(this.driverName);let i=this.resolveExecutionContext(n,`transaction`),a=this.serializeTransactions&&!this.inTransaction;a&&this.assertBaseOperationAllowedDuringTransaction(i);let o=connectionQueueWait(r?.maxWaitMode===`queue`?r.maxWaitMs:void 0,{driverName:this.driverName,form:`callback`}),executeTransaction=(t,n)=>{let run=()=>this.runProviderTransactionCore(e,r,t,n);return a?this.connectionQueue.enqueue(()=>this.runConnectionTransactionLease(run),o):run()};return this.hasTrustedObservers(i)?this.observeTransactionLifecycle(`transaction`,i,executeTransaction):executeTransaction(i)}async withTransaction(e,t,n){let r=this.resolveTransactionOptions(t,`callback`),i=this.resolveExecutionContext(n,`transaction`),a=r?.timeoutMs,o=a===void 0?t:withoutTimeout(t),s;return this._transaction(async t=>{s=this.createTransactionBoundDriver(t,i);let n=s,scopedBody=()=>this.runTransactionBody(()=>e(n)),runBody=()=>a===void 0?scopedBody():runWithTransactionTimeout(scopedBody,a,{driverName:this.driverName,form:`callback`});try{let e=await runBody();return s.closeTransactionScope(),await s.waitForActiveOperations(),s.assertTransactionCommittable(),e}catch(e){s.closeTransactionScope(e),await s.waitForActiveOperations();let t=s.getTransactionFailure();throw t&&t!==e?j(e,t):e}},o,i)}async executeBatch(e,t,n,r,i){let a=n??{operation:`executeBatch`},o=[];try{for(let[n,r]of t.entries()){if(!r)continue;let t=r.context?this.resolveExecutionContext(r.context,r.context.operation??`executeBatch`):a,i=r,s=this.getBatchDiagnosticParameters(r),normalizeFailure=e=>E(e,{driverName:this.driverName,dialect:this.dialect,model:t.model,operation:t.operation,correlationId:t.correlationId,statementIndex:n,query:i.sql,params:s,diagnostics:this.getErrorDisclosure(t),forceContext:!0});o.push(await new Promise((n,a)=>{let o,c,l=new Promise((e,t)=>{o=e,c=t}),d=this.observeTrustedStatement(t,(a=K)=>{i=this.materializeTrustedBatchQuery(r,t),s=this.getBatchDiagnosticParameters(i);let{sql:f,params:p}=i,m=u(i);return n({execute:async()=>{try{o(await a.execute({context:t,forceErrorContext:!0,params:s,sql:f},()=>this.executeNormalizedStatement(f,s,t,()=>m?this.executeRaw(e,f,p,t):this.execute(e,f,p??[],t),!0)))}catch(e){c(normalizeFailure(e))}return d},cancel:e=>(c(e),d)}),l});d.catch(a)}).catch(e=>{throw normalizeFailure(e)}))}let n=[];for(let e of o)n.push(await e.execute());return n}catch(e){throw await Promise.allSettled(o.map(t=>t.cancel(e))),e}}async _executeBatch(e,t,n,r){if(this.resolveTransactionOptions(t,`batch`),e.length===0)return[];if(!(this.supportsBatch||this.supportsTransactions))throw new O(`Driver "${this.driverName}" supports neither transactions nor atomic batch execution.`,{meta:{driver:this.driverName,method:`$transaction([...])`}});let i=this.resolveExecutionContext(n,`executeBatch`),a={provider:this.driverName,operation:i.operation??`executeBatch`};if(this.supportsBatch){if(r&&!this.supportsOrderedCommittedSegments)throw new O(`Driver '${this.driverName}' cannot acknowledge ordered committed segments.`);let executeNativeBatch=async(n=e,o=K)=>{let{queries:s,diagnosticParams:c,members:l}=prepareAtomicBatch(n,i,(e,t)=>this.getDiagnosticParameters(e,t,i),this.canDiscloseParameters(i)),u=s.map(e=>e.sql).join(`; `),d=await this.getClient(i),executeProvider=async()=>{try{let e=await this.executeBatch(d,s,i,r,t);return h(e,s.length,a),e}catch(e){let t=findUniqueExecutionContextIndex(e,s),n=t===void 0?void 0:s[t],r=n?.context??i;throw E(e,{driverName:this.driverName,dialect:this.dialect,model:r.model,operation:r.operation,correlationId:r.correlationId,statementIndex:n?t:void 0,query:n?n.sql:u,params:n?this.getBatchDiagnosticParameters(n):c,diagnostics:this.getErrorDisclosure(r),forceContext:!0})}};return o.execute({context:i,forceErrorContext:!1,members:l,params:c,sql:u},()=>this.executeNormalizedStatement(u,c,i,executeProvider,!1))},submitNativeBatch=()=>this.observeTrustedBatchStatements(e,i,executeNativeBatch);return this.serializeTransactions&&!this.inTransaction?(this.assertBaseOperationAllowedDuringTransaction(i),this.connectionQueue.enqueue(submitNativeBatch,connectionQueueWait(void 0,{driverName:this.driverName,form:`batch`}))):submitNativeBatch()}let{queries:o}=prepareAtomicBatch(e,i,(e,t)=>this.getDiagnosticParameters(e,t,i),this.canDiscloseParameters(i)),runSequentialBatch=async e=>{let t=await this.executeBatch(e,o,i);return h(t,o.length,a),t};return this.inTransaction?runSequentialBatch(await this.getClient(i)):this._transaction(runSequentialBatch,t,i)}transactionCleanupFailed(e){this.transactionPoisonError??=e}};function observePromiseRejection(e,t){return new te(e,t)}var te=class RejectionObservedPromise{[Symbol.toStringTag]=`Promise`;onRejectionObserved;promise;constructor(e,t){this.promise=e,this.onRejectionObserved=t}then(e,t){return t&&this.onRejectionObserved(),new RejectionObservedPromise(this.promise.then(e,t),this.onRejectionObserved)}catch(e){return e&&this.onRejectionObserved(),new RejectionObservedPromise(this.promise.catch(e),this.onRejectionObserved)}finally(e){return new RejectionObservedPromise(this.promise.finally(e),this.onRejectionObserved)}},Driver=class extends DriverTransactionBase{createTransactionBoundDriver(e,t){return new ne(this,e,t)}_connect(e){return this.runConnectionLifecycle(`connect`,e,(e,t)=>t.execute(async()=>{await this.getClient(e)}))}_disconnect(e){return this.runConnectionLifecycle(`disconnect`,e,async(e,t)=>{if(this.isDisconnecting)throw this.connectionClosedError(`Database connection is closing`,e);this.isDisconnecting=!0;let doDisconnect=async()=>{if(this.initPromise)try{await this.initPromise}catch{}let t=this.closeRetryClient??this.client;if(!t){this.transactionPoisonError=void 0;return}try{await this.closeClient(t)}catch(n){throw this.closeRetryClient=t,this.client===t&&(this.client=null),this.initPromise=null,T(n,{driverName:this.driverName,model:e.model,operation:e.operation,correlationId:e.correlationId,diagnostics:this.getErrorDisclosure(e)},`Database disconnection failed`)}},n=t.execute(doDisconnect);try{await n,this.client=null,this.initPromise=null,this.closeRetryClient=null,this.transactionPoisonError=void 0}finally{this.isDisconnecting=!1}})}async runConnectionLifecycle(e,t,n){let r=this.resolveExecutionContext(t,e),run=(e=q)=>n(r,e),i=this.serializeTransactions&&!this.inTransaction;return i&&this.assertBaseOperationAllowedDuringTransaction(r),this.hasTrustedObservers(r)?this.observeTrustedDriverLifecycle(`connection`,r,e,i?e=>this.connectionQueue.enqueue(()=>run(e)):run):i?this.connectionQueue.enqueue(run):run()}async disconnect(){return this._disconnect()}};function disposeDriver(){return this.disconnect()}o!==void 0&&Object.defineProperty(Driver.prototype,o,{configurable:!0,writable:!0,enumerable:!1,value:disposeDriver});var ne=class TransactionBoundDriver extends Driver{baseDriver;parentTransactionDriver;tx;scopeQueue=new SavepointQueue;activeOperations=new Set;nestedTransactionObservations=new Set;transactionClosed=!1;signalScopeClosed;scopeClosed;isSavepointActive=!1;hasAdmittedWithTransactionDispatch=!1;rollbackOnlyError;result;inTransaction=!0;supportsTransactions;supportsBatch;supportsOrderedCommittedSegments;maxBindParametersPerStatement;constructor(e,t,n){super(e.dialect,e.driverName,n,e.migrationNamespaceAttestation);let resolveClosed=()=>void 0;this.scopeClosed=new Promise(e=>{resolveClosed=e}),this.signalScopeClosed=resolveClosed,this.baseDriver=e,this.parentTransactionDriver=e instanceof TransactionBoundDriver?e:void 0,this.tx=t,V(this,`adapter`,e.adapter),this.result=e.result,this.supportsTransactions=e.supportsTransactions,this.supportsBatch=e.supportsBatch,this.supportsOrderedCommittedSegments=e.supportsOrderedCommittedSegments,this.maxBindParametersPerStatement=e.maxBindParametersPerStatement}async getClient(e){return this.tx}closeTransactionScope(...e){this.transactionClosed=!0,e.length>0&&this.signalScopeClosed(e[0]);for(let e of this.nestedTransactionObservations)e.failure&&!e.isRejectionObserved&&this.markCurrentScopeRollbackOnly(e.failure)}runTransactionBody(e){return Promise.race([e(),this.scopeClosed.then(e=>{throw e})])}async waitForActiveOperations(){for(;this.activeOperations.size>0;)await Promise.allSettled([...this.activeOperations])}getTransactionFailure(){return this.parentTransactionDriver?.getTransactionFailure()??this.rollbackOnlyError}assertTransactionCommittable(){if(this.parentTransactionDriver?.assertTransactionCommittable(),this.rollbackOnlyError)throw this.rollbackOnlyError}markCurrentScopeRollbackOnly(e){this.rollbackOnlyError??=e}markRootTransactionRollbackOnly(e){if(this.parentTransactionDriver){this.parentTransactionDriver.markRootTransactionRollbackOnly(e);return}this.rollbackOnlyError??=e}assertRollbackOnlyUsable(){let e=this.getTransactionFailure();if(e)throw j(D(e,new O(`Transaction for driver "${this.driverName}" is rollback-only after an earlier failure; no further statements can execute.`,{cause:e,meta:{driver:this.driverName,method:`$transaction`}})),e)}assertTransactionOpen(){if(this.parentTransactionDriver?.assertTransactionOpen(),this.assertRollbackOnlyUsable(),this.transactionClosed)throw new O(`Transaction for driver "${this.driverName}" is no longer active.`,{meta:{driver:this.driverName,method:`$transaction`}})}getActiveSavepointUseError(e){if(this.isSavepointActive)return new O(`Transaction scope for driver "${this.driverName}" cannot be used while its nested transaction is active. At every nesting level, use the transaction client supplied to that callback.`,{meta:{driver:this.driverName,method:e}})}enqueueScopeOperation(e){return this.scopeQueue.enqueue(async()=>{this.assertRollbackOnlyUsable();try{return await e()}catch(e){throw this.markCurrentScopeRollbackOnly(toTransactionOperationError(e)),e}})}trackTransactionOperation(e,t){let n=t?void 0:{isRejectionObserved:!1};n&&this.nestedTransactionObservations.add(n);let r=Promise.resolve().then(()=>(this.assertTransactionOpen(),e()));return this.activeOperations.add(r),r.then(()=>{this.activeOperations.delete(r)},e=>{this.activeOperations.delete(r);let t=toTransactionOperationError(e);if(n){n.failure=t,this.transactionClosed&&!n.isRejectionObserved&&this.markCurrentScopeRollbackOnly(t);return}this.markCurrentScopeRollbackOnly(t)}).catch(()=>void 0),n?observePromiseRejection(r,()=>{n.isRejectionObserved=!0}):r}scoped(e,t){let n=this.getActiveSavepointUseError(e);return n?Promise.reject(n):this.trackTransactionOperation(()=>this.enqueueScopeOperation(t),!0)}_execute(e,t){return this.scoped(`execute`,()=>super._execute(e,t))}_executeRaw(e,t,n){return this.scoped(`executeRaw`,()=>super._executeRaw(e,t,n))}transactionOptionSupport(){return{isolationLevel:`unsupported`,isolationLevelReason:`a nested transaction runs as a SAVEPOINT inside the outer transaction, whose isolation level is already fixed and cannot be changed mid-transaction — set it on the outermost $transaction`,timeout:!0,maxWait:`unsupported`,maxWaitReason:`a nested transaction reuses the outer transaction's connection, so there is no transaction slot to wait for`}}resolveNestedOptions(e,t){try{return this.resolveTransactionOptions(e,t)}catch(e){return toTransactionOperationError(e)}}_executeBatch(e,t,n,r){let i=this.resolveNestedOptions(t,`batch`);return i instanceof Error?Promise.reject(i):e.length===0?Promise.resolve([]):this.scoped(`$transaction([...])`,()=>super._executeBatch(e,t,n,r))}_transaction(e,t,n){let r=this.resolveNestedOptions(t,`callback`);if(r instanceof Error)return Promise.reject(r);let i=this.hasAdmittedWithTransactionDispatch;if(!i){let e=this.getActiveSavepointUseError(`$transaction(callback)`);if(e)return Promise.reject(e);try{this.assertTransactionOpen()}catch(e){return Promise.reject(e)}}let a=this.resolveExecutionContext(n,`transaction`),o=this.hasTrustedObservers(a),executeTransaction=(t=q)=>this.scopeQueue.enqueue(async()=>{this.assertRollbackOnlyUsable(),this.isSavepointActive=!0;try{return await this.runProviderTransactionCore(e,r,a,t)}finally{this.isSavepointActive=!1}}),s=o?()=>this.observeTransactionLifecycle(`savepoint`,a,(e,t)=>executeTransaction(t)):void 0;return i?s?s():executeTransaction():this.trackTransactionOperation(s??executeTransaction,!1)}withTransaction(e,t,n){let r=this.resolveNestedOptions(t,`callback`);if(r instanceof Error)return Promise.reject(r);let i=this.getActiveSavepointUseError(`$transaction(callback)`);return i?Promise.reject(i):this.trackTransactionOperation(()=>{this.hasAdmittedWithTransactionDispatch=!0;try{return super.withTransaction(e,t,n)}finally{this.hasAdmittedWithTransactionDispatch=!1}},!1)}initClient(){throw Error(`TransactionBoundDriver does not initialize clients`)}closeClient(){return Promise.resolve()}execute(e,t,n,r){return this.baseDriver.execute(e,t,n,r)}executeRaw(e,t,n,r){return this.baseDriver.executeRaw(e,t,n,r)}async transaction(e,t,n){return this.assertTransactionCommittable(),F(e=>this.baseDriver.executeRaw(this.tx,e,void 0,n??{}),()=>t(this.tx))}transactionCleanupFailed(e){this.markRootTransactionRollbackOnly(e)}async disconnect(){}};export{isolationLevelStatement as i,physicalConnectionQueue as n,acquireWithMaxWait as r,Driver as t};
2
- //# sourceMappingURL=driver-yCYqzIQg.mjs.map