viborm 1.14.2 → 1.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (483) hide show
  1. package/dist/adapter-namespace-DwFnfpED.mjs +2 -0
  2. package/dist/{adapter-namespace-DaRiTIIf.mjs.map → adapter-namespace-DwFnfpED.mjs.map} +1 -1
  3. package/dist/adapters.d.mts +26 -10
  4. package/dist/adapters.mjs +1 -1
  5. package/dist/args-7WgBFd_f.mjs +2 -0
  6. package/dist/{args-764KdWMr.mjs.map → args-7WgBFd_f.mjs.map} +1 -1
  7. package/dist/array-literal-BOzj0E2u.mjs +2 -0
  8. package/dist/{array-literal-DHinAnVs.mjs.map → array-literal-BOzj0E2u.mjs.map} +1 -1
  9. package/dist/base-17NSFtrA.mjs +2 -0
  10. package/dist/base-17NSFtrA.mjs.map +1 -0
  11. package/dist/batch-refs-Bd8HvwUc.mjs +2 -0
  12. package/dist/{batch-refs-C-gx7A4-.mjs.map → batch-refs-Bd8HvwUc.mjs.map} +1 -1
  13. package/dist/better-auth.d.mts +116 -0
  14. package/dist/better-auth.mjs +6 -0
  15. package/dist/better-auth.mjs.map +1 -0
  16. package/dist/bind-parameter-capacity-BAFQM9Jt.mjs +2 -0
  17. package/dist/{bind-parameter-capacity-BMD-bxMO.mjs.map → bind-parameter-capacity-BAFQM9Jt.mjs.map} +1 -1
  18. package/dist/bun-sql.d.mts +1 -1
  19. package/dist/bun-sql.mjs +1 -1
  20. package/dist/bun-sql.mjs.map +1 -1
  21. package/dist/bun-sqlite.d.mts +1 -1
  22. package/dist/bun-sqlite.mjs +1 -1
  23. package/dist/bun-sqlite.mjs.map +1 -1
  24. package/dist/cache/cloudflare-kv.d.mts +1 -1
  25. package/dist/cache/cloudflare-kv.mjs +1 -1
  26. package/dist/cache/cloudflare-kv.mjs.map +1 -1
  27. package/dist/cache/memory.d.mts +1 -1
  28. package/dist/cache/memory.mjs +1 -1
  29. package/dist/cache/memory.mjs.map +1 -1
  30. package/dist/cache.d.mts +2 -2
  31. package/dist/cache.mjs +1 -1
  32. package/dist/cache.mjs.map +1 -1
  33. package/dist/call-0bd_B9Vp.mjs +2 -0
  34. package/dist/{call-Cz8XUmrl.mjs.map → call-0bd_B9Vp.mjs.map} +1 -1
  35. package/dist/cli.mjs +6 -6
  36. package/dist/cli.mjs.map +1 -1
  37. package/dist/client-D7sWgUt2.mjs +2 -0
  38. package/dist/client-D7sWgUt2.mjs.map +1 -0
  39. package/dist/client-DEfFqv4S.mjs +9 -0
  40. package/dist/client-DEfFqv4S.mjs.map +1 -0
  41. package/dist/{client-CRxfhw2y.d.mts → client-Dlz3-2JC.d.mts} +3 -3
  42. package/dist/client.d.mts +3 -3
  43. package/dist/client.mjs +1 -1
  44. package/dist/client.mjs.map +1 -1
  45. package/dist/config.d.mts +2 -2
  46. package/dist/config.mjs +1 -1
  47. package/dist/confine-CyI9IwjC.mjs +2 -0
  48. package/dist/{confine-DqFBTUw6.mjs.map → confine-CyI9IwjC.mjs.map} +1 -1
  49. package/dist/coordination-BxMskOgi.mjs +2 -0
  50. package/dist/coordination-BxMskOgi.mjs.map +1 -0
  51. package/dist/d1.d.mts +2 -30
  52. package/dist/d1.mjs +1 -1
  53. package/dist/d1.mjs.map +1 -1
  54. package/dist/{database-adapter-BGqvjeEy.d.mts → database-adapter-BMjJiBFm.d.mts} +8476 -8386
  55. package/dist/datetime-physical-codec-DAF7WJpy.mjs +2 -0
  56. package/dist/datetime-physical-codec-DAF7WJpy.mjs.map +1 -0
  57. package/dist/defaults-DAPb-tJ4.mjs +2 -0
  58. package/dist/{defaults-DwOHWI_M.mjs.map → defaults-DAPb-tJ4.mjs.map} +1 -1
  59. package/dist/{document-BVTQ-cF-.d.mts → document-CHaVF7Vn.d.mts} +36 -2
  60. package/dist/{driver-BBEmaJZy.d.mts → driver-BvTixv-m.d.mts} +1 -1
  61. package/dist/driver-diagnostics-aQ54bArn.mjs +2 -0
  62. package/dist/{driver-diagnostics-DW9NdckJ.mjs.map → driver-diagnostics-aQ54bArn.mjs.map} +1 -1
  63. package/dist/driver-kiIQS_Fd.mjs +2 -0
  64. package/dist/driver-kiIQS_Fd.mjs.map +1 -0
  65. package/dist/driver-lShUkDmf.mjs +2 -0
  66. package/dist/driver-lShUkDmf.mjs.map +1 -0
  67. package/dist/driver.d.mts +1 -1
  68. package/dist/driver.mjs +1 -1
  69. package/dist/durable-object.d.mts +1 -1
  70. package/dist/durable-object.mjs +2 -2
  71. package/dist/durable-object.mjs.map +1 -1
  72. package/dist/error-mapping-B9rSvgG9.mjs +2 -0
  73. package/dist/error-mapping-B9rSvgG9.mjs.map +1 -0
  74. package/dist/every-JpbiHdMb.mjs +2 -0
  75. package/dist/{every-tOgQmaIE.mjs.map → every-JpbiHdMb.mjs.map} +1 -1
  76. package/dist/execution-context-couU2tgh.mjs +2 -0
  77. package/dist/execution-context-couU2tgh.mjs.map +1 -0
  78. package/dist/{exports-COCJ8f2f.d.mts → exports-DYnTfvQo.d.mts} +1 -1
  79. package/dist/extension-Dh1ddrlA.mjs +2 -0
  80. package/dist/{extension-CGepsF-p.mjs.map → extension-Dh1ddrlA.mjs.map} +1 -1
  81. package/dist/fs-estate-n-QpsFqb.mjs +2 -0
  82. package/dist/{fs-estate-D1Nsg9G1.mjs.map → fs-estate-n-QpsFqb.mjs.map} +1 -1
  83. package/dist/geo-area-codec-Bti2PA2i.mjs +2 -0
  84. package/dist/geo-area-codec-Bti2PA2i.mjs.map +1 -0
  85. package/dist/id-domain-Cg65TLZ-.mjs +2 -0
  86. package/dist/id-domain-Cg65TLZ-.mjs.map +1 -0
  87. package/dist/identifier-conversion-BTDxDwDB.mjs +2 -0
  88. package/dist/identifier-conversion-BTDxDwDB.mjs.map +1 -0
  89. package/dist/identifiers-BxOf57qy.mjs +2 -0
  90. package/dist/identifiers-BxOf57qy.mjs.map +1 -0
  91. package/dist/identity-CJlRQA-m.mjs +2 -0
  92. package/dist/identity-CJlRQA-m.mjs.map +1 -0
  93. package/dist/index.d.mts +3 -3
  94. package/dist/index.mjs +1 -1
  95. package/dist/index.mjs.map +1 -1
  96. package/dist/instrumentation.d.mts +1 -1
  97. package/dist/instrumentation.mjs +1 -1
  98. package/dist/instrumentation.mjs.map +1 -1
  99. package/dist/introspect-q3Rf_Xv8.mjs +2 -0
  100. package/dist/introspect-q3Rf_Xv8.mjs.map +1 -0
  101. package/dist/json-CsAdz9pg.mjs +2 -0
  102. package/dist/json-CsAdz9pg.mjs.map +1 -0
  103. package/dist/json-number-C09rsm1g.mjs +2 -0
  104. package/dist/{json-number-AI-SdUUn.mjs.map → json-number-C09rsm1g.mjs.map} +1 -1
  105. package/dist/json-parameter-D7hDrVKw.mjs +2 -0
  106. package/dist/{json-parameter-oQ8nGaKr.mjs.map → json-parameter-D7hDrVKw.mjs.map} +1 -1
  107. package/dist/judge-words-k5GCc4cV.mjs +2 -0
  108. package/dist/judge-words-k5GCc4cV.mjs.map +1 -0
  109. package/dist/key-BDH6oTyC.mjs +2 -0
  110. package/dist/key-BDH6oTyC.mjs.map +1 -0
  111. package/dist/keys-CIal55WQ.mjs +2 -0
  112. package/dist/{keys-BQxM4c_a.mjs.map → keys-CIal55WQ.mjs.map} +1 -1
  113. package/dist/keys-DZdKAd4n.mjs +2 -0
  114. package/dist/keys-DZdKAd4n.mjs.map +1 -0
  115. package/dist/libsql-DEZ0uhK2.mjs +3 -0
  116. package/dist/libsql-DEZ0uhK2.mjs.map +1 -0
  117. package/dist/libsql.d.mts +2 -20
  118. package/dist/libsql.mjs +1 -1
  119. package/dist/libsql.mjs.map +1 -1
  120. package/dist/light-D2wNSbzY.mjs +2 -0
  121. package/dist/{light-BkJe3-yW.mjs.map → light-D2wNSbzY.mjs.map} +1 -1
  122. package/dist/memory-BaGWNdvk.mjs +2 -0
  123. package/dist/{memory-G4cSuc6A.mjs.map → memory-BaGWNdvk.mjs.map} +1 -1
  124. package/dist/methods-part-BaNx3o7b.mjs +2 -0
  125. package/dist/methods-part-BaNx3o7b.mjs.map +1 -0
  126. package/dist/migrations/mysql.d.mts +5 -5
  127. package/dist/migrations/mysql.mjs +1 -1
  128. package/dist/migrations/postgres.d.mts +5 -5
  129. package/dist/migrations/postgres.mjs +1 -1
  130. package/dist/migrations/snowflake.d.mts +5 -5
  131. package/dist/migrations/snowflake.mjs +1 -1
  132. package/dist/migrations/sqlite.d.mts +5 -5
  133. package/dist/migrations/sqlite.mjs +1 -1
  134. package/dist/migrations/storage/durable-object.d.mts +1 -1
  135. package/dist/migrations/storage/durable-object.mjs +1 -1
  136. package/dist/migrations/storage/durable-object.mjs.map +1 -1
  137. package/dist/migrations/storage/fs.d.mts +1 -1
  138. package/dist/migrations/storage/fs.mjs +1 -1
  139. package/dist/migrations/storage/r2.d.mts +1 -1
  140. package/dist/migrations/storage/r2.mjs +1 -1
  141. package/dist/migrations/storage/r2.mjs.map +1 -1
  142. package/dist/migrations/surrealdb.d.mts +5 -5
  143. package/dist/migrations/surrealdb.mjs +1 -1
  144. package/dist/migrations/tenant.d.mts +3 -3
  145. package/dist/migrations/tenant.mjs +1 -1
  146. package/dist/migrations/tenant.mjs.map +1 -1
  147. package/dist/migrations-DIUltjr3.mjs +2 -0
  148. package/dist/{migrations-BMiRjR-N.mjs.map → migrations-DIUltjr3.mjs.map} +1 -1
  149. package/dist/migrations.d.mts +5 -5
  150. package/dist/migrations.mjs +1 -1
  151. package/dist/model-Dtd37Sky.mjs +2 -0
  152. package/dist/model-Dtd37Sky.mjs.map +1 -0
  153. package/dist/mysql-BFPF8xyv.mjs +9 -0
  154. package/dist/mysql-BFPF8xyv.mjs.map +1 -0
  155. package/dist/mysql-adapter-BFWYPoM0.mjs +2 -0
  156. package/dist/mysql-adapter-BFWYPoM0.mjs.map +1 -0
  157. package/dist/mysql2.d.mts +2 -27
  158. package/dist/mysql2.mjs +1 -1
  159. package/dist/mysql2.mjs.map +1 -1
  160. package/dist/named-statements-CkOOD__I.mjs +2 -0
  161. package/dist/named-statements-CkOOD__I.mjs.map +1 -0
  162. package/dist/named-statements-NF7Iycjk.d.mts +13 -0
  163. package/dist/native-types-1ewJXVks.mjs +2 -0
  164. package/dist/native-types-1ewJXVks.mjs.map +1 -0
  165. package/dist/neon-http.d.mts +1 -1
  166. package/dist/neon-http.mjs +1 -1
  167. package/dist/neon-http.mjs.map +1 -1
  168. package/dist/normalized-result-D7nVkF36.mjs +2 -0
  169. package/dist/normalized-result-D7nVkF36.mjs.map +1 -0
  170. package/dist/{object-store-B_YMoW8u.d.mts → object-store-C4qmW7xf.d.mts} +4 -4
  171. package/dist/object-store-Chq1PMYz.mjs +2 -0
  172. package/dist/object-store-Chq1PMYz.mjs.map +1 -0
  173. package/dist/on-ZkOVmE4-.mjs +2 -0
  174. package/dist/{on-ylYaKuRu.mjs.map → on-ZkOVmE4-.mjs.map} +1 -1
  175. package/dist/on.d.mts +1 -1
  176. package/dist/on.mjs +1 -1
  177. package/dist/on.mjs.map +1 -1
  178. package/dist/ordering/keys.mjs +1 -1
  179. package/dist/ordering.d.mts +9 -3
  180. package/dist/ordering.mjs +10 -10
  181. package/dist/ordering.mjs.map +1 -1
  182. package/dist/pending-operation-D4gUKMxD.mjs +2 -0
  183. package/dist/pending-operation-D4gUKMxD.mjs.map +1 -0
  184. package/dist/permissions.d.mts +1 -1
  185. package/dist/permissions.mjs +1 -1
  186. package/dist/permissions.mjs.map +1 -1
  187. package/dist/pg.d.mts +16 -99
  188. package/dist/pg.mjs +1 -1
  189. package/dist/pg.mjs.map +1 -1
  190. package/dist/pglite.d.mts +3 -1
  191. package/dist/pglite.mjs +1 -1
  192. package/dist/pglite.mjs.map +1 -1
  193. package/dist/physical-DO4PEYcc.mjs +2 -0
  194. package/dist/physical-DO4PEYcc.mjs.map +1 -0
  195. package/dist/pinned-session-Y7-2pRBJ.mjs +2 -0
  196. package/dist/pinned-session-Y7-2pRBJ.mjs.map +1 -0
  197. package/dist/planetscale.d.mts +1 -1
  198. package/dist/planetscale.mjs +1 -1
  199. package/dist/planetscale.mjs.map +1 -1
  200. package/dist/{planner-DHjdvjwk.d.mts → planner-C-zjj19U.d.mts} +123 -1
  201. package/dist/postgres-DQQE2ys_.mjs +34 -0
  202. package/dist/postgres-DQQE2ys_.mjs.map +1 -0
  203. package/dist/postgres-adapter-BpLizOaK.mjs +2 -0
  204. package/dist/{postgres-adapter-axapXX8d.mjs.map → postgres-adapter-BpLizOaK.mjs.map} +1 -1
  205. package/dist/postgres-adapter-psTVfuw7.mjs +2 -0
  206. package/dist/postgres-adapter-psTVfuw7.mjs.map +1 -0
  207. package/dist/postgres-result-133boRW-.mjs +2 -0
  208. package/dist/postgres-result-133boRW-.mjs.map +1 -0
  209. package/dist/postgres.d.mts +27 -59
  210. package/dist/postgres.mjs +1 -1
  211. package/dist/postgres.mjs.map +1 -1
  212. package/dist/provider-limits-Bcsz0EJv.mjs +2 -0
  213. package/dist/provider-limits-Bcsz0EJv.mjs.map +1 -0
  214. package/dist/provider-parameter-snapshot-cyTUDutH.mjs +2 -0
  215. package/dist/provider-parameter-snapshot-cyTUDutH.mjs.map +1 -0
  216. package/dist/quantized-BKBs0joq.mjs +2 -0
  217. package/dist/quantized-BKBs0joq.mjs.map +1 -0
  218. package/dist/query-BTb6iakn.mjs +2 -0
  219. package/dist/query-BTb6iakn.mjs.map +1 -0
  220. package/dist/query-backend-TisPjCPF.mjs +2 -0
  221. package/dist/query-backend-TisPjCPF.mjs.map +1 -0
  222. package/dist/query-inspection-DwYBKSDG.mjs +2 -0
  223. package/dist/query-inspection-DwYBKSDG.mjs.map +1 -0
  224. package/dist/raw-DqEb71JZ.mjs +2 -0
  225. package/dist/raw-DqEb71JZ.mjs.map +1 -0
  226. package/dist/relation-bound-CSNKLyDy.mjs +2 -0
  227. package/dist/{relation-bound-ku_cMdye.mjs.map → relation-bound-CSNKLyDy.mjs.map} +1 -1
  228. package/dist/result-parsing-BbffueEX.mjs +2 -0
  229. package/dist/{result-parsing-B0Y4KGDT.mjs.map → result-parsing-BbffueEX.mjs.map} +1 -1
  230. package/dist/routed-operations-CcKOdn51.mjs +2 -0
  231. package/dist/{routed-operations-wytpbYKv.mjs.map → routed-operations-CcKOdn51.mjs.map} +1 -1
  232. package/dist/rows-of-Bgl9GVtK.mjs +2 -0
  233. package/dist/rows-of-Bgl9GVtK.mjs.map +1 -0
  234. package/dist/rule-words-DMbQuvD2.mjs +2 -0
  235. package/dist/{rule-words-ZIGm7cDm.mjs.map → rule-words-DMbQuvD2.mjs.map} +1 -1
  236. package/dist/scalar-Dm9brvAU.mjs +4 -0
  237. package/dist/scalar-Dm9brvAU.mjs.map +1 -0
  238. package/dist/schema/introspect.d.mts +2 -2
  239. package/dist/schema/introspect.mjs +1 -1
  240. package/dist/schema/json.d.mts +6 -4
  241. package/dist/schema/json.mjs +1 -1
  242. package/dist/schema-DDkAUfOb.mjs +2 -0
  243. package/dist/schema-DDkAUfOb.mjs.map +1 -0
  244. package/dist/schema-DqR_Kcje.mjs +2 -0
  245. package/dist/schema-DqR_Kcje.mjs.map +1 -0
  246. package/dist/schema-introspection-Bbo4DN_d.mjs +4 -0
  247. package/dist/schema-introspection-Bbo4DN_d.mjs.map +1 -0
  248. package/dist/schema.d.mts +2 -2
  249. package/dist/schema.mjs +1 -1
  250. package/dist/select-assembly-CEpNu-Gw.mjs +2 -0
  251. package/dist/select-assembly-CEpNu-Gw.mjs.map +1 -0
  252. package/dist/serializer-ettLu5xG.mjs +33 -0
  253. package/dist/serializer-ettLu5xG.mjs.map +1 -0
  254. package/dist/settle-Pui-1tfJ.mjs +2 -0
  255. package/dist/{settle-1cy5x_52.mjs.map → settle-Pui-1tfJ.mjs.map} +1 -1
  256. package/dist/settled-DYYPcaBX.mjs +2 -0
  257. package/dist/{settled-BjyuA76m.mjs.map → settled-DYYPcaBX.mjs.map} +1 -1
  258. package/dist/snowflake-BfF8xwfP.mjs +2 -0
  259. package/dist/{snowflake-UOCC820W.mjs.map → snowflake-BfF8xwfP.mjs.map} +1 -1
  260. package/dist/snowflake.d.mts +3 -3
  261. package/dist/snowflake.mjs +2 -2
  262. package/dist/snowflake.mjs.map +1 -1
  263. package/dist/soft-delete.d.mts +9 -3
  264. package/dist/soft-delete.mjs +1 -1
  265. package/dist/soft-delete.mjs.map +1 -1
  266. package/dist/{spans-XDUFeTzC.mjs → spans-DwDXMvyd.mjs} +1 -1
  267. package/dist/{spans-XDUFeTzC.mjs.map → spans-DwDXMvyd.mjs.map} +1 -1
  268. package/dist/sql-Bu63iAfT.mjs +2 -0
  269. package/dist/sql-Bu63iAfT.mjs.map +1 -0
  270. package/dist/{sql-BVZ8QefY.d.mts → sql-C4_sFNDm.d.mts} +18 -5
  271. package/dist/sql-statement-tokens-Z5Ta4iDB.mjs +3 -0
  272. package/dist/{sql-statement-tokens-DbeMwHra.mjs.map → sql-statement-tokens-Z5Ta4iDB.mjs.map} +1 -1
  273. package/dist/sql-tegqTqGq.mjs +2 -0
  274. package/dist/sql-tegqTqGq.mjs.map +1 -0
  275. package/dist/sql.d.mts +1 -1
  276. package/dist/sql.mjs +1 -1
  277. package/dist/sqlite-adapter-Cb-SJw2f.mjs +2 -0
  278. package/dist/sqlite-adapter-Cb-SJw2f.mjs.map +1 -0
  279. package/dist/sqlite-statement-classifier-JBHiQO6Q.mjs +2 -0
  280. package/dist/{sqlite-statement-classifier-BAHl-WXS.mjs.map → sqlite-statement-classifier-JBHiQO6Q.mjs.map} +1 -1
  281. package/dist/sqlite-utils-Bfmtkt1b.mjs +2 -0
  282. package/dist/sqlite-utils-Bfmtkt1b.mjs.map +1 -0
  283. package/dist/sqlite3.d.mts +2 -46
  284. package/dist/sqlite3.mjs +1 -1
  285. package/dist/sqlite3.mjs.map +1 -1
  286. package/dist/standard-sql-Bl2OHGfi.mjs +6 -0
  287. package/dist/standard-sql-Bl2OHGfi.mjs.map +1 -0
  288. package/dist/suppressed-failure-CFUDJrUw.mjs +2 -0
  289. package/dist/{suppressed-failure-CQkQsMVS.mjs.map → suppressed-failure-CFUDJrUw.mjs.map} +1 -1
  290. package/dist/surrealdb.d.mts +2 -2
  291. package/dist/surrealdb.mjs +1 -1
  292. package/dist/surrealdb.mjs.map +1 -1
  293. package/dist/surrealql-DY74AUeD.mjs +2 -0
  294. package/dist/surrealql-DY74AUeD.mjs.map +1 -0
  295. package/dist/time-step-DJaIhpAz.mjs +2 -0
  296. package/dist/time-step-DJaIhpAz.mjs.map +1 -0
  297. package/dist/transaction-Bv5nyp-U.mjs +2 -0
  298. package/dist/{transaction-BNomMtme.mjs.map → transaction-Bv5nyp-U.mjs.map} +1 -1
  299. package/dist/transaction-operation-CaWzo7gE.mjs +2 -0
  300. package/dist/{transaction-operation-CVVJxQ19.mjs.map → transaction-operation-CaWzo7gE.mjs.map} +1 -1
  301. package/dist/types-Dy33vBdd.mjs +2 -0
  302. package/dist/{types-DtDnXhwa.mjs.map → types-Dy33vBdd.mjs.map} +1 -1
  303. package/dist/unit-DUPX5Sdd.mjs +2 -0
  304. package/dist/{unit-BhHbZyuJ.mjs.map → unit-DUPX5Sdd.mjs.map} +1 -1
  305. package/dist/unit-words-BXpLpyr2.mjs +2 -0
  306. package/dist/{unit-words-CT0yeqfZ.mjs.map → unit-words-BXpLpyr2.mjs.map} +1 -1
  307. package/dist/utils-BHkJsduV.mjs +26 -0
  308. package/dist/{utils-CpAojrCj.mjs.map → utils-BHkJsduV.mjs.map} +1 -1
  309. package/dist/v1-parse-shared-cJ-uD14P.mjs +2 -0
  310. package/dist/v1-parse-shared-cJ-uD14P.mjs.map +1 -0
  311. package/dist/validation-ATmgN5RE.mjs +2 -0
  312. package/dist/validation-ATmgN5RE.mjs.map +1 -0
  313. package/dist/validation-BHjx13zG.mjs +2 -0
  314. package/dist/validation-BHjx13zG.mjs.map +1 -0
  315. package/dist/validation.d.mts +1 -1
  316. package/dist/validation.mjs +1 -1
  317. package/dist/validator-DMzH5Tz0.mjs +2 -0
  318. package/dist/validator-DMzH5Tz0.mjs.map +1 -0
  319. package/dist/value-guards-CBVIJXlI.mjs +2 -0
  320. package/dist/{value-guards-CBuxSC66.mjs.map → value-guards-CBVIJXlI.mjs.map} +1 -1
  321. package/dist/values-Ch2cTlss.mjs +2 -0
  322. package/dist/{values-B4aj1i1f.mjs.map → values-Ch2cTlss.mjs.map} +1 -1
  323. package/dist/version-0BDwfy7C.mjs +2 -0
  324. package/dist/{version-CXGIA82S.mjs.map → version-0BDwfy7C.mjs.map} +1 -1
  325. package/dist/view-CHgjF2BO.mjs +2 -0
  326. package/dist/view-CHgjF2BO.mjs.map +1 -0
  327. package/dist/write-sinks-Bei5vFHP.mjs +2 -0
  328. package/dist/{write-sinks-3IKCDF-S.mjs.map → write-sinks-Bei5vFHP.mjs.map} +1 -1
  329. package/package.json +50 -37
  330. package/dist/adapter-internals-DOqI8IlQ.mjs +0 -2
  331. package/dist/adapter-internals-DOqI8IlQ.mjs.map +0 -1
  332. package/dist/adapter-namespace-DaRiTIIf.mjs +0 -2
  333. package/dist/adapter-result-parser-3WP82Cm-.mjs +0 -2
  334. package/dist/adapter-result-parser-3WP82Cm-.mjs.map +0 -1
  335. package/dist/args-764KdWMr.mjs +0 -2
  336. package/dist/array-literal-DHinAnVs.mjs +0 -2
  337. package/dist/base-z-cH5ZBI.mjs +0 -2
  338. package/dist/base-z-cH5ZBI.mjs.map +0 -1
  339. package/dist/batch-refs-C-gx7A4-.mjs +0 -2
  340. package/dist/bind-parameter-capacity-BMD-bxMO.mjs +0 -2
  341. package/dist/call-Cz8XUmrl.mjs +0 -2
  342. package/dist/canonical-json-Bl-fKFF_.mjs +0 -2
  343. package/dist/canonical-json-Bl-fKFF_.mjs.map +0 -1
  344. package/dist/chunk-BuuaeEvq.mjs +0 -1
  345. package/dist/client-DRpX3-vw.mjs +0 -2
  346. package/dist/client-DRpX3-vw.mjs.map +0 -1
  347. package/dist/client-y7TV0PRZ.mjs +0 -9
  348. package/dist/client-y7TV0PRZ.mjs.map +0 -1
  349. package/dist/confine-DqFBTUw6.mjs +0 -2
  350. package/dist/coordination-6qZHx_kl.mjs +0 -2
  351. package/dist/coordination-6qZHx_kl.mjs.map +0 -1
  352. package/dist/current-DBTlPsQg.mjs +0 -2
  353. package/dist/current-DBTlPsQg.mjs.map +0 -1
  354. package/dist/datetime-physical-codec-Dj-APo9f.mjs +0 -2
  355. package/dist/datetime-physical-codec-Dj-APo9f.mjs.map +0 -1
  356. package/dist/defaults-DwOHWI_M.mjs +0 -2
  357. package/dist/driver-BGVcgnIX.mjs +0 -2
  358. package/dist/driver-BGVcgnIX.mjs.map +0 -1
  359. package/dist/driver-BIXhOH2_.mjs +0 -2
  360. package/dist/driver-BIXhOH2_.mjs.map +0 -1
  361. package/dist/driver-diagnostics-DW9NdckJ.mjs +0 -2
  362. package/dist/error-mapping-B1-IWkCQ.mjs +0 -2
  363. package/dist/error-mapping-B1-IWkCQ.mjs.map +0 -1
  364. package/dist/every-tOgQmaIE.mjs +0 -2
  365. package/dist/execution-context-BXpcbyPe.mjs +0 -2
  366. package/dist/execution-context-BXpcbyPe.mjs.map +0 -1
  367. package/dist/extension-CGepsF-p.mjs +0 -2
  368. package/dist/fs-estate-D1Nsg9G1.mjs +0 -2
  369. package/dist/geo-area-codec-mHrM3b9A.mjs +0 -2
  370. package/dist/geo-area-codec-mHrM3b9A.mjs.map +0 -1
  371. package/dist/hydration-A3zffFWP.mjs +0 -2
  372. package/dist/hydration-A3zffFWP.mjs.map +0 -1
  373. package/dist/identifier-conversion-DHYPTgzr.mjs +0 -2
  374. package/dist/identifier-conversion-DHYPTgzr.mjs.map +0 -1
  375. package/dist/identifiers-s00pGES8.mjs +0 -2
  376. package/dist/identifiers-s00pGES8.mjs.map +0 -1
  377. package/dist/identity-CtW15WlB.mjs +0 -2
  378. package/dist/identity-CtW15WlB.mjs.map +0 -1
  379. package/dist/introspect-Bm6xnXcG.mjs +0 -2
  380. package/dist/introspect-Bm6xnXcG.mjs.map +0 -1
  381. package/dist/json-DgMc8-GU.mjs +0 -2
  382. package/dist/json-DgMc8-GU.mjs.map +0 -1
  383. package/dist/json-number-AI-SdUUn.mjs +0 -2
  384. package/dist/json-parameter-oQ8nGaKr.mjs +0 -2
  385. package/dist/judge-words-CzUyXtJ6.mjs +0 -2
  386. package/dist/judge-words-CzUyXtJ6.mjs.map +0 -1
  387. package/dist/key-hxFFCKed.mjs +0 -2
  388. package/dist/key-hxFFCKed.mjs.map +0 -1
  389. package/dist/keys-BQxM4c_a.mjs +0 -2
  390. package/dist/libsql-DuGR904j.mjs +0 -3
  391. package/dist/libsql-DuGR904j.mjs.map +0 -1
  392. package/dist/light-BkJe3-yW.mjs +0 -2
  393. package/dist/memory-G4cSuc6A.mjs +0 -2
  394. package/dist/methods-part-ZY0f2AV_.mjs +0 -2
  395. package/dist/methods-part-ZY0f2AV_.mjs.map +0 -1
  396. package/dist/migrations-BMiRjR-N.mjs +0 -2
  397. package/dist/mysql-BNXWfTOo.mjs +0 -100
  398. package/dist/mysql-BNXWfTOo.mjs.map +0 -1
  399. package/dist/mysql-adapter-C69j1sKh.mjs +0 -2
  400. package/dist/mysql-adapter-C69j1sKh.mjs.map +0 -1
  401. package/dist/native-types-DgjMUikz.mjs +0 -2
  402. package/dist/native-types-DgjMUikz.mjs.map +0 -1
  403. package/dist/normalized-result-B8pifWS0.mjs +0 -2
  404. package/dist/normalized-result-B8pifWS0.mjs.map +0 -1
  405. package/dist/object-store-DS0F0yZX.mjs +0 -2
  406. package/dist/object-store-DS0F0yZX.mjs.map +0 -1
  407. package/dist/on-ylYaKuRu.mjs +0 -2
  408. package/dist/pending-operation-C_eOFOBE.mjs +0 -2
  409. package/dist/pending-operation-C_eOFOBE.mjs.map +0 -1
  410. package/dist/physical-CeE2nYmI.mjs +0 -2
  411. package/dist/physical-CeE2nYmI.mjs.map +0 -1
  412. package/dist/pinned-session-DCoAZDOz.mjs +0 -2
  413. package/dist/pinned-session-DCoAZDOz.mjs.map +0 -1
  414. package/dist/postgres-CDdh5dSP.mjs +0 -437
  415. package/dist/postgres-CDdh5dSP.mjs.map +0 -1
  416. package/dist/postgres-adapter-Dlr3ZWd7.mjs +0 -2
  417. package/dist/postgres-adapter-Dlr3ZWd7.mjs.map +0 -1
  418. package/dist/postgres-adapter-axapXX8d.mjs +0 -2
  419. package/dist/postgres-result-DF6DmW3r.mjs +0 -2
  420. package/dist/postgres-result-DF6DmW3r.mjs.map +0 -1
  421. package/dist/provider-limits-Ccsb8PTb.mjs +0 -2
  422. package/dist/provider-limits-Ccsb8PTb.mjs.map +0 -1
  423. package/dist/provider-parameter-snapshot-BikrgKqI.mjs +0 -2
  424. package/dist/provider-parameter-snapshot-BikrgKqI.mjs.map +0 -1
  425. package/dist/query-BZVHfA0s.mjs +0 -2
  426. package/dist/query-BZVHfA0s.mjs.map +0 -1
  427. package/dist/query-inspection-BoG-yAln.mjs +0 -2
  428. package/dist/query-inspection-BoG-yAln.mjs.map +0 -1
  429. package/dist/raw-Dyq6Y6UX.mjs +0 -2
  430. package/dist/raw-Dyq6Y6UX.mjs.map +0 -1
  431. package/dist/relation-bound-ku_cMdye.mjs +0 -2
  432. package/dist/result-parsing-B0Y4KGDT.mjs +0 -2
  433. package/dist/routed-operations-wytpbYKv.mjs +0 -2
  434. package/dist/rule-words-ZIGm7cDm.mjs +0 -2
  435. package/dist/scalar-BHCh7aUz.mjs +0 -4
  436. package/dist/scalar-BHCh7aUz.mjs.map +0 -1
  437. package/dist/schema-BYA-_bpk.mjs +0 -2
  438. package/dist/schema-BYA-_bpk.mjs.map +0 -1
  439. package/dist/schema-CFIaebgi.mjs +0 -2
  440. package/dist/schema-CFIaebgi.mjs.map +0 -1
  441. package/dist/schema-introspection-D0f8cti4.mjs +0 -6
  442. package/dist/schema-introspection-D0f8cti4.mjs.map +0 -1
  443. package/dist/select-assembly-DVI7d3tf.mjs +0 -2
  444. package/dist/select-assembly-DVI7d3tf.mjs.map +0 -1
  445. package/dist/serializer-rBq3v1xr.mjs +0 -51
  446. package/dist/serializer-rBq3v1xr.mjs.map +0 -1
  447. package/dist/settle-1cy5x_52.mjs +0 -2
  448. package/dist/settled-BjyuA76m.mjs +0 -2
  449. package/dist/snowflake-UOCC820W.mjs +0 -2
  450. package/dist/sql-3o4DOKm9.mjs +0 -2
  451. package/dist/sql-3o4DOKm9.mjs.map +0 -1
  452. package/dist/sql-Dl6nykFV.mjs +0 -2
  453. package/dist/sql-Dl6nykFV.mjs.map +0 -1
  454. package/dist/sql-statement-tokens-DbeMwHra.mjs +0 -3
  455. package/dist/sqlite-adapter-Ad0d-m2t.mjs +0 -2
  456. package/dist/sqlite-adapter-Ad0d-m2t.mjs.map +0 -1
  457. package/dist/sqlite-statement-classifier-BAHl-WXS.mjs +0 -2
  458. package/dist/sqlite-utils-BRvbmlQ1.mjs +0 -2
  459. package/dist/sqlite-utils-BRvbmlQ1.mjs.map +0 -1
  460. package/dist/standard-sql-qLcQyCtK.mjs +0 -6
  461. package/dist/standard-sql-qLcQyCtK.mjs.map +0 -1
  462. package/dist/suppressed-failure-CQkQsMVS.mjs +0 -2
  463. package/dist/surrealql-C1dp1sWw.mjs +0 -2
  464. package/dist/surrealql-C1dp1sWw.mjs.map +0 -1
  465. package/dist/to-many-BybuKQM1.mjs +0 -2
  466. package/dist/to-many-BybuKQM1.mjs.map +0 -1
  467. package/dist/transaction-BNomMtme.mjs +0 -2
  468. package/dist/transaction-operation-CVVJxQ19.mjs +0 -2
  469. package/dist/types-DtDnXhwa.mjs +0 -2
  470. package/dist/unit-BhHbZyuJ.mjs +0 -2
  471. package/dist/unit-words-CT0yeqfZ.mjs +0 -2
  472. package/dist/utils-CpAojrCj.mjs +0 -26
  473. package/dist/validation--qS7OPmg.mjs +0 -2
  474. package/dist/validation--qS7OPmg.mjs.map +0 -1
  475. package/dist/validation-CYaJ8ndO.mjs +0 -2
  476. package/dist/validation-CYaJ8ndO.mjs.map +0 -1
  477. package/dist/validator-CZLW7aR3.mjs +0 -2
  478. package/dist/validator-CZLW7aR3.mjs.map +0 -1
  479. package/dist/value-guards-CBuxSC66.mjs +0 -2
  480. package/dist/values-B4aj1i1f.mjs +0 -2
  481. package/dist/version-CXGIA82S.mjs +0 -2
  482. package/dist/write-sinks-3IKCDF-S.mjs +0 -2
  483. /package/dist/{contract-CrIB-3ZJ.d.mts → contract-CxJn0_cV.d.mts} +0 -0
@@ -1,2 +0,0 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{p as t}from"./validation--qS7OPmg.mjs";function observePromiseRejection(e,t){return new n(e,t)}function afterFulfilled(e,t){return e instanceof n?e.fulfilled(t):e.then(t)}var n=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)}fulfilled(e){let t=this.promise.then(e);return t.catch(()=>void 0),new RejectionObservedPromise(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)}};function createNormalizedResultMeta(e){return{driver:e.provider,operation:e.operation,...e.model?{model:e.model}:{},...e.correlationId?{correlationId:e.correlationId}:{}}}const r=/^(?:0|[1-9]\d*)$/;function normalizeProviderRowCount(e,n,i){let a=e===null?i?.nullValue:e;if(i?.allowDecimalString===!0&&typeof a==`string`&&r.test(a)&&(a=Number(a)),typeof a!=`number`||!Number.isSafeInteger(a)||a<0)throw new t(`Driver "${n.provider}" returned a malformed row count for operation "${n.operation}".`,{meta:createNormalizedResultMeta(n)});return a}function normalizeProviderInsertId(e,t,n){if(typeof e==`string`){if(!r.test(e))throw malformedInsertId(t);return e===`0`?void 0:BigInt(e)}if(n?.allowNumber===!0&&typeof e==`number`){if(!Number.isSafeInteger(e)||e<0)throw malformedInsertId(t);return e===0?void 0:e}throw malformedInsertId(t)}function malformedInsertId(e){return new t(`Driver "${e.provider}" returned a malformed insert id for operation "${e.operation}".`,{meta:createNormalizedResultMeta(e)})}function malformedNormalizedResult(e,n){let r=n===void 0?``:` at batch result index ${n}`;return new t(`Driver "${e.provider}" returned a malformed normalized result for operation "${e.operation}"${r}; expected { rows: object[], rowCount: safe non-negative integer }.`,{meta:{...createNormalizedResultMeta(e),...n===void 0?{}:{resultIndex:n}}})}function isNormalizedResultRow(e){return typeof e==`object`&&!!e&&Object.prototype.toString.call(e)===`[object Object]`}function hasNormalizedRows(e){if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t+=1)if(!(Object.hasOwn(e,t)&&isNormalizedResultRow(e[t])))return!1;return!0}function assertNormalizedQueryResult(e,t,n){let r=e?.insertId===void 0||typeof e.insertId==`bigint`&&e.insertId>=0n||typeof e.insertId==`number`&&Number.isFinite(e.insertId)&&Number.isSafeInteger(e.insertId)&&e.insertId>=0;if(!(isNormalizedResultRow(e)&&hasNormalizedRows(e.rows))||typeof e.rowCount!=`number`||!Number.isFinite(e.rowCount)||!Number.isSafeInteger(e.rowCount)||e.rowCount<0||!r)throw malformedNormalizedResult(t,n)}function assertNormalizedBatchResults(e,n,r){if(!Array.isArray(e)||e.length!==n){let i=Array.isArray(e)?e.length:0;throw new t(`Driver "${r.provider}" returned ${i} results for operation "${r.operation}"; expected ${n}, one per statement.`,{meta:{...createNormalizedResultMeta(r),expectedStatementCount:n,actualResultCount:i}})}for(let t=0;t<e.length;t+=1)assertNormalizedQueryResult(e[t],r,t)}export{normalizeProviderInsertId as a,observePromiseRejection as c,isNormalizedResultRow as i,assertNormalizedQueryResult as n,normalizeProviderRowCount as o,createNormalizedResultMeta as r,afterFulfilled as s,assertNormalizedBatchResults as t};
2
- //# sourceMappingURL=normalized-result-B8pifWS0.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"normalized-result-B8pifWS0.mjs","names":[],"sources":["../src/drivers/rejection-observed-promise.ts","../src/drivers/normalized-result.ts"],"sourcesContent":["/**\n * Wrap a native promise so transaction scope tracking can distinguish a\n * handled nested rejection from fire-and-forget work. Await and catch both\n * supply a rejection handler through this Promise-compatible surface.\n */\nexport function observePromiseRejection<T>(\n promise: Promise<T>,\n onRejectionObserved: () => void\n): Promise<T> {\n return new RejectionObservedPromise(promise, onRejectionObserved);\n}\n\n/**\n * `promise.then(onfulfilled)` that is no handler of its rejection: what\n * runs after a nested transaction committed, leaving the caller's own\n * handlers to say whether its failure was observed. The promise it makes\n * rejects with that failure, which the outer transaction reports unless the\n * caller observes it, so it leaves no unhandled rejection of its own.\n */\nexport function afterFulfilled<T, R>(\n promise: Promise<T>,\n onfulfilled: (value: T) => R | PromiseLike<R>\n): Promise<R> {\n return promise instanceof RejectionObservedPromise\n ? promise.fulfilled(onfulfilled)\n : promise.then(onfulfilled);\n}\n\nclass RejectionObservedPromise<T> implements Promise<T> {\n readonly [Symbol.toStringTag] = \"Promise\";\n private readonly onRejectionObserved: () => void;\n private readonly promise: Promise<T>;\n\n constructor(promise: Promise<T>, onRejectionObserved: () => void) {\n this.promise = promise;\n this.onRejectionObserved = onRejectionObserved;\n }\n\n then<TResult1 = T, TResult2 = never>(\n onfulfilled?: ((value: T) => PromiseLike<TResult1> | TResult1) | null,\n onrejected?: ((reason: unknown) => PromiseLike<TResult2> | TResult2) | null\n ): Promise<TResult1 | TResult2> {\n if (onrejected) this.onRejectionObserved();\n return new RejectionObservedPromise(\n this.promise.then(onfulfilled, onrejected),\n this.onRejectionObserved\n );\n }\n\n fulfilled<R>(onfulfilled: (value: T) => R | PromiseLike<R>): Promise<R> {\n const next = this.promise.then(onfulfilled);\n next.catch(() => undefined);\n return new RejectionObservedPromise(next, this.onRejectionObserved);\n }\n\n catch<TResult = never>(\n onrejected?: ((reason: unknown) => PromiseLike<TResult> | TResult) | null\n ): Promise<T | TResult> {\n if (onrejected) this.onRejectionObserved();\n return new RejectionObservedPromise(\n this.promise.catch(onrejected),\n this.onRejectionObserved\n );\n }\n\n finally(onfinally?: (() => void) | null): Promise<T> {\n return new RejectionObservedPromise(\n this.promise.finally(onfinally),\n this.onRejectionObserved\n );\n }\n}\n","import { QueryError } from \"@errors\";\nimport type { QueryResult } from \"./types\";\n\nexport interface NormalizedResultContext {\n provider: string;\n operation: string;\n model?: string;\n correlationId?: string;\n}\n\nexport function createNormalizedResultMeta(\n context: NormalizedResultContext\n): Record<string, unknown> {\n return {\n driver: context.provider,\n operation: context.operation,\n ...(context.model ? { model: context.model } : {}),\n ...(context.correlationId ? { correlationId: context.correlationId } : {}),\n };\n}\n\nconst NON_NEGATIVE_DECIMAL_REGEX = /^(?:0|[1-9]\\d*)$/;\n\nexport function normalizeProviderRowCount(\n value: unknown,\n context: NormalizedResultContext,\n options?: { allowDecimalString?: boolean; nullValue?: number }\n): number {\n let normalized = value === null ? options?.nullValue : value;\n if (\n options?.allowDecimalString === true &&\n typeof normalized === \"string\" &&\n NON_NEGATIVE_DECIMAL_REGEX.test(normalized)\n ) {\n normalized = Number(normalized);\n }\n if (\n typeof normalized !== \"number\" ||\n !Number.isSafeInteger(normalized) ||\n normalized < 0\n ) {\n throw new QueryError(\n `Driver \"${context.provider}\" returned a malformed row count for operation \"${context.operation}\".`,\n {\n meta: createNormalizedResultMeta(context),\n }\n );\n }\n return normalized;\n}\n\nexport function normalizeProviderInsertId(\n value: unknown,\n context: NormalizedResultContext,\n options?: { allowNumber?: boolean }\n): number | bigint | undefined {\n if (typeof value === \"string\") {\n if (!NON_NEGATIVE_DECIMAL_REGEX.test(value)) {\n throw malformedInsertId(context);\n }\n return value === \"0\" ? undefined : BigInt(value);\n }\n if (options?.allowNumber === true && typeof value === \"number\") {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw malformedInsertId(context);\n }\n return value === 0 ? undefined : value;\n }\n throw malformedInsertId(context);\n}\n\nfunction malformedInsertId(context: NormalizedResultContext): QueryError {\n return new QueryError(\n `Driver \"${context.provider}\" returned a malformed insert id for operation \"${context.operation}\".`,\n {\n meta: createNormalizedResultMeta(context),\n }\n );\n}\n\nfunction malformedNormalizedResult(\n context: NormalizedResultContext,\n resultIndex?: number\n): QueryError {\n const position =\n resultIndex === undefined ? \"\" : ` at batch result index ${resultIndex}`;\n return new QueryError(\n `Driver \"${context.provider}\" returned a malformed normalized result for operation \"${context.operation}\"${position}; expected { rows: object[], rowCount: safe non-negative integer }.`,\n {\n meta: {\n ...createNormalizedResultMeta(context),\n ...(resultIndex === undefined ? {} : { resultIndex }),\n },\n }\n );\n}\n\nexport function isNormalizedResultRow(\n value: unknown\n): value is Record<string, unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n Object.prototype.toString.call(value) === \"[object Object]\"\n );\n}\n\nfunction hasNormalizedRows(value: unknown): value is Record<string, unknown>[] {\n if (!Array.isArray(value)) return false;\n for (let index = 0; index < value.length; index += 1) {\n if (!(Object.hasOwn(value, index) && isNormalizedResultRow(value[index]))) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Assert the single cross-driver success contract. Empty row arrays and a\n * rowCount of zero are valid; missing fields, non-record rows, and invented\n * counts are not.\n */\nexport function assertNormalizedQueryResult(\n result: QueryResult<unknown> | undefined,\n context: NormalizedResultContext,\n resultIndex?: number\n): void {\n const hasValidInsertId =\n result?.insertId === undefined ||\n (typeof result.insertId === \"bigint\" && result.insertId >= 0n) ||\n (typeof result.insertId === \"number\" &&\n Number.isFinite(result.insertId) &&\n Number.isSafeInteger(result.insertId) &&\n result.insertId >= 0);\n if (\n !(isNormalizedResultRow(result) && hasNormalizedRows(result.rows)) ||\n typeof result.rowCount !== \"number\" ||\n !Number.isFinite(result.rowCount) ||\n !Number.isSafeInteger(result.rowCount) ||\n result.rowCount < 0 ||\n !hasValidInsertId\n ) {\n throw malformedNormalizedResult(context, resultIndex);\n }\n}\n\n/**\n * Native and planned batches must return one normalized result for each\n * submitted statement, in the same order.\n */\nexport function assertNormalizedBatchResults(\n results: readonly QueryResult<unknown>[],\n expectedStatementCount: number,\n context: NormalizedResultContext\n): void {\n if (!Array.isArray(results) || results.length !== expectedStatementCount) {\n const actualResultCount = Array.isArray(results) ? results.length : 0;\n throw new QueryError(\n `Driver \"${context.provider}\" returned ${actualResultCount} results for operation \"${context.operation}\"; expected ${expectedStatementCount}, one per statement.`,\n {\n meta: {\n ...createNormalizedResultMeta(context),\n expectedStatementCount,\n actualResultCount,\n },\n }\n );\n }\n\n for (let resultIndex = 0; resultIndex < results.length; resultIndex += 1) {\n assertNormalizedQueryResult(results[resultIndex], context, resultIndex);\n }\n}\n"],"mappings":"uFAKA,SAAgB,wBACd,EACA,EACY,CACZ,OAAO,IAAI,EAAyB,EAAS,EAAoB,CAUnE,SAAgB,eACd,EACA,EACY,CACZ,OAAO,aAAmB,EACtB,EAAQ,UAAU,EAAY,CAC9B,EAAQ,KAAK,EAAY,CAG/B,IAAM,EAAN,MAAM,wBAAkD,CACtD,CAAU,OAAO,aAAe,UAChC,oBACA,QAEA,YAAY,EAAqB,EAAiC,CAChE,KAAK,QAAU,EACf,KAAK,oBAAsB,EAG7B,KACE,EACA,EAC8B,CAE9B,OADI,GAAY,KAAK,qBAAqB,CACnC,IAAI,yBACT,KAAK,QAAQ,KAAK,EAAa,EAAW,CAC1C,KAAK,oBACN,CAGH,UAAa,EAA2D,CACtE,IAAM,EAAO,KAAK,QAAQ,KAAK,EAAY,CAE3C,OADA,EAAK,UAAY,IAAA,GAAU,CACpB,IAAI,yBAAyB,EAAM,KAAK,oBAAoB,CAGrE,MACE,EACsB,CAEtB,OADI,GAAY,KAAK,qBAAqB,CACnC,IAAI,yBACT,KAAK,QAAQ,MAAM,EAAW,CAC9B,KAAK,oBACN,CAGH,QAAQ,EAA6C,CACnD,OAAO,IAAI,yBACT,KAAK,QAAQ,QAAQ,EAAU,CAC/B,KAAK,oBACN,GC3DL,SAAgB,2BACd,EACyB,CACzB,MAAO,CACL,OAAQ,EAAQ,SAChB,UAAW,EAAQ,UACnB,GAAI,EAAQ,MAAQ,CAAE,MAAO,EAAQ,MAAO,CAAG,EAAE,CACjD,GAAI,EAAQ,cAAgB,CAAE,cAAe,EAAQ,cAAe,CAAG,EAAE,CAC1E,CAGH,MAAM,EAA6B,mBAEnC,S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{a as i}from"./identity-CtW15WlB.mjs";function refuseWorkersKvWritable(){throw new n(`Workers KV cannot be a V1 estate writer: listing is eventually consistent and puts are not conditional`,t.MIGRATION_UNSUPPORTED_PROVIDER)}var ObjectStoreEstateStorage=class{store;constructor(e){this.store=e}async readEstate(){return this.store.get(`estate.json`)}async listStates(){return this.listHex(`states/`,`.json`)}async listSnapshots(){return this.listHex(`snapshots/`,`.json`)}async listSql(){return this.listHex(`sql/`,`.sql`)}async readState(e){return this.store.get(`states/${e}.json`)}async readSnapshot(e){return this.store.get(`snapshots/${e}.json`)}async readSql(e){return this.store.get(`sql/${e}.sql`)}async publishEstate(e){return this.publish(`estate.json`,e)}async publishSnapshot(e,t){return this.publish(`snapshots/${e}.json`,t)}async publishSql(e,t){return this.publish(`sql/${e}.sql`,t)}async publishState(e,r){if(!i(e))throw new n(`State id is not a SHA-256 digest`,t.MIGRATION_INVALID_ESTATE);return this.publish(`states/${e}.json`,r)}async publish(e,i){if(await this.store.putIfAbsent(e,i)===`created`)return{outcome:`created`};let a=await this.store.get(e);if(!(a&&r(a,i)))throw new n(`Object-store key ${e} already holds different bytes`,t.MIGRATION_CORRUPTION);return{outcome:`identical`}}async listHex(e,t){let n=await this.store.list(e),r=[];for(let a of n){let n=a.slice(e.length);if(!n.endsWith(t))continue;let o=n.slice(0,-t.length);i(o)&&r.push(o)}return r.sort()}},MemoryConditionalObjectStore=class{objects=new Map;async putIfAbsent(e,t){return this.objects.has(e)?`exists`:(this.objects.set(e,t.slice()),`created`)}async get(e){let t=this.objects.get(e);return t?t.slice():null}async list(e){return[...this.objects.keys()].filter(t=>t.startsWith(e)).sort()}};export{ObjectStoreEstateStorage as n,refuseWorkersKvWritable as r,MemoryConditionalObjectStore as t};
2
- //# sourceMappingURL=object-store-DS0F0yZX.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"object-store-DS0F0yZX.mjs","names":[],"sources":["../src/migrations/storage/object-store.ts"],"sourcesContent":["/**\n * Strong object-store publication contract.\n * A writable driver that cannot do conditional create is not a V1 estate owner.\n * Workers KV is refused here: it has no compare-and-swap publication.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../../errors\";\nimport { bytesEqual } from \"../canonical-json\";\nimport { isSha256, type Sha256 } from \"../identity\";\nimport type { MigrationStorageWriter, PublishResult } from \"./contract\";\n\nexport function refuseWorkersKvWritable(): never {\n throw new MigrationError(\n \"Workers KV cannot be a V1 estate writer: listing is eventually consistent and puts are not conditional\",\n VibORMErrorCode.MIGRATION_UNSUPPORTED_PROVIDER\n );\n}\n\nexport interface ObjectStoreConditionalPut {\n putIfAbsent(key: string, bytes: Uint8Array): Promise<\"created\" | \"exists\">;\n get(key: string): Promise<Uint8Array | null>;\n list(prefix: string): Promise<readonly string[]>;\n}\n\n/**\n * Estate writer over a strongly consistent object store with if-none-match\n * publication. Manifests become visible only after referenced bytes exist.\n */\nexport class ObjectStoreEstateStorage implements MigrationStorageWriter {\n private readonly store: ObjectStoreConditionalPut;\n\n constructor(store: ObjectStoreConditionalPut) {\n this.store = store;\n }\n\n async readEstate(): Promise<Uint8Array | null> {\n return this.store.get(\"estate.json\");\n }\n\n async listStates(): Promise<readonly Sha256[]> {\n return this.listHex(\"states/\", \".json\");\n }\n\n async listSnapshots(): Promise<readonly Sha256[]> {\n return this.listHex(\"snapshots/\", \".json\");\n }\n\n async listSql(): Promise<readonly Sha256[]> {\n return this.listHex(\"sql/\", \".sql\");\n }\n\n async readState(id: Sha256): Promise<Uint8Array | null> {\n return this.store.get(`states/${id}.json`);\n }\n\n async readSnapshot(hash: Sha256): Promise<Uint8Array | null> {\n return this.store.get(`snapshots/${hash}.json`);\n }\n\n async readSql(hash: Sha256): Promise<Uint8Array | null> {\n return this.store.get(`sql/${hash}.sql`);\n }\n\n async publishEstate(bytes: Uint8Array): Promise<PublishResult> {\n return this.publish(\"estate.json\", bytes);\n }\n\n async publishSnapshot(\n hash: Sha256,\n bytes: Uint8Array\n ): Promise<PublishResult> {\n return this.publish(`snapshots/${hash}.json`, bytes);\n }\n\n async publishSql(hash: Sha256, bytes: Uint8Array): Promise<PublishResult> {\n return this.publish(`sql/${hash}.sql`, bytes);\n }\n\n async publishState(id: Sha256, bytes: Uint8Array): Promise<PublishResult> {\n if (!isSha256(id)) {\n throw new MigrationError(\n \"State id is not a SHA-256 digest\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n return this.publish(`states/${id}.json`, bytes);\n }\n\n private async publish(\n key: string,\n bytes: Uint8Array\n ): Promise<PublishResult> {\n const result = await this.store.putIfAbsent(key, bytes);\n if (result === \"created\") return { outcome: \"created\" };\n const existing = await this.store.get(key);\n if (!(existing && bytesEqual(existing, bytes))) {\n throw new MigrationError(\n `Object-store key ${key} already holds different bytes`,\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n return { outcome: \"identical\" };\n }\n\n private async listHex(prefix: string, suffix: string): Promise<Sha256[]> {\n const keys = await this.store.list(prefix);\n const hashes: Sha256[] = [];\n for (const key of keys) {\n const name = key.slice(prefix.length);\n if (!name.endsWith(suffix)) continue;\n const hex = name.slice(0, -suffix.length);\n if (isSha256(hex)) hashes.push(hex);\n }\n return hashes.sort();\n }\n}\n\n/** In-memory strong object store for the conformance fixture. */\nexport class MemoryConditionalObjectStore implements ObjectStoreConditionalPut {\n private readonly objects = new Map<string, Uint8Array>();\n\n async putIfAbsent(\n key: string,\n bytes: Uint8Array\n ): Promise<\"created\" | \"exists\"> {\n if (this.objects.has(key)) return \"exists\";\n this.objects.set(key, bytes.slice());\n return \"created\";\n }\n\n async get(key: string): Promise<Uint8Array | null> {\n const bytes = this.objects.get(key);\n return bytes ? bytes.slice() : null;\n }\n\n async list(prefix: string): Promise<readonly string[]> {\n return [...this.objects.keys()]\n .filter((key) => key.startsWith(prefix))\n .sort();\n }\n}\n"],"mappings":"6NAWA,SAAgB,yBAAiC,CAC/C,MAAM,IAAI,EACR,yGACA,EAAgB,+BACjB,CAaH,IAAa,yBAAb,KAAwE,CACtE,MAE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AM,KAAK,MAAM,KAAK,EAAO,CACpC,EAAmB,EAAE,CAC3B,IAAK,IAAM,KAAO,EAAM,CACtB,IAAM,EAAO,EAAI,MAAM,EAAO,OAAO,CACrC,GAAI,CAAC,EAAK,SAAS,EAAO,CAAE,SAC5B,IAAM,EAAM,EAAK,MAAM,EAAG,CAAC,EAAO,OAAO,CACrC,EAAS,EAAI,EAAE,EAAO,KAAK,EAAI,CAErC,OAAO,EAAO,MAAM,GAKX,6BAAb,KAA+E,CAC7E,QAA2B,IAAI,IAE/B,MAAM,YACJ,EACA,EAC+B,CAG/B,OAFI,KAAK,QAAQ,IAAI,EAAI,CAAS,UAClC,KAAK,QAAQ,IAAI,EAAK,EAAM,OAAO,CAAC,CAC7B,WAGT,MAAM,IAAI,EAAyC,CACjD,IAAM,EAAQ,KAAK,QAAQ,IAAI,EAAI,CACnC,OAAO,EAAQ,EAAM,OAAO,CAAG,KAGjC,MAAM,KAAK,EAA4C,CACrD,MAAO,CAAC,GAAG,KAAK,QAAQ,MAAM,CAAC,CAC5B,OAAQ,GAAQ,EAAI,WAAW,EAAO,CAAC,CACvC,MAAM"}
@@ -1,2 +0,0 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{c as t,i as n,o as r,s as i,t as a}from"./coordination-6qZHx_kl.mjs";import{t as o}from"./routed-operations-wytpbYKv.mjs";import{t as s}from"./write-sinks-3IKCDF-S.mjs";function watchWrite(e,n,r){if(e.length===0)return;let a=[];for(let[t,n]of e)n.settled&&a.push({extension:t,listener:n.settled});return{extension:e[0][0],tell:t,listener:e.find(([,e])=>e.show)?.[1].show?.(e,a,n,r)??(e=>i(a,e))}}const watchShown=(e,t,n,r)=>{let a=new Set;for(let[t,n]of e)n.show&&a.add(t);let o=t.filter(({extension:e})=>a.has(e)),s=t.filter(({extension:e})=>!a.has(e)),c=!1,l,wants=(t,n)=>e.some(([,e])=>e.wants?.(t,n)===!0);return showRows(n,wants,t=>{for(let[n,r,i,a]of t)for(let[,t]of e)t.wants?.(n,r)===!0&&t.rows?.(n,r,i,a);c=!0;let n=l;n&&r(()=>i(o,n))}),e=>c||e.certainty===`may-have-committed`?i(t,e):(l=e,i(s,e))},showRows=(e,t,n)=>{s.set(e,{wants:t,attempt(){let e=[];return{wants:t,shows(t,n,r){r.length>0&&e.push([t,n,r,!0])},own(n,r,i,a){let o=r[`~`].names.ts;if(!a.some(e=>t(o,e)))return;let s=i.select,{scalars:c}=r[`~`].state,l={...Object.fromEntries(Object.entries(s??{}).filter(([e,t])=>t&&!Object.hasOwn(c,e))),...i.include};return{projection:n.prepareProjection(r,Object.keys(l).length>0?{include:l}:{}),cut(n,r){if(r&&t(o,r)&&n.length>0&&e.unshift([o,r,n.map(e=>Object.fromEntries(Object.entries(e).filter(([e])=>Object.hasOwn(c,e)))),!1]),s)for(let e of n)for(let t of Object.keys(e))s[t]||Object.hasOwn(l,t)||delete e[t];return n}}},done:()=>n(e)}}})},c=Symbol(`viborm.watch`),l={registering:(e,t)=>({[c](n){return(e.watched??=[]).push([t,n]),!0}}),join({next:e}){e.watch={watch:(e,t,n,r)=>watchWrite(e.call?.watched??[],n,r)},n(e,a,r)}};function set(e,t){return{operations:e,watch:t}}const u=o,d=set([`findMany`,`findUnique`,`findFirst`,`findUniqueOrThrow`,`findFirstOrThrow`,`count`,`aggregate`,`groupBy`,`exist`]),f=set([`create`,`update`,`delete`,`upsert`,`createMany`,`updateMany`,`deleteMany`],l),p=set([`delete`,`deleteMany`],l),m=set([`findMany`,`findUnique`,`findFirst`,`findUniqueOrThrow`,`findFirstOrThrow`,`count`,`aggregate`,`groupBy`,`exist`,`update`,`delete`,`upsert`,`updateMany`,`deleteMany`]),h=set([`findMany`,`findUnique`,`findFirst`,`findUniqueOrThrow`,`findFirstOrThrow`,`count`,`aggregate`,`groupBy`,`exist`,`create`,`update`,`delete`,`upsert`,`createMany`,`updateMany`,`deleteMany`]),selectionOf=e=>e,operationsOf=e=>typeof e==`string`?[e]:Array.isArray(e)?e:selectionOf(e)?.operations;function target(e,t){return typeof e==`object`&&!Array.isArray(e)?e:{models:typeof e==`string`?[e]:e,operations:operationsOf(t),watch:selectionOf(t)?.watch}}export{d as a,target as c,watchShown as d,operationsOf as i,f as l,p as n,m as o,h as r,selectionOf as s,u as t,c as u};
2
- //# sourceMappingURL=on-ylYaKuRu.mjs.map
@@ -1,2 +0,0 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{I as t}from"./error-mapping-B1-IWkCQ.mjs";import{f as n,y as r}from"./validation--qS7OPmg.mjs";import{t as i}from"./transaction-BNomMtme.mjs";import{n as a}from"./transaction-operation-CVVJxQ19.mjs";import{r as o,t as s}from"./routed-operations-wytpbYKv.mjs";import{o as c}from"./value-guards-CBuxSC66.mjs";import{i as l,n as u,r as d}from"./execution-context-BXpcbyPe.mjs";import{t as f}from"./adapter-result-parser-3WP82Cm-.mjs";import{n as p}from"./bind-parameter-capacity-BMD-bxMO.mjs";import{m}from"./validator-CZLW7aR3.mjs";import{n as h,t as g}from"./query-inspection-BoG-yAln.mjs";function compileBindBudgetChunks(e,t,n){if(e===0)return[];let r=n(0,e);if(t===void 0||r.values.length<=t||e===1)return[{start:0,end:e,statement:r}];let i=[],a=0;for(;a<e;){let r=a+1,o=Math.min(e,a+1),s;for(;;){let i=n(a,o);if(i.values.length>t||(s={start:a,end:o,statement:i},o===e))break;r=o+1,o=Math.min(e,a+(o-a)*2)}if(s?.end!==e)for(--o;r<=o;){let e=r+Math.floor((o-r)/2),i=n(a,e);i.values.length<=t?(s={start:a,end:e,statement:i},r=e+1):o=e-1}let c=s??{start:a,end:a+1,statement:n(a,a+1)};i.push(c),a=c.end}return i}const _=Symbol(`run alone`),v={string:e=>typeof e==`string`,int:e=>typeof e==`number`&&Number.isSafeInteger(e),bigint:e=>typeof e==`bigint`};let y;const b=new WeakSet;function enableFindUniqueBatching(e){b.add(e)}const x=(()=>{let e=globalThis.process,t=e?.nextTick;return typeof t==`function`?n=>t.call(e,n):queueMicrotask})();function batchFindUnique(e){if(!engineBatches(e.engine)||e.engine.driver.holdsConnectionScope())return;let t;try{t=e.routed.args}catch{return}let n=keyOf(e.model,t.where);if(n===void 0)return;let{where:r,...i}=e.args,a=signatureOf(i);if(a===void 0)return;let o,s=new Promise(e=>{o=e}),c,l=new Promise(e=>{c=e}),u={values:n.values,signature:signatureOf(n.values),orThrow:e.requested!==`findUnique`,decide:o};return(enqueue(e,`${n.selector}\u0000${a}`,n,u,c)?l.then(e=>(runBatch(e),s)):s).then(t=>t===_?e.run():t.value)}function engineBatches(e){let{driver:t}=e;return b.has(e.route)&&t===e.route.driver&&e.extensionChain?.rewrites===void 0&&t.result?.parseResult===void 0&&t.adapter.result.parseResult===f}function keyOf(e,t){if(!c(t))return;let n=Object.keys(t);if(n.length!==1)return;let r=n[0],i=m(e,r);if(i===void 0)return;let a=t[r],o;if(i.name===void 0)o=[a];else{if(!c(a)||Object.keys(a).length!==i.fields.length)return;o=i.fields.map(e=>a[e])}let{scalars:s,omit:l}=e[`~`].state,u=!1;for(let[e,t]of i.fields.entries()){let n=s[t]?.[`~`].state;if(!(n&&!n.array&&v[n.type])?.(o[e])||l?.[t]===!0)return;n.type===`string`&&(u=!0)}return{selector:r,fields:i.fields,values:o,textKey:u}}function enqueue(e,t,n,r,i){y===void 0&&(y=new Map,x(flush));let a=y.get(e.engine);a===void 0&&y.set(e.engine,a=new Map);let o=`${e.model[`~`].names.ts}\u0000${t}`,s=a.get(o);s===void 0&&a.set(o,s=[]);let c=s.find(t=>sameControls(t.leader.values,e.values)),l=!1;if(c===void 0){let t={leader:e,start:()=>i(t),fields:n.fields,textKey:n.textKey,members:[]};c=t,s.push(c),l=!0}return c.members.push(r),l}function sameControls(e,t){if(e===t)return!0;if(e===void 0||t===void 0)return!1;let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>Object.hasOwn(t,n)&&e[n]===t[n])}function flush(){let e=y;y=void 0;for(let t of e.values())for(let e of t.values())for(let t of e)t.start()}function runBatch(e){let{members:n}=e,runAlone=e=>{for(let t of e)t.decide(_)};if(n.length===1){runAlone(n);return}try{let r=new Map;for(let e of n){let t=r.get(e.signature);t?t.push(e):r.set(e.signature,[e])}let i=planBatch(e,[...r.values()]),{engine:a}=e.leader,o=t(e.leader.context);for(let t of i.chunks){let n=t.signatures.flatMap(e=>r.get(e));t.read.run({committedWriteSegment:void 0,context:o,driverOverride:void 0,engineDriver:a.driver,isWrite:!1,writeMayBeVisible:void 0}).then(a=>{try{dispatch(e,t,r,i.injected,a)}catch{runAlone(n)}},()=>runAlone(n))}}catch{runAlone(n)}}function planBatch(e,t){let{leader:n,fields:r}=e,i=projectionWithKey(n,r),a=n.rows(),o=new Map,read=(e,s)=>{let c=`${e}:${s}`,l=o.get(c);if(l===void 0){let u=t.slice(e,s).map(e=>e[0].values);l=n.engine.route.prepare(n.model[`~`].names.ts,`findMany`,{...i.args,where:mergedWhere(r,u)},a),o.set(c,l)}return l},s=t.map(e=>e[0].signature),c=p(n.engine.driver.maxBindParametersPerStatement);return{chunks:(c===void 0?[{start:0,end:t.length}]:compileBindBudgetChunks(t.length,c,(e,t)=>read(e,t).read.statement)).map(({start:e,end:t})=>({signatures:s.slice(e,t),read:read(e,t)})),injected:i.injected}}function mergedWhere(e,t){return e.length===1?{[e[0]]:{in:t.map(e=>e[0])}}:{OR:t.map(t=>Object.fromEntries(e.map((e,n)=>[e,t[n]])))}}function projectionWithKey(e,t){let{where:n,...r}=e.args,i=e.routed.args.select,a=[];if(!c(i))return{args:r,injected:a};for(let e of t)i[e]!==!0&&(c(r.select)&&(r.select={...r.select,[e]:!0}),c(r.omit)&&(r.omit={...r.omit,[e]:!1}),a.push(e));return{args:r,injected:a}}function dispatch(e,t,n,r,i){let a=new Map;for(let t of i){let n=signatureOf(e.fields.map(e=>t[e]));for(let e of r)delete t[e];a.has(n)||a.set(n,t)}for(let r of t.signatures){let t=a.get(r);for(let[i,a]of n.get(r).entries())t===void 0?a.orThrow||e.textKey?a.decide(_):a.decide({value:null}):a.decide({value:i===0?t:copyResult(t)})}}function signatureOf(e){switch(typeof e){case`undefined`:return`u`;case`boolean`:case`number`:return String(e);case`string`:return JSON.stringify(e);case`bigint`:return`${e}n`;case`object`:break;default:return}if(e===null)return`null`;if(Array.isArray(e)){let t=[];for(let n of e){let e=signatureOf(n);if(e===void 0)return;t.push(e)}return`[${t.join(`,`)}]`}if(e instanceof Date)return`D${e.getTime()}`;let t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)return;let n=[];for(let[t,r]of Object.entries(e)){let e=signatureOf(r);if(e===void 0)return;n.push(`${JSON.stringify(t)}:${e}`)}return`{${n.join(`,`)}}`}function copyResult(e,t=new Map){if(typeof e!=`object`||!e)return e;let n=t.get(e);if(n!==void 0)return n;if(e instanceof Date)return new Date(e.getTime());if(e instanceof Uint8Array)return Uint8Array.prototype.slice.call(e);if(Array.isArray(e)){let n=[];t.set(e,n);for(let r of e)n.push(copyResult(r,t));return n}let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)return e;let i=Object.create(r);t.set(e,i);for(let[n,r]of Object.entries(e))Object.defineProperty(i,n,{value:copyResult(r,t),enumerable:!0,writable:!0,configurable:!0});return i}const S=Symbol.for(`viborm.pendingOperation`);function combineWriteNotifications(e,t){return e===void 0?t:t===void 0||t===e?e:async()=>{let n=!1,i;try{await e()}catch(e){n=!0,i=e}try{await t()}catch(e){throw n?r(i,e,`Write publication callbacks both failed.`):e}if(n)throw i}}const C=Object.freeze({});let createPendingOperationFriend,w;var T=class PendingOperation{[Symbol.toStringTag]=`Promise`;[S]=!0;#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d=!1;#f;#p;#m;#h;#g=!1;static{createPendingOperationFriend=(e,t,n,r,i,a,o)=>new PendingOperation(C,e,t,n,r,i,a===void 0?void 0:{prepare:a,status:`pending`},o),w=Object.freeze({clientId:e=>e.#e.clientId,scopeId:e=>e.#e.scopeId,model:e=>e.#i,operation:e=>e.#a,context:e=>e.#e.attribution,prepareAdmission:(e,t=`input`)=>{e.#S(),t===`plan`&&e.#x()},around:e=>{let t=String(e.#o.originalOperation),n=e.#t.extensionChain?.around?.handlers(e.#i,t);return{context:n?.length?e.#C(`array`,e.#S()):void 0,handlers:n,write:!o(t),registration:e.#v()}},executeCore:(e,t,n)=>e.#s.executeReserved(()=>e.#j(t,n?.committed,n?.mayHaveCommitted)),unit:e=>e.#E(),reserveWith:(e,t)=>{e.#s.reserveWith(t)},executeWith:(e,t)=>{let n=e.#t.extensionChain?.observation;return n===void 0?e.#s.executeWith(t,()=>e.#j(t)):e.#s.executeWith(t,()=>n.run(e.#E(!0),()=>e.#j(t)))},finishResult:(e,t)=>e.#o.finishResult?e.#o.finishResult(t):t,prepare:e=>e.#x()?.queries[0],prepareBatch:e=>e.#y().prepareBatch(e.#e.attribution),parseResult:(e,t)=>{let r=e.#x();if(!r)throw new n(`Operation '${e.#a}' on model '${e.#i}' publishes no single driver result to parse.`);return r.parseResult([t])},observeBatchPhase:(e,t,n)=>d(e.#e.attribution,t,n)}),a(PendingOperation.prototype,e=>#e in e,w),Object.freeze(PendingOperation.prototype)}constructor(e,t,n,r,a,o,s,c){if(e!==C)throw new i;this.#t=t,this.#n=n,this.#r=a,this.#c=s,this.#l=c,this.#p=t.route;let l=r.endsWith(`OrThrow`);this.#a=l?r.slice(0,-7):r,this.#i=n[`~`].names.ts??`unknown`,this.#s=new h(this.#i,this.#a),this.#o=Object.freeze({...o,throwIfNotFound:l||o?.throwIfNotFound,originalOperation:o?.originalOperation??r}),this.#e=u(this.#i,this.#a,t.clientId,t.scopeId,t.extensionChain),s&&(s.of={engine:t,context:this.#e.attribution,prepared:()=>this.#y()}),Object.freeze(this)}#_(){let e=this.#c;if(e===void 0)return this.#r;if(e.status===`success`&&e.args)return e.args;if(e.status===`failure`)throw e.error;try{let t=this.#t.extensionChain?.args?.admit(this.#i,String(this.#o.originalOperation),this.#a,this.#r,this.#t.bound),n=e.prepare(t?.args??this.#r,t?.values,e);return e.args=n,e.values=t?.values,e.status=`success`,n}catch(t){throw e.error=t,e.status=`failure`,t}}#v(){return this.#d?this.#u:(this.#u=this.#l?.(this.#e.attribution,this.#c?.values,this.#c),this.#d=!0,this.#u)}#y(){if(this.#m)return this.#m;if(!s.has(this.#a))throw new n(`Unknown operation '${this.#a}' on model '${this.#i}'. Known operations: ${[...s].sort().join(`, `)}.`);let e=this.#_();this.#v();let t=this.#p.prepare(this.#i,this.#o.originalOperation,e,this.#b());return this.#m=t,t}#b(){return(this.#t.extensionChain?.callRows)?.call(this.#i,this.#c?.values)}#x(){if(this.#g)return this.#h;let e=this.#y().prepareSingle(this.#e.attribution);return this.#h=e?.queries.length===1?e:void 0,this.#g=!0,this.#h}#S(){return this.#y().args}#C(e,t){let n=this.#c?.values,r;return Object.freeze({mode:e,kind:`model`,model:this.#i,operation:String(this.#o.originalOperation),get input(){return r??=g(t),r},...n===void 0?{}:{values:n},call:this.#c})}#w(){return this.#s.executeDefault(()=>{let e=this.#t.extensionChain?.observation;return e===void 0?this.#T(this.#D()):e.run(this.#E(!0),()=>this.#T(this.#D()))})}#T(e){let t=this.#o.finishResult;return t?e.then(e=>t(e)):e}#E(e){return{kind:`operation`,operation:String(this.#o.originalOperation),model:this.#i,context:this.#e.attribution,driver:this.#t.driver,table:this.#n[`~`].names.sql??this.#i,...e?{certainty:()=>this.#f}:{}}}#D(e,t,n){return l(this.#e.attribution,()=>this.#O(e,t,n))}#O(e,t,n){let r=this.#A(`committed`),i=this.#A(`may-have-committed`),a=String(this.#o.originalOperation),o=this.#t.extensionChain?.around?.handlers(this.#i,a);return(o===void 0||o.length===0)&&this.#l===void 0?this.#j(e,combineWriteNotifications(t,r),combineWriteNotifications(n,i)):this.#k(o,a,r,i,e,t,n)}#k(e,t,n,r,i,a,s){let c;try{c=this.#S()}catch(e){return Promise.reject(e)}let l=this.#v(),u=this.#t.extensionChain?.coordination;if(u===void 0||(e===void 0||e.length===0)&&l===void 0)return this.#j(i,combineWriteNotifications(a,n),combineWriteNotifications(s,r));let d=e===void 0||e.length===0?void 0:this.#C(this.#t.transaction?`transaction`:`direct`,c);return u.executePreparedQuery(d,e,(e,t)=>this.#j(t??i,combineWriteNotifications(a,combineWriteNotifications(e?.committed,n)),combineWriteNotifications(s,combineWriteNotifications(e?.mayHaveCommitted,r))),!o(t),this.#t.transaction,void 0,l)}#A(e){if(!(this.#t.transaction!==void 0||this.#t.extensionChain?.observation===void 0))return async()=>{(e===`committed`||this.#f===void 0)&&(this.#f=e)}}#j(e,t,n){return this.#M(e,t,n)}#M(e,t,n){let r;try{r=this.#y()}catch(e){return Promise.reject(e)}let run=()=>r.run({committedWriteSegment:t,context:this.#e.attribution,driverOverride:e,engineDriver:this.#t.driver,isWrite:!o(String(this.#o.originalOperation)),writeMayBeVisible:n});if(this.#a===`findUnique`&&e===void 0&&r.seen===void 0){let e=batchFindUnique({engine:this.#t,model:this.#n,requested:String(this.#o.originalOperation),args:this.#_(),values:this.#c?.values,rows:()=>this.#b(),routed:r,context:this.#e.attribution,run});if(e!==void 0)return e}return run()}getArgs(){return this.#r}buildStatement(){return this.#y().read?.statement}then(e,t){return this.#w().then(e,t)}catch(e){return this.#w().catch(e)}finally(e){return this.#w().finally(e)}};function createPendingOperation(e,t,n,r,i,a,o){return createPendingOperationFriend(e,t,n,r,i,a,o)}function isPendingOperation(e){return typeof e==`object`&&!!e&&S in e&&e[S]===!0}export{compileBindBudgetChunks as a,enableFindUniqueBatching as i,createPendingOperation as n,isPendingOperation as r,T as t};
2
- //# sourceMappingURL=pending-operation-C_eOFOBE.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"pending-operation-C_eOFOBE.mjs","names":["copy","#context","#engine","#model","#args","#modelName","#operation","#options","#execution","#inputPreparation","#prepareWriteOutcomeRegistration","#route","#preparedInput","#resolveSinglePackage","#queryContext","#resolveWriteOutcomeRegistration","#runCoreExecution","#unit","#resolveRouted","#writeOutcomeRegistrationResolved","#writeOutcomeRegistration","#routedInstance","#resolveArgs","#callRows","#singlePackageResolved","#singlePackage","#finished","#runExecution","#observationCommitCertainty","#runAttributedExecution","#observationNotification","#runExtendedExecution","#run","#getPromise"],"sources":["../src/query-engine/bind-budget.ts","../src/query-engine/find-unique-batch.ts","../src/query-engine/pending-operation.ts"],"sourcesContent":["import type { Sql } from \"@sql\";\n\nexport { normalizedBindParameterLimit } from \"@drivers/bind-parameter-capacity\";\n\nexport interface CompiledBindBudgetChunk {\n /** Inclusive semantic-item offset. */\n readonly start: number;\n /** Exclusive semantic-item offset. */\n readonly end: number;\n readonly statement: Sql;\n}\n\n/**\n * Compile the largest contiguous semantic-item ranges that fit a verified bind\n * budget. The compiled SQL is the meter; callers do not estimate binds from\n * item count or shape. `compile` must be monotonic for a growing prefix, as\n * INSERT value tuples and exact-key predicate lists are.\n *\n * Unknown capacity preserves the original one-statement shape. One item that\n * exceeds a known budget stays indivisible so the executor's final capacity\n * check can refuse it before I/O.\n */\nexport function compileBindBudgetChunks(\n itemCount: number,\n maxBindParametersPerStatement: number | undefined,\n compile: (start: number, end: number) => Sql\n): CompiledBindBudgetChunk[] {\n if (itemCount === 0) return [];\n const whole = compile(0, itemCount);\n if (\n maxBindParametersPerStatement === undefined ||\n whole.values.length <= maxBindParametersPerStatement ||\n itemCount === 1\n ) {\n return [{ start: 0, end: itemCount, statement: whole }];\n }\n\n const chunks: CompiledBindBudgetChunk[] = [];\n let start = 0;\n while (start < itemCount) {\n let lower = start + 1;\n let upper = Math.min(itemCount, start + 1);\n let largest: CompiledBindBudgetChunk | undefined;\n // Probe geometrically from this window, never from the entire remaining\n // suffix. Oversized compilation stays proportional to a window's size.\n while (true) {\n const statement = compile(start, upper);\n if (statement.values.length > maxBindParametersPerStatement) break;\n largest = { start, end: upper, statement };\n if (upper === itemCount) break;\n lower = upper + 1;\n upper = Math.min(itemCount, start + (upper - start) * 2);\n }\n if (largest?.end !== itemCount) {\n upper -= 1;\n while (lower <= upper) {\n const end = lower + Math.floor((upper - lower) / 2);\n const statement = compile(start, end);\n if (statement.values.length <= maxBindParametersPerStatement) {\n largest = { start, end, statement };\n lower = end + 1;\n } else upper = end - 1;\n }\n }\n const chunk = largest ?? {\n start,\n end: start + 1,\n statement: compile(start, start + 1),\n };\n chunks.push(chunk);\n start = chunk.end;\n }\n return chunks;\n}\n","/**\n * `findUnique` batching: Prisma's dataloader, at the operation dispatch layer.\n *\n * Opt-in (`createClient({ findUniqueBatching: true })`, 1.4.1): calls issued\n * in the same tick that would each cost one round trip are answered by ONE\n * `findMany` over the keys they name, and each caller gets its own row back.\n * The shared read runs in its leader's own async context (the first call of\n * its batch), which may not be every member's: a driver that picks a database\n * by `AsyncLocalStorage`, or a trace per request, sees the leader's. That is\n * why it is opt-in. The merge happens below every per-call lifecycle step — request\n * transforms, arguments, default omit, admission, query interceptors, the\n * official cache and observers all still see each call as its own operation —\n * and above the route, which runs the merged read like any other read.\n *\n * Two calls share a batch only when nothing that decides their rows differs:\n * the same engine (so the same client view, extension chain and bound\n * arguments), outside every transaction, the same model, the same unique key\n * spelled the same way, the same projection (`select`/`include`/`omit`, nested\n * arguments included, compared structurally) and the same admitted arguments.\n * The `where` must be the key alone: a value per member, nothing else.\n *\n * A row reaches a caller only when its decoded key is EXACTLY the caller's\n * admitted key. Whatever cannot be decided that way runs as the caller's own\n * unbatched operation, so a batch can cost a statement but never change an\n * answer:\n * - a string key without an exact match (a case-insensitive or padding\n * collation can make the database find a row JavaScript does not match);\n * - a missing row for `findUniqueOrThrow` (its own error comes from its owner);\n * - a merged read that fails, for every caller of that read.\n * Only string, integer and bigint key members are batched. An integer or\n * bigint member's decoded value is its bound value, so a row JavaScript does\n * not match is a row the database did not return either: a missing integer\n * key answers `null` from the batch.\n */\n\nimport { passThroughParseResult } from \"@adapters/adapter-result-parser\";\nimport { normalizedBindParameterLimit } from \"@drivers/bind-parameter-capacity\";\nimport { deriveRecoverableExecutionContext } from \"@drivers/execution-context\";\nimport type { QueryExecutionContext } from \"@drivers/exports\";\nimport type { AdmittedArgs } from \"@extensions/arguments\";\nimport type { AnyModel } from \"@schema/model\";\nimport { findAddressableKey } from \"@schema/model/keys\";\nimport { isRecord } from \"@validation/value-guards\";\nimport { compileBindBudgetChunks } from \"./bind-budget\";\nimport type { QueryEngine } from \"./query-engine\";\nimport type { PreparedOperation } from \"./raptor3/commands\";\nimport type { CallRows } from \"./raptor3/shared/row-scope\";\n\n/** One `findUnique` call, as its pending operation knows it at dispatch. */\nexport interface FindUniqueCall {\n readonly engine: QueryEngine;\n readonly model: AnyModel;\n /** `findUnique` or `findUniqueOrThrow`. */\n readonly requested: string;\n /** The client-prepared input: arguments removed, request transforms applied. */\n readonly args: Record<string, unknown>;\n readonly values: AdmittedArgs | undefined;\n /** The call's own row domain, resolved for the batch that runs it. */\n readonly rows: () => CallRows | undefined;\n readonly routed: PreparedOperation;\n readonly context: QueryExecutionContext;\n /** The call's own, unbatched execution. */\n readonly run: () => Promise<unknown>;\n}\n\n/** What a batch decided for one caller. */\ntype Decision = { readonly value: unknown } | typeof RUN_ALONE;\nconst RUN_ALONE = Symbol(\"run alone\");\n\ninterface Member {\n readonly values: readonly unknown[];\n readonly signature: string;\n readonly orThrow: boolean;\n readonly decide: (decision: Decision) => void;\n}\n\ninterface Batch {\n readonly leader: FindUniqueCall;\n /** Starts the batch in its leader's own continuation (its async context). */\n readonly start: () => void;\n readonly fields: readonly string[];\n readonly textKey: boolean;\n readonly members: Member[];\n}\n\n/** Key members whose decoded value is the bound value, by scalar type. */\nconst EXACT_KEY_VALUES: Readonly<Record<string, (value: unknown) => boolean>> =\n {\n string: (value) => typeof value === \"string\",\n int: (value) => typeof value === \"number\" && Number.isSafeInteger(value),\n bigint: (value) => typeof value === \"bigint\",\n };\n\nlet pending: Map<QueryEngine, Map<string, Batch[]>> | undefined;\n\n/** The operation routes of the clients created with `findUniqueBatching`. */\nconst batchingRoutes = new WeakSet<object>();\n\n/** Turn batching on for every engine of the client that owns `route`. */\nexport function enableFindUniqueBatching(route: object): void {\n batchingRoutes.add(route);\n}\n\n/**\n * After the current synchronous run AND the microtasks it queued, so resolvers\n * that each await once before calling still share a batch. Where there is no\n * `process.nextTick`, the end of the current synchronous run.\n */\nconst defer: (callback: () => void) => void = (() => {\n const host = (\n globalThis as {\n process?: { nextTick?: (callback: () => void) => void };\n }\n ).process;\n const nextTick = host?.nextTick;\n return typeof nextTick === \"function\"\n ? (callback) => nextTick.call(host, callback)\n : queueMicrotask;\n})();\n\n/**\n * Join a batch, or answer `undefined` when this call does not batch and must\n * run as it always has.\n */\nexport function batchFindUnique(\n call: FindUniqueCall\n): Promise<unknown> | undefined {\n // A call on the originating client inside its own callback transaction\n // runs alone, and is refused there as it always was: in a batch, the shared\n // read would queue behind the transaction that waits for this call.\n if (!engineBatches(call.engine) || call.engine.driver.holdsConnectionScope())\n return undefined;\n let admitted: Record<string, unknown>;\n try {\n admitted = call.routed.args;\n } catch {\n // The call's own execution admits again and rejects with the same error.\n return undefined;\n }\n const key = keyOf(call.model, admitted.where);\n if (key === undefined) return undefined;\n const { where: _where, ...projection } = call.args;\n const shape = signatureOf(projection);\n if (shape === undefined) return undefined;\n\n let decide!: (decision: Decision) => void;\n const decision = new Promise<Decision>((resolve) => {\n decide = resolve;\n });\n let lead!: (batch: Batch) => void;\n const leading = new Promise<Batch>((resolve) => {\n lead = resolve;\n });\n const member: Member = {\n values: key.values,\n signature: signatureOf(key.values)!,\n orThrow: call.requested !== \"findUnique\",\n decide,\n };\n const leads = enqueue(\n call,\n `${key.selector}\\u0000${shape}`,\n key,\n member,\n lead\n );\n // Continuations run in the async context of the call that registered them:\n // the leader runs its batch in its own, and a call that runs alone runs in\n // its own. The tick's flush runs in whichever context queued first, and\n // only starts batches.\n const settled = leads\n ? leading.then((batch) => {\n runBatch(batch);\n return decision;\n })\n : decision;\n return settled.then((outcome) =>\n outcome === RUN_ALONE ? call.run() : outcome.value\n );\n}\n\n/**\n * The engine runs outside every transaction scope, and nothing below the\n * operation is keyed on the statement or the operation name: a statement\n * transform sees `findUnique`, and a result middleware is handed the operation\n * name, so either would observe the merged `findMany`.\n */\nfunction engineBatches(engine: QueryEngine): boolean {\n const { driver } = engine;\n return (\n batchingRoutes.has(engine.route) &&\n driver === engine.route.driver &&\n engine.extensionChain?.rewrites === undefined &&\n driver.result?.parseResult === undefined &&\n driver.adapter.result.parseResult === passThroughParseResult\n );\n}\n\ninterface BatchKey {\n readonly selector: string;\n readonly fields: readonly string[];\n readonly values: readonly unknown[];\n readonly textKey: boolean;\n}\n\n/** The admitted `where` as one addressable key and nothing else, or nothing. */\nfunction keyOf(model: AnyModel, where: unknown): BatchKey | undefined {\n if (!isRecord(where)) return undefined;\n const selectors = Object.keys(where);\n if (selectors.length !== 1) return undefined;\n const selector = selectors[0]!;\n const key = findAddressableKey(model, selector);\n if (key === undefined) return undefined;\n const value = where[selector];\n let values: unknown[];\n if (key.name === undefined) values = [value];\n else {\n if (!isRecord(value) || Object.keys(value).length !== key.fields.length)\n return undefined;\n values = key.fields.map((field) => value[field]);\n }\n // A member the model hides from every result cannot be read back to\n // dispatch a row, and no call may select it.\n const { scalars, omit } = model[\"~\"].state;\n let textKey = false;\n for (const [index, field] of key.fields.entries()) {\n const state = scalars[field]?.[\"~\"].state;\n const exact = state && !state.array && EXACT_KEY_VALUES[state.type];\n if (!exact?.(values[index]) || omit?.[field] === true) return undefined;\n if (state.type === \"string\") textKey = true;\n }\n return { selector, fields: key.fields, values, textKey };\n}\n\n/** Join or open a batch; `true` when this call opened it and leads it. */\nfunction enqueue(\n call: FindUniqueCall,\n shape: string,\n key: BatchKey,\n member: Member,\n lead: (batch: Batch) => void\n): boolean {\n if (pending === undefined) {\n pending = new Map();\n defer(flush);\n }\n let byShape = pending.get(call.engine);\n if (byShape === undefined) pending.set(call.engine, (byShape = new Map()));\n const signature = `${call.model[\"~\"].names.ts}\\u0000${shape}`;\n let batches = byShape.get(signature);\n if (batches === undefined) byShape.set(signature, (batches = []));\n let batch = batches.find((candidate) =>\n sameControls(candidate.leader.values, call.values)\n );\n let leads = false;\n if (batch === undefined) {\n const opened: Batch = {\n leader: call,\n start: () => lead(opened),\n fields: key.fields,\n textKey: key.textKey,\n members: [],\n };\n batch = opened;\n batches.push(batch);\n leads = true;\n }\n batch.members.push(member);\n return leads;\n}\n\n/** Admitted arguments decide the row domain: the same values, the same rows. */\nfunction sameControls(\n first: AdmittedArgs | undefined,\n second: AdmittedArgs | undefined\n): boolean {\n if (first === second) return true;\n if (first === undefined || second === undefined) return false;\n const names = Object.keys(first);\n return (\n names.length === Object.keys(second).length &&\n names.every(\n (name) => Object.hasOwn(second, name) && first[name] === second[name]\n )\n );\n}\n\nfunction flush(): void {\n const batches = pending;\n pending = undefined;\n for (const byShape of batches!.values())\n for (const list of byShape.values())\n for (const batch of list) batch.start();\n}\n\ninterface Chunk {\n readonly signatures: readonly string[];\n readonly read: PreparedOperation;\n}\n\n/**\n * Run one batch. Whatever goes wrong before a caller's row is decided sends\n * that caller back to its own execution; a caller is decided once, so a later\n * decision never replaces an earlier one.\n */\nfunction runBatch(batch: Batch): void {\n const { members } = batch;\n const runAlone = (callers: readonly Member[]) => {\n for (const member of callers) member.decide(RUN_ALONE);\n };\n if (members.length === 1) {\n runAlone(members);\n return;\n }\n try {\n const bySignature = new Map<string, Member[]>();\n for (const member of members) {\n const same = bySignature.get(member.signature);\n if (same) same.push(member);\n else bySignature.set(member.signature, [member]);\n }\n const plan = planBatch(batch, [...bySignature.values()]);\n const { engine } = batch.leader;\n // Its callers recover a failure by running alone, so the shared read's\n // own failure is not logged or traced as an error.\n const context = deriveRecoverableExecutionContext(batch.leader.context);\n for (const chunk of plan.chunks) {\n const callers = chunk.signatures.flatMap((key) => bySignature.get(key)!);\n (\n chunk.read.run({\n committedWriteSegment: undefined,\n context,\n driverOverride: undefined,\n engineDriver: engine.driver,\n isWrite: false,\n writeMayBeVisible: undefined,\n }) as Promise<Record<string, unknown>[]>\n ).then(\n (rows) => {\n try {\n dispatch(batch, chunk, bySignature, plan.injected, rows);\n } catch {\n runAlone(callers);\n }\n },\n () => runAlone(callers)\n );\n }\n } catch {\n runAlone(members);\n }\n}\n\n/**\n * The merged reads, split where the driver's bind budget requires, through the\n * one chunking owner: the compiled statement is the meter.\n */\nfunction planBatch(\n batch: Batch,\n keys: readonly (readonly Member[])[]\n): { chunks: Chunk[]; injected: readonly string[] } {\n const { leader, fields } = batch;\n const projected = projectionWithKey(leader, fields);\n const rows = leader.rows();\n const reads = new Map<string, PreparedOperation>();\n const read = (start: number, end: number): PreparedOperation => {\n const id = `${start}:${end}`;\n let operation = reads.get(id);\n if (operation === undefined) {\n const values = keys.slice(start, end).map((same) => same[0]!.values);\n operation = leader.engine.route.prepare(\n leader.model[\"~\"].names.ts!,\n \"findMany\",\n { ...projected.args, where: mergedWhere(fields, values) },\n rows\n );\n reads.set(id, operation);\n }\n return operation;\n };\n const signatures = keys.map((same) => same[0]!.signature);\n const limit = normalizedBindParameterLimit(\n leader.engine.driver.maxBindParametersPerStatement\n );\n const ranges =\n limit === undefined\n ? [{ start: 0, end: keys.length }]\n : compileBindBudgetChunks(\n keys.length,\n limit,\n (start, end) => read(start, end).read!.statement\n );\n return {\n chunks: ranges.map(({ start, end }) => ({\n signatures: signatures.slice(start, end),\n read: read(start, end),\n })),\n injected: projected.injected,\n };\n}\n\n/** One key member: `IN`; a compound key: one equality group per key. */\nfunction mergedWhere(\n fields: readonly string[],\n values: readonly (readonly unknown[])[]\n): Record<string, unknown> {\n if (fields.length === 1)\n return { [fields[0]!]: { in: values.map((value) => value[0]) } };\n return {\n OR: values.map((value) =>\n Object.fromEntries(fields.map((field, index) => [field, value[index]]))\n ),\n };\n}\n\n/**\n * The leader's projection with every key member read, so each row can be\n * dispatched; a member the caller does not read is removed again before the\n * row is handed over. A member can be missing because it is not selected or\n * because it is omitted (an omit wins over a select), so both are lifted.\n */\nfunction projectionWithKey(\n leader: FindUniqueCall,\n fields: readonly string[]\n): { args: Record<string, unknown>; injected: string[] } {\n const { where: _where, ...args } = leader.args;\n const selected = leader.routed.args.select;\n const injected: string[] = [];\n if (!isRecord(selected)) return { args, injected };\n for (const field of fields) {\n if (selected[field] === true) continue;\n if (isRecord(args.select)) args.select = { ...args.select, [field]: true };\n if (isRecord(args.omit)) args.omit = { ...args.omit, [field]: false };\n injected.push(field);\n }\n return { args, injected };\n}\n\nfunction dispatch(\n batch: Batch,\n chunk: Chunk,\n bySignature: ReadonlyMap<string, readonly Member[]>,\n injected: readonly string[],\n rows: readonly Record<string, unknown>[]\n): void {\n const found = new Map<string | undefined, Record<string, unknown>>();\n for (const row of rows) {\n const signature = signatureOf(batch.fields.map((field) => row[field]));\n for (const field of injected) delete row[field];\n if (!found.has(signature)) found.set(signature, row);\n }\n for (const signature of chunk.signatures) {\n const row = found.get(signature);\n for (const [index, member] of bySignature.get(signature)!.entries()) {\n if (row !== undefined)\n member.decide({ value: index === 0 ? row : copyResult(row) });\n else if (member.orThrow || batch.textKey) member.decide(RUN_ALONE);\n else member.decide({ value: null });\n }\n }\n}\n\n/**\n * A structural signature of plain argument data: equal signatures, equal\n * arguments. Anything else (a function, a fragment, a class instance) has\n * none, and the call does not batch.\n */\nfunction signatureOf(value: unknown): string | undefined {\n switch (typeof value) {\n case \"undefined\":\n return \"u\";\n case \"boolean\":\n case \"number\":\n return String(value);\n case \"string\":\n return JSON.stringify(value);\n case \"bigint\":\n return `${value}n`;\n case \"object\":\n break;\n default:\n return undefined;\n }\n if (value === null) return \"null\";\n if (Array.isArray(value)) {\n const items: string[] = [];\n for (const item of value) {\n const signature = signatureOf(item);\n if (signature === undefined) return undefined;\n items.push(signature);\n }\n return `[${items.join(\",\")}]`;\n }\n if (value instanceof Date) return `D${value.getTime()}`;\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) return undefined;\n const entries: string[] = [];\n for (const [name, entry] of Object.entries(value)) {\n const signature = signatureOf(entry);\n if (signature === undefined) return undefined;\n entries.push(`${JSON.stringify(name)}:${signature}`);\n }\n return `{${entries.join(\",\")}}`;\n}\n\n/**\n * A second caller of the same key gets its own result, as it would have\n * unbatched: plain objects, arrays, dates and byte arrays are copied, keeping\n * the shape of what is shared inside the result (a node reached twice is one\n * copy); an immutable value (a Decimal) is shared. Members are defined, never\n * assigned, so a JSON key named `__proto__` stays an own member.\n */\nfunction copyResult(\n value: unknown,\n copies = new Map<object, unknown>()\n): unknown {\n if (typeof value !== \"object\" || value === null) return value;\n const known = copies.get(value);\n if (known !== undefined) return known;\n if (value instanceof Date) return new Date(value.getTime());\n if (value instanceof Uint8Array)\n return Uint8Array.prototype.slice.call(value);\n if (Array.isArray(value)) {\n const copy: unknown[] = [];\n copies.set(value, copy);\n for (const item of value) copy.push(copyResult(item, copies));\n return copy;\n }\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) return value;\n const copy = Object.create(prototype) as object;\n copies.set(value, copy);\n for (const [name, entry] of Object.entries(value))\n Object.defineProperty(copy, name, {\n value: copyResult(entry, copies),\n enumerable: true,\n writable: true,\n configurable: true,\n });\n return copy;\n}\n","/**\n * Deferred operation lifecycle owned by the query engine.\n * Validation, SQL construction, and execution remain lazy until a lifecycle\n * method is called. Every operation is served by the single (V2) engine.\n */\n\nimport type { AnyDriver, QueryExecutionContext } from \"@drivers/exports\";\nimport {\n InvalidTransactionInputError,\n retainWriteOutcomeFailure,\n} from \"@errors\";\nimport type { AdmittedArgs } from \"@extensions/arguments\";\nimport type { CallOrigin } from \"@extensions/origin\";\nimport type {\n AroundHandlers,\n CallMode,\n PreparedModelQueryContext,\n WriteOutcomeRegistration,\n} from \"@extensions/query\";\nimport type { UnitSource } from \"@extensions/unit-source\";\nimport type { AnyModel } from \"@schema/model\";\nimport type { Sql } from \"@sql\";\nimport {\n createPendingOperationContext,\n type OperationExecutionContext,\n observeTransactionBatchPhase,\n withOperationErrorContext,\n} from \"./execution-context\";\nimport { batchFindUnique } from \"./find-unique-batch\";\nimport { PendingExecution } from \"./pending-execution\";\nimport type { QueryEngine } from \"./query-engine\";\nimport { snapshotQueryInput } from \"./query-inspection\";\nimport type { CommandEngine, PreparedOperation } from \"./raptor3/commands\";\nimport { isReadOperation, ROUTED_OPERATIONS } from \"./routed-operations\";\nimport {\n registerTransactionOperationOwner,\n type TransactionOperation,\n type TransactionOperationOwner,\n} from \"./transaction-operation\";\nimport {\n type Operation,\n type PreparedBatchOperation,\n type PrepareOptions,\n QueryEngineError,\n} from \"./types\";\n\nexport const PENDING_OPERATION_SYMBOL = Symbol.for(\"viborm.pendingOperation\");\n\n/** Publish a durably committed write segment to the cache and observers. */\nexport type CommittedWriteSegmentNotification = () => Promise<void>;\n/** Conservatively invalidate after dispatch when provider acknowledgement is ambiguous. */\nexport type WriteMayBeVisibleNotification = () => Promise<void>;\n\nfunction combineWriteNotifications(\n first: (() => Promise<void>) | undefined,\n second: (() => Promise<void>) | undefined\n): (() => Promise<void>) | undefined {\n if (first === undefined) return second;\n if (second === undefined || second === first) return first;\n return async () => {\n let firstFailed = false;\n let firstFailure: unknown;\n try {\n await first();\n } catch (error) {\n firstFailed = true;\n firstFailure = error;\n }\n try {\n await second();\n } catch (error) {\n if (firstFailed) {\n throw retainWriteOutcomeFailure(\n firstFailure,\n error,\n \"Write publication callbacks both failed.\"\n );\n }\n throw error;\n }\n if (firstFailed) throw firstFailure;\n };\n}\n\n/**\n * Client-owned work that must finish before operation construction starts. It\n * receives the call's arguments without the ones extensions declare (`args`),\n * and the values admitted from those.\n */\nexport type PrepareOperationInput = (\n args: Record<string, unknown>,\n values: AdmittedArgs | undefined,\n /** One object per call: what an extension's two moments of it share. */\n call: object\n) => Record<string, unknown>;\n\n/** Package-owned write listener prepared only after the operation input is trusted. */\nexport type PrepareWriteOutcomeRegistration = (\n context: QueryExecutionContext,\n values: AdmittedArgs | undefined,\n call: object | undefined\n) => WriteOutcomeRegistration | undefined;\n\ninterface OperationInputPreparation extends CallOrigin {\n readonly prepare: PrepareOperationInput;\n status: \"pending\" | \"success\" | \"failure\";\n args?: Record<string, unknown>;\n /** The operation's one admission record, settled with its arguments. */\n values?: AdmittedArgs;\n error?: unknown;\n}\n\ntype ResolvedPrepareOptions = Readonly<\n PrepareOptions & { readonly originalOperation: string }\n>;\n\nconst OR_THROW_SUFFIX = \"OrThrow\";\nconst pendingOperationConstruction = Object.freeze({});\n\ntype CreatePendingOperation = <T>(\n engine: QueryEngine,\n model: AnyModel,\n operation: Operation | `${Operation}OrThrow`,\n args: Record<string, unknown>,\n options?: PrepareOptions,\n prepareInput?: PrepareOperationInput,\n prepareWriteOutcomeRegistration?: PrepareWriteOutcomeRegistration\n) => PendingOperation<T>;\n\nlet createPendingOperationFriend: CreatePendingOperation;\n\nlet pendingOperationTransactionOwner: TransactionOperationOwner<\n PendingOperation<unknown>\n>;\n\n/** One user operation, from lazy creation through execution and parsing. */\nexport class PendingOperation<T>\n implements Promise<T>, TransactionOperation<T>\n{\n readonly [Symbol.toStringTag] = \"Promise\";\n readonly [PENDING_OPERATION_SYMBOL] = true;\n readonly #context: OperationExecutionContext;\n readonly #engine: QueryEngine;\n readonly #model: AnyModel;\n readonly #args: Record<string, unknown>;\n readonly #modelName: string;\n readonly #operation: Operation;\n readonly #options: ResolvedPrepareOptions;\n\n readonly #execution: PendingExecution<T>;\n readonly #inputPreparation: OperationInputPreparation | undefined;\n readonly #prepareWriteOutcomeRegistration:\n | PrepareWriteOutcomeRegistration\n | undefined;\n #writeOutcomeRegistration: WriteOutcomeRegistration | undefined;\n #writeOutcomeRegistrationResolved = false;\n #observationCommitCertainty: \"committed\" | \"may-have-committed\" | undefined;\n\n // The ONE operation owner (C-01). Every client lineage builds it in\n // `VibORM`'s constructor and `bind()` forwards it, so an operation that was\n // created from a client has one.\n readonly #route: CommandEngine;\n #routedInstance: PreparedOperation | undefined;\n #singlePackage: PreparedBatchOperation<unknown> | undefined;\n #singlePackageResolved = false;\n\n static {\n createPendingOperationFriend = <T>(\n engine: QueryEngine,\n model: AnyModel,\n operation: Operation | `${Operation}OrThrow`,\n args: Record<string, unknown>,\n options?: PrepareOptions,\n prepareInput?: PrepareOperationInput,\n prepareWriteOutcomeRegistration?: PrepareWriteOutcomeRegistration\n ) =>\n new PendingOperation<T>(\n pendingOperationConstruction,\n engine,\n model,\n operation,\n args,\n options,\n prepareInput === undefined\n ? undefined\n : { prepare: prepareInput, status: \"pending\" },\n prepareWriteOutcomeRegistration\n );\n pendingOperationTransactionOwner = Object.freeze({\n clientId: (operation) => operation.#context.clientId,\n scopeId: (operation) => operation.#context.scopeId,\n model: (operation) => operation.#modelName,\n operation: (operation) => operation.#operation,\n context: (operation) => operation.#context.attribution,\n prepareAdmission: (operation, phase = \"input\") => {\n operation.#preparedInput();\n if (phase === \"plan\") operation.#resolveSinglePackage();\n },\n around: (operation) => {\n const requestedOperation = String(operation.#options.originalOperation);\n const handlers = operation.#engine.extensionChain?.around?.handlers(\n operation.#modelName,\n requestedOperation\n );\n return {\n context: handlers?.length\n ? operation.#queryContext(\"array\", operation.#preparedInput())\n : undefined,\n handlers,\n write: !isReadOperation(requestedOperation),\n registration: operation.#resolveWriteOutcomeRegistration(),\n };\n },\n executeCore: (operation, driver, notifications) =>\n operation.#execution.executeReserved(() =>\n operation.#runCoreExecution(\n driver,\n notifications?.committed,\n notifications?.mayHaveCommitted\n )\n ),\n unit: (operation) => operation.#unit(),\n reserveWith: (operation, driver) => {\n operation.#execution.reserveWith(driver);\n },\n executeWith: (operation, driver) => {\n const observation = operation.#engine.extensionChain?.observation;\n if (observation === undefined) {\n return operation.#execution.executeWith(driver, () =>\n operation.#runCoreExecution(driver)\n );\n }\n return operation.#execution.executeWith(driver, () =>\n observation.run(operation.#unit(true), () =>\n operation.#runCoreExecution(driver)\n )\n );\n },\n // One preparation answers both arms: the package this operation prepares\n // to synchronously publishes the one query and the parser for its one\n // result. A verb that needs the asynchronous fold publishes no single\n // query, and the array owner asks it for the package instead.\n finishResult: (operation, value) =>\n operation.#options.finishResult\n ? operation.#options.finishResult(value)\n : value,\n prepare: (operation) => operation.#resolveSinglePackage()?.queries[0],\n prepareBatch: (operation) =>\n operation.#resolveRouted().prepareBatch(operation.#context.attribution),\n parseResult: (operation, raw) => {\n const single = operation.#resolveSinglePackage();\n if (!single) {\n throw new QueryEngineError(\n `Operation '${operation.#operation}' on model '${operation.#modelName}' publishes no single driver result to parse.`\n );\n }\n return single.parseResult([raw]);\n },\n observeBatchPhase: (operation, driver, execute) =>\n observeTransactionBatchPhase(\n operation.#context.attribution,\n driver,\n execute\n ),\n } satisfies TransactionOperationOwner<PendingOperation<unknown>>);\n registerTransactionOperationOwner(\n PendingOperation.prototype,\n (value): value is PendingOperation<unknown> => #context in value,\n pendingOperationTransactionOwner\n );\n Object.freeze(PendingOperation.prototype);\n }\n\n private constructor(\n construction: typeof pendingOperationConstruction,\n engine: QueryEngine,\n model: AnyModel,\n requestedOperation: Operation | `${Operation}OrThrow`,\n args: Record<string, unknown>,\n options?: PrepareOptions,\n inputPreparation?: OperationInputPreparation,\n prepareWriteOutcomeRegistration?: PrepareWriteOutcomeRegistration\n ) {\n if (construction !== pendingOperationConstruction) {\n throw new InvalidTransactionInputError();\n }\n this.#engine = engine;\n this.#model = model;\n this.#args = args;\n this.#inputPreparation = inputPreparation;\n this.#prepareWriteOutcomeRegistration = prepareWriteOutcomeRegistration;\n // Every client lineage installs the route in `VibORM`'s constructor and\n // `bind()` forwards it (C-01); an engine built outside that lineage owns no\n // operation path at all.\n this.#route = engine.route;\n const isOrThrow = requestedOperation.endsWith(OR_THROW_SUFFIX);\n this.#operation = isOrThrow\n ? (requestedOperation.slice(0, -OR_THROW_SUFFIX.length) as Operation)\n : (requestedOperation as Operation);\n this.#modelName = model[\"~\"].names.ts ?? \"unknown\";\n this.#execution = new PendingExecution<T>(this.#modelName, this.#operation);\n this.#options = Object.freeze({\n ...options,\n throwIfNotFound: isOrThrow || options?.throwIfNotFound,\n originalOperation: options?.originalOperation ?? requestedOperation,\n });\n this.#context = createPendingOperationContext(\n this.#modelName,\n this.#operation,\n engine.clientId,\n engine.scopeId,\n engine.extensionChain\n );\n // The call object an extension's moments share is where the words on the\n // call (`key`, `codec`, `database`) find the operation it became.\n if (inputPreparation)\n inputPreparation.of = {\n engine,\n context: this.#context.attribution,\n prepared: () => this.#resolveRouted(),\n };\n Object.freeze(this);\n }\n\n /**\n * Resolve client request preparation once, caching both values and throws.\n * The arguments extensions declare leave the call's own and are admitted\n * first, so the record is settled with the call's own arguments and no\n * first moment sees a declared one among them.\n */\n #resolveArgs(): Record<string, unknown> {\n const preparation = this.#inputPreparation;\n if (preparation === undefined) return this.#args;\n if (preparation.status === \"success\" && preparation.args) {\n return preparation.args;\n }\n if (preparation.status === \"failure\") throw preparation.error;\n\n try {\n const admission = this.#engine.extensionChain?.args?.admit(\n this.#modelName,\n String(this.#options.originalOperation),\n this.#operation,\n this.#args,\n this.#engine.bound\n );\n const args = preparation.prepare(\n admission?.args ?? this.#args,\n admission?.values,\n preparation\n );\n preparation.args = args;\n preparation.values = admission?.values;\n preparation.status = \"success\";\n return args;\n } catch (error) {\n preparation.error = error;\n preparation.status = \"failure\";\n throw error;\n }\n }\n\n /** Resolve one exact package-owned listener for every lifecycle entry point. */\n #resolveWriteOutcomeRegistration(): WriteOutcomeRegistration | undefined {\n if (this.#writeOutcomeRegistrationResolved) {\n return this.#writeOutcomeRegistration;\n }\n this.#writeOutcomeRegistration = this.#prepareWriteOutcomeRegistration?.(\n this.#context.attribution,\n this.#inputPreparation?.values,\n this.#inputPreparation\n );\n this.#writeOutcomeRegistrationResolved = true;\n return this.#writeOutcomeRegistration;\n }\n\n /** Construct (once) the route's view of this operation. */\n #resolveRouted(): PreparedOperation {\n if (this.#routedInstance) return this.#routedInstance;\n // The model proxy answers every property with a callable child, so a\n // misspelled or REMOVED operation name (`createManyAndReturn`,\n // `updateManyAndReturn` — see the implicit-returning surface) reaches here\n // instead of failing as \"undefined is not a function\". Name it as what it\n // is, from the one vocabulary owner, before the route is asked for a verb\n // it has no construction path for.\n if (!ROUTED_OPERATIONS.has(this.#operation)) {\n throw new QueryEngineError(\n `Unknown operation '${this.#operation}' on model '${this.#modelName}'. Known operations: ${[...ROUTED_OPERATIONS].sort().join(\", \")}.`\n );\n }\n const args = this.#resolveArgs();\n // A package-owned listener may tell the engine what to report while it\n // plans (a write hook's upsert arm): it exists before any planning.\n this.#resolveWriteOutcomeRegistration();\n const routed = this.#route.prepare(\n this.#modelName,\n // Refused above where it is no operation the engine knows.\n this.#options.originalOperation as never,\n args,\n this.#callRows()\n );\n this.#routedInstance = routed;\n return routed;\n }\n\n /** The row facts this call's admitted arguments resolve to, if any. */\n #callRows() {\n const binding = this.#engine.extensionChain?.callRows;\n return binding?.call(this.#modelName, this.#inputPreparation?.values);\n }\n\n /**\n * The ONE prepared package this operation compiles to when it compiles to\n * exactly one driver query — every read. The route prepares it once and both\n * array-owner arms read it: the query `prepare()` publishes and the parser\n * `parseResult()` applies come from that single preparation, so a member's\n * statement and its decoder cannot describe different queries.\n */\n #resolveSinglePackage(): PreparedBatchOperation<unknown> | undefined {\n if (this.#singlePackageResolved) return this.#singlePackage;\n const prepared = this.#resolveRouted().prepareSingle(\n this.#context.attribution\n );\n this.#singlePackage = prepared?.queries.length === 1 ? prepared : undefined;\n this.#singlePackageResolved = true;\n return this.#singlePackage;\n }\n\n /**\n * The payload this operation runs: the prepared operation's ONE admission.\n * Resolving it settles request preparation and admits the operation.\n */\n #preparedInput(): Record<string, unknown> {\n return this.#resolveRouted().args;\n }\n\n /**\n * The prepared facts one query handler chain inspects. Its `input` is\n * snapshotted at the first read, once for the whole chain: the prepared\n * payload is the admission's own and nothing writes it after admission, so\n * a later snapshot says what an eager one would, and a chain that never\n * reads it never copies it.\n */\n #queryContext(\n mode: CallMode,\n preparedInput: Record<string, unknown>\n ): PreparedModelQueryContext<Record<string, unknown>> {\n const values = this.#inputPreparation?.values;\n let input: Readonly<Record<string, unknown>> | undefined;\n return Object.freeze({\n mode,\n kind: \"model\" as const,\n model: this.#modelName,\n operation: String(this.#options.originalOperation),\n get input() {\n input ??= snapshotQueryInput(preparedInput);\n return input;\n },\n ...(values === undefined ? {} : { values }),\n call: this.#inputPreparation,\n });\n }\n\n #getPromise(): Promise<T> {\n return this.#execution.executeDefault(() => {\n const observation = this.#engine.extensionChain?.observation;\n if (observation === undefined) {\n return this.#finished(this.#runExecution());\n }\n return observation.run(this.#unit(true), () =>\n this.#finished(this.#runExecution())\n );\n });\n }\n\n /** The value its caller receives: the client's last step applied, if any. */\n #finished(value: Promise<T>): Promise<T> {\n const finish = this.#options.finishResult;\n return finish ? value.then((result) => finish(result) as T) : value;\n }\n\n /**\n * This operation's `operation` unit. Its certainty is the operation's own,\n * except for an array member, whose array reports it.\n */\n #unit(certain?: true): UnitSource {\n return {\n kind: \"operation\",\n operation: String(this.#options.originalOperation),\n model: this.#modelName,\n context: this.#context.attribution,\n driver: this.#engine.driver,\n table: this.#model[\"~\"].names.sql ?? this.#modelName,\n ...(certain ? { certainty: () => this.#observationCommitCertainty } : {}),\n };\n }\n\n #runExecution(\n driverOverride?: AnyDriver,\n committedWriteSegment?: CommittedWriteSegmentNotification,\n writeMayBeVisible?: WriteMayBeVisibleNotification\n ): Promise<T> {\n return withOperationErrorContext(this.#context.attribution, () =>\n this.#runAttributedExecution(\n driverOverride,\n committedWriteSegment,\n writeMayBeVisible\n )\n );\n }\n\n #runAttributedExecution(\n driverOverride?: AnyDriver,\n committedWriteSegment?: CommittedWriteSegmentNotification,\n writeMayBeVisible?: WriteMayBeVisibleNotification\n ): Promise<T> {\n const observerCommitted = this.#observationNotification(\"committed\");\n const observerMayHaveCommitted =\n this.#observationNotification(\"may-have-committed\");\n const requestedOperation = String(this.#options.originalOperation);\n const handlers = this.#engine.extensionChain?.around?.handlers(\n this.#modelName,\n requestedOperation\n );\n if (\n (handlers === undefined || handlers.length === 0) &&\n this.#prepareWriteOutcomeRegistration === undefined\n ) {\n return this.#runCoreExecution(\n driverOverride,\n combineWriteNotifications(committedWriteSegment, observerCommitted),\n combineWriteNotifications(writeMayBeVisible, observerMayHaveCommitted)\n );\n }\n return this.#runExtendedExecution(\n handlers,\n requestedOperation,\n observerCommitted,\n observerMayHaveCommitted,\n driverOverride,\n committedWriteSegment,\n writeMayBeVisible\n );\n }\n\n /** Query extensions and write-outcome registration, out of line. */\n #runExtendedExecution(\n handlers: AroundHandlers | undefined,\n requestedOperation: string,\n observerCommitted: (() => Promise<void>) | undefined,\n observerMayHaveCommitted: (() => Promise<void>) | undefined,\n driverOverride?: AnyDriver,\n committedWriteSegment?: CommittedWriteSegmentNotification,\n writeMayBeVisible?: WriteMayBeVisibleNotification\n ): Promise<T> {\n let preparedInput: Record<string, unknown>;\n try {\n preparedInput = this.#preparedInput();\n } catch (error) {\n return Promise.reject(error);\n }\n const writeOutcomeRegistration = this.#resolveWriteOutcomeRegistration();\n const coordination = this.#engine.extensionChain?.coordination;\n if (\n coordination === undefined ||\n ((handlers === undefined || handlers.length === 0) &&\n writeOutcomeRegistration === undefined)\n ) {\n return this.#runCoreExecution(\n driverOverride,\n combineWriteNotifications(committedWriteSegment, observerCommitted),\n combineWriteNotifications(writeMayBeVisible, observerMayHaveCommitted)\n );\n }\n const context =\n handlers === undefined || handlers.length === 0\n ? undefined\n : this.#queryContext(\n this.#engine.transaction ? \"transaction\" : \"direct\",\n preparedInput\n );\n // Handlers come with `around` and a registration with the part that\n // watches writes: each coordinates with what runs them.\n return coordination.executePreparedQuery!<T, Record<string, unknown>>(\n context,\n handlers,\n (notifications, driver) =>\n this.#runCoreExecution(\n driver ?? driverOverride,\n combineWriteNotifications(\n committedWriteSegment,\n combineWriteNotifications(\n notifications?.committed,\n observerCommitted\n )\n ),\n combineWriteNotifications(\n writeMayBeVisible,\n combineWriteNotifications(\n notifications?.mayHaveCommitted,\n observerMayHaveCommitted\n )\n )\n ),\n !isReadOperation(requestedOperation),\n this.#engine.transaction,\n undefined,\n writeOutcomeRegistration\n );\n }\n\n #observationNotification(\n certainty: \"committed\" | \"may-have-committed\"\n ): (() => Promise<void>) | undefined {\n if (\n this.#engine.transaction !== undefined ||\n this.#engine.extensionChain?.observation === undefined\n ) {\n return undefined;\n }\n return async () => {\n if (\n certainty === \"committed\" ||\n this.#observationCommitCertainty === undefined\n ) {\n this.#observationCommitCertainty = certainty;\n }\n };\n }\n\n #runCoreExecution(\n driverOverride?: AnyDriver,\n committedWriteSegment?: CommittedWriteSegmentNotification,\n writeMayBeVisible?: WriteMayBeVisibleNotification\n ): Promise<T> {\n return this.#run(driverOverride, committedWriteSegment, writeMayBeVisible);\n }\n\n /**\n * Run this operation through the route. The driver an existing transaction or\n * array owner supplied stays exactly the driver it supplied; this owner opens\n * and closes no scope of its own, and retries nothing here. The engine's four\n * bounded recoveries live inside the route (`raptor3/AGENTS.md`, \"Which\n * recovery REPLAYS and which RE-PLANS\"); one of them reads `meta.raceable`\n * off the failure to decide whether a premise may be answered by a second\n * attempt.\n */\n #run(\n driverOverride?: AnyDriver,\n committedWriteSegment?: CommittedWriteSegmentNotification,\n writeMayBeVisible?: WriteMayBeVisibleNotification\n ): Promise<T> {\n let routed: PreparedOperation;\n try {\n routed = this.#resolveRouted();\n } catch (error) {\n return Promise.reject(error);\n }\n const run = () =>\n routed.run({\n committedWriteSegment,\n context: this.#context.attribution,\n driverOverride,\n engineDriver: this.#engine.driver,\n isWrite: !isReadOperation(String(this.#options.originalOperation)),\n writeMayBeVisible,\n }) as Promise<T>;\n // Below every per-call lifecycle step, outside any borrowed scope: a\n // `findUnique` may share one read with the calls of the same tick.\n // A read whose rows are kept (`codec`) is sent alone: a shared read's\n // rows are not its own.\n if (\n this.#operation === \"findUnique\" &&\n driverOverride === undefined &&\n routed.seen === undefined\n ) {\n const batched = batchFindUnique({\n engine: this.#engine,\n model: this.#model,\n requested: String(this.#options.originalOperation),\n args: this.#resolveArgs(),\n values: this.#inputPreparation?.values,\n rows: () => this.#callRows(),\n routed,\n context: this.#context.attribution,\n run,\n });\n if (batched !== undefined) return batched as Promise<T>;\n }\n return run();\n }\n\n getArgs(): Record<string, unknown> {\n return this.#args;\n }\n\n /**\n * The one SQL statement this operation compiles to, or `undefined` when it\n * does not compile to exactly one (backs {@link QueryEngine.build}).\n *\n * Every read compiles to one statement and publishes it, from the prepared\n * read the execution itself runs — there is no second lowering here. A write\n * answers `undefined`: the engine's only write fold is the asynchronous\n * `prepareBatch()`, which publishes driver-prepared queries rather than an\n * `Sql`, and this accessor is synchronous.\n */\n buildStatement(): Sql | undefined {\n return this.#resolveRouted().read?.statement;\n }\n\n then<TResult1 = T, TResult2 = never>(\n onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null\n ): Promise<TResult1 | TResult2> {\n return this.#getPromise().then(onfulfilled, onrejected);\n }\n\n catch<TResult = never>(\n onrejected?: ((reason: unknown) => TResult | PromiseLike<TResult>) | null\n ): Promise<T | TResult> {\n return this.#getPromise().catch(onrejected);\n }\n\n finally(onfinally?: (() => void) | null): Promise<T> {\n return this.#getPromise().finally(onfinally);\n }\n}\n\n/** Create one genuine operation without exposing its construction identity. */\nexport function createPendingOperation<T>(\n engine: QueryEngine,\n model: AnyModel,\n operation: Operation | `${Operation}OrThrow`,\n args: Record<string, unknown>,\n options?: PrepareOptions,\n prepareInput?: PrepareOperationInput,\n prepareWriteOutcomeRegistration?: PrepareWriteOutcomeRegistration\n): PendingOperation<T> {\n return createPendingOperationFriend(\n engine,\n model,\n operation,\n args,\n options,\n prepareInput,\n prepareWriteOutcomeRegistration\n );\n}\n\nexport function isPendingOperation<T = unknown>(\n value: unknown\n): value is PendingOperation<T> {\n return (\n value !== null &&\n typeof value === \"object\" &&\n PENDING_OPERATION_SYMBOL in value &&\n (value as Record<symbol, unknown>)[PENDING_OPERATION_SYMBOL] === true\n );\n}\n\nexport type UnwrapPendingOperation<T> =\n T extends PendingOperation<infer U> ? U : T;\n\nexport type UnwrapPendingOperations<\n T extends readonly PendingOperation<unknown>[],\n> = {\n [K in keyof T]: UnwrapPendingOperation<T[K]>;\n};\n"],"mappings":"6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A,IAAM,EAAU,gBAAgB,CAC9B,OAAQ,MAAA,EACR,MAAO,MAAA,EACP,UAAW,OAAO,MAAA,EAAc,kBAAkB,CAClD,KAAM,MAAA,GAAmB,CACzB,OAAQ,MAAA,GAAwB,OAChC,SAAY,MAAA,GAAgB,CAC5B,SACA,QAAS,MAAA,EAAc,YACvB,IACD,CAAC,CACF,GAAI,IAAY,IAAA,GAAW,OAAO,EAEpC,OAAO,KAAK,CAGd,SAAmC,CACjC,OAAO,MAAA,EAaT,gBAAkC,CAChC,OAAO,MAAA,GAAqB,CAAC,MAAM,UAGrC,KACE,EACA,EAC8B,CAC9B,OAAO,MAAA,GAAkB,CAAC,KAAK,EAAa,EAAW,CAGzD,MACE,EACsB,CACtB,OAAO,MAAA,GAAkB,CAAC,MAAM,EAAW,CAG7C,QAAQ,EAA6C,CACnD,OAAO,MAAA,GAAkB,CAAC,QAAQ,EAAU,GAKhD,SAAgB,uBACd,EACA,EACA,EACA,EACA,EACA,EACA,EACqB,CACrB,OAAO,6BACL,EACA,EACA,EACA,EACA,EACA,EACA,EACD,CAGH,SAAgB,mBACd,EAC8B,CAC9B,OAEE,OAAO,GAAU,YADjB,GAEA,KAA4B,GAC3B,EAAkC,KAA8B"}
@@ -1,2 +0,0 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{ct as t,i as n,o as r,r as i,t as a,ut as o}from"./native-types-DgjMUikz.mjs";const s=new WeakMap;function idDomainOfState(e){return e?.array===!0?void 0:idMemberDomainOfState(e)}function idMemberDomainOfState(e){if(e===void 0||e.type!==`string`)return;let t=s.get(e);if(t)return t;let n=e.autoGenerate;if(n===void 0||!o(n.kind)||n.implicit===!0)return;let r={format:n.kind,prefix:n.prefix,length:n.length};return s.set(e,r),r}const c=/^(?:text|citext|varchar\(\d+\))$/,l=/^(?:TINYTEXT|TEXT|MEDIUMTEXT|LONGTEXT|VARCHAR\(\d+\)|CHAR\(\d+\))$/,u=/^TEXT$/,d=/^(?:BINARY|VARBINARY)\((\d+)\)$/;function defaultIdStorage(e,r){let o=t(e);if(o===void 0)switch(r){case`pg`:return{representation:`text`,columnType:i.STRING.TEXT.type};case`mysql`:return{representation:`text`,columnType:`TEXT`};default:return{representation:`text`,columnType:n.STRING.TEXT.type}}switch(r){case`pg`:return e===`uuid`||e===`uuidv7`?{representation:`uuid`,columnType:i.STRING.UUID.type}:{representation:`bytes`,columnType:i.BLOB.BYTEA.type};case`mysql`:return{representation:`bytes`,columnType:a.BLOB.BINARY(o).type};default:return{representation:`bytes`,columnType:n.BLOB.BLOB.type}}}function isTextColumnType(e,t){switch(t){case`pg`:return c.test(e);case`mysql`:return l.test(e);default:return u.test(e)}}function binaryRepresentation(e,r,o){let s=t(r);if(s===void 0)return;if(o===`pg`)return e===i.BLOB.BYTEA.type?`bytes`:e===i.STRING.UUID.type&&(r===`uuid`||r===`uuidv7`)?`uuid`:void 0;if(o===`sqlite`)return e===n.BLOB.BLOB.type?`bytes`:void 0;if(e===a.BLOB.BLOB.type)return`bytes`;let c=d.exec(e);return c&&Number(c[1])===s?`bytes`:void 0}function idStorageOf(e,t,n){let i=r(t,n);if(i===void 0)return defaultIdStorage(e.format,n);let a=i.type;if(isTextColumnType(a,n))return{representation:`text`,columnType:a};let o=binaryRepresentation(a,e.format,n);return o===void 0?void 0:{representation:o,columnType:a}}function describeIdNativeTypes(e,n){let r=t(e),i=n===`pg`?`text, citext, varchar(n)`:n===`mysql`?`TEXT, TINYTEXT, MEDIUMTEXT, LONGTEXT, VARCHAR(n), CHAR(n)`:`TEXT`;return r===void 0?i:`${n===`pg`?e===`uuid`||e===`uuidv7`?`uuid, bytea`:`bytea`:n===`mysql`?`BINARY(${r}), VARBINARY(${r}), BLOB`:`BLOB`}, ${i}`}function sqliteDateTimePhysicalForm(e){let t=r(e,`sqlite`);return t===void 0?`text`:t.type===`INTEGER`?`epochMillis`:t.type===`REAL`?`julianDay`:`text`}export{idStorageOf as a,idMemberDomainOfState as i,describeIdNativeTypes as n,idDomainOfState as r,sqliteDateTimePhysicalForm as t};
2
- //# sourceMappingURL=physical-CeE2nYmI.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"physical-CeE2nYmI.mjs","names":[],"sources":["../src/schema/scalars/string/id-domain.ts","../src/schema/scalars/datetime/physical.ts"],"sourcesContent":["/**\n * Where a DECLARED identifier domain is read from, and how it becomes a column.\n *\n * There is no second declaration: `ScalarState.autoGenerate` — the same record\n * `.uuid()`, `.ulid()`, `.ksuid()`, `.nanoid()` and `.cuid()` already write —\n * IS the domain. This module only projects it into the shape the codec takes,\n * and answers the one storage question the projection cannot: which physical\n * representation and which column spelling this domain has on a given dialect,\n * with a native type override taken into account.\n *\n * Storage lives HERE rather than in the codec because it is the only part of\n * the identifier language that speaks a dialect's vocabulary. The codec below\n * it stays pure — it takes a representation, never a provider — so the\n * validation schemas, which run long before any adapter exists, can use it.\n */\n\nimport {\n type IdDomain,\n type IdFormat,\n type IdRepresentation,\n idByteLength,\n isIdFormat,\n} from \"@validation/primitives/id-codec\";\nimport type { AutoGenerate, ScalarState } from \"../common\";\nimport {\n MYSQL,\n type NativeDialect,\n type NativeTypeDeclaration,\n nativeTypeFor,\n PG,\n SQLITE,\n} from \"../native-types\";\n\n// =============================================================================\n// THE DECLARED DOMAIN\n// =============================================================================\n\nconst DOMAINS = new WeakMap<ScalarState, IdDomain>();\n\n/**\n * The identifier domain a scalar state declares, or `undefined`.\n *\n * Only a NAMED format declares one. `.id()` installs a ULID generator without\n * naming a format (see {@link AutoGenerate.implicit}), so a `.id()` key has no\n * domain: nothing admits its values and nothing narrows its storage.\n *\n * A LIST answers `undefined` deliberately, exactly as the decimal descriptor\n * lookup does: physical parameter encoding, projection, decode and DDL must\n * not bind a whole container as one compact identifier. List admission reads\n * the same declaration through idMemberDomainOfState instead.\n *\n * The projection is memoized per state so the hot write path compares and\n * encodes against one object instead of allocating a domain per value.\n */\nexport function idDomainOfState(\n state: ScalarState | undefined\n): IdDomain | undefined {\n return state?.array === true ? undefined : idMemberDomainOfState(state);\n}\n\n/** The named member domain, also used by lists with plain string storage. */\nexport function idMemberDomainOfState(\n state: ScalarState | undefined\n): IdDomain | undefined {\n if (state === undefined || state.type !== \"string\") return undefined;\n const existing = DOMAINS.get(state);\n if (existing) return existing;\n const generate = state.autoGenerate;\n if (generate === undefined || !isIdFormat(generate.kind)) return undefined;\n // A format the caller did not NAME is not a domain the caller asserted:\n // `.id()` declares a key and carries a generator for convenience, and its\n // values stay whatever a string column holds. `.ulid().id()` names the\n // format and gets the domain, the admission and the compact column.\n if (generate.implicit === true) return undefined;\n const domain: IdDomain = {\n format: generate.kind,\n prefix: generate.prefix,\n length: generate.length,\n };\n DOMAINS.set(state, domain);\n return domain;\n}\n\n// =============================================================================\n// PHYSICAL STORAGE\n// =============================================================================\n\n/** The three dialects a column spelling is asked for. */\nexport type IdDialect = NativeDialect;\n\n/** What one domain is physically, on one dialect. */\nexport interface IdStorage {\n readonly representation: IdRepresentation;\n /** The column type this dialect spells it with. */\n readonly columnType: string;\n}\n\n// `char(n)` is absent deliberately. PostgreSQL BLANK-PADS `character(n)` to its\n// full width, so a 36-character uuid in a `char(40)` column reads back with four\n// trailing spaces and no value of the domain is ever returned — the column is\n// unusable from the moment it is created, for every n wider than the format's\n// own public spelling. MySQL's `CHAR(n)` pads on the way in and STRIPS on the\n// way out, so it keeps its place in that dialect's list.\nconst PG_TEXT_FAMILY = /^(?:text|citext|varchar\\(\\d+\\))$/;\nconst MYSQL_TEXT_FAMILY =\n /^(?:TINYTEXT|TEXT|MEDIUMTEXT|LONGTEXT|VARCHAR\\(\\d+\\)|CHAR\\(\\d+\\))$/;\nconst SQLITE_TEXT_FAMILY = /^TEXT$/;\nconst MYSQL_SIZED_BINARY = /^(?:BINARY|VARBINARY)\\((\\d+)\\)$/;\n\n/** The default column spelling and representation, before any override. */\nfunction defaultIdStorage(format: IdFormat, dialect: IdDialect): IdStorage {\n const width = idByteLength(format);\n if (width === undefined) {\n // `nanoid` and `cuid` keep the text column the dialect already gave them.\n switch (dialect) {\n case \"pg\":\n return { representation: \"text\", columnType: PG.STRING.TEXT.type };\n case \"mysql\":\n return { representation: \"text\", columnType: \"TEXT\" };\n default:\n return {\n representation: \"text\",\n columnType: SQLITE.STRING.TEXT.type,\n };\n }\n }\n switch (dialect) {\n case \"pg\":\n // A UUID gets PostgreSQL's own 16-byte type, which the wire spells as\n // canonical text. A ULID is never spelled `uuid`: its bytes are not a\n // UUID's and a database that formatted them as one would publish a\n // version nibble the value does not have.\n return format === \"uuid\" || format === \"uuidv7\"\n ? { representation: \"uuid\", columnType: PG.STRING.UUID.type }\n : { representation: \"bytes\", columnType: PG.BLOB.BYTEA.type };\n case \"mysql\":\n return {\n representation: \"bytes\",\n columnType: MYSQL.BLOB.BINARY(width).type,\n };\n default:\n return { representation: \"bytes\", columnType: SQLITE.BLOB.BLOB.type };\n }\n}\n\n/** Whether this dialect spells `type` as one of its text column types. */\nfunction isTextColumnType(type: string, dialect: IdDialect): boolean {\n switch (dialect) {\n case \"pg\":\n return PG_TEXT_FAMILY.test(type);\n case \"mysql\":\n return MYSQL_TEXT_FAMILY.test(type);\n default:\n return SQLITE_TEXT_FAMILY.test(type);\n }\n}\n\n/**\n * The representation a BINARY-family override names for this format, or\n * `undefined` when the override is not a binary column this domain fits.\n *\n * A sized MySQL column must be the format's exact width: `BINARY(16)` holds a\n * KSUID's first sixteen bytes and pads a ULID that was never short, and both\n * are silent corruptions rather than storage choices. `bytea` and `BLOB` carry\n * no declared width, so the codec's exact-width encoding is the only promise\n * they need.\n */\nfunction binaryRepresentation(\n type: string,\n format: IdFormat,\n dialect: IdDialect\n): IdRepresentation | undefined {\n const width = idByteLength(format);\n if (width === undefined) return undefined;\n if (dialect === \"pg\") {\n if (type === PG.BLOB.BYTEA.type) return \"bytes\";\n return type === PG.STRING.UUID.type &&\n (format === \"uuid\" || format === \"uuidv7\")\n ? \"uuid\"\n : undefined;\n }\n if (dialect === \"sqlite\") {\n return type === SQLITE.BLOB.BLOB.type ? \"bytes\" : undefined;\n }\n if (type === MYSQL.BLOB.BLOB.type) return \"bytes\";\n const sized = MYSQL_SIZED_BINARY.exec(type);\n return sized && Number(sized[1]) === width ? \"bytes\" : undefined;\n}\n\n/**\n * The column spelling and representation of one domain on one dialect.\n *\n * The ONE owner of that decision: the migration type mapping, the parameter\n * encoding, the read projection and the result decode all derive from this, so\n * a column cannot be created as one thing and written as another.\n *\n * The declaration is resolved for THIS dialect (`nativeTypeFor`): a tagged\n * native type for another dialect, or a map without this dialect's entry, is\n * not this dialect's column and is ignored exactly as every other scalar's\n * mapping ignores it. An override that IS this\n * dialect's and that this domain cannot live in returns `undefined` — the\n * schema boundary refuses it by name long before a query is built, and this\n * answering `undefined` rather than guessing is what keeps that refusal the\n * only place the question is decided.\n */\nexport function idStorageOf(\n domain: IdDomain,\n declaration: NativeTypeDeclaration | undefined,\n dialect: IdDialect\n): IdStorage | undefined {\n const nativeType = nativeTypeFor(declaration, dialect);\n if (nativeType === undefined) {\n return defaultIdStorage(domain.format, dialect);\n }\n const type = nativeType.type;\n if (isTextColumnType(type, dialect)) {\n // The opt-out for a column that already holds text: the domain is still\n // admitted and normalized, only its storage stays as it was.\n return { representation: \"text\", columnType: type };\n }\n const representation = binaryRepresentation(type, domain.format, dialect);\n return representation === undefined\n ? undefined\n : { representation, columnType: type };\n}\n\n/** The overrides this domain accepts on this dialect, for a refusal message. */\nexport function describeIdNativeTypes(\n format: IdFormat,\n dialect: IdDialect\n): string {\n const width = idByteLength(format);\n const text =\n dialect === \"pg\"\n ? \"text, citext, varchar(n)\"\n : dialect === \"mysql\"\n ? \"TEXT, TINYTEXT, MEDIUMTEXT, LONGTEXT, VARCHAR(n), CHAR(n)\"\n : \"TEXT\";\n if (width === undefined) return text;\n const binary =\n dialect === \"pg\"\n ? format === \"uuid\" || format === \"uuidv7\"\n ? \"uuid, bytea\"\n : \"bytea\"\n : dialect === \"mysql\"\n ? `BINARY(${width}), VARBINARY(${width}), BLOB`\n : \"BLOB\";\n return `${binary}, ${text}`;\n}\n","import type { DateTimePhysicalForm } from \"@validation/primitives/datetime-physical-codec\";\nimport { type NativeTypeDeclaration, nativeTypeFor } from \"../native-types\";\n\n/**\n * The physical vocabulary SQLite assigns to one DateTime native declaration.\n *\n * A missing declaration, a declaration that selects nothing on SQLite, and\n * explicit TEXT all use SQLite's default timestamp text. INTEGER is epoch milliseconds and\n * REAL is a Julian day. Schema validation, query lowering, result parsing, and\n * migration defaults consume this same interpretation.\n */\nexport function sqliteDateTimePhysicalForm(\n declaration: NativeTypeDeclaration | undefined\n): DateTimePhysicalForm {\n const nativeType = nativeTypeFor(declaration, \"sqlite\");\n if (nativeType === undefined) return \"text\";\n if (nativeType.type === \"INTEGER\") return \"epochMillis\";\n return nativeType.type === \"REAL\" ? \"julianDay\" : \"text\";\n}\n"],"mappings":"8HAqCA,MAAM,EAAU,IAAI,QAiBpB,SAAgB,gBACd,EACsB,CACtB,OAAO,GAAO,QAAU,GAAO,IAAA,GAAY,sBAAsB,EAAM,CAIzE,SAAgB,sBACd,EACsB,CACtB,GAAI,IAAU,IAAA,IAAa,EAAM,OAAS,SAAU,OACpD,IAAM,EAAW,EAAQ,IAAI,EAAM,CACnC,GAAI,EAAU,OAAO,EACrB,IAAM,EAAW,EAAM,aAMvB,GALI,IAAa,IAAA,IAAa,CAAC,EAAW,EAAS,KAAK,EAKpD,EAAS,WAAa,GAAM,OAChC,IAAM,EAAmB,CACvB,OAAQ,EAAS,KACjB,OAAQ,EAAS,OACjB,OAAQ,EAAS,OAClB,CAED,OADA,EAAQ,IAAI,EAAO,EAAO,CACnB,EAuBT,MAAM,EAAiB,mCACjB,EACJ,qEACI,EAAqB,SACrB,EAAqB,kCAG3B,SAAS,iBAAiB,EAAkB,EAA+B,CACzE,IAAM,EAAQ,EAAa,EAAO,CAClC,GAAI,IAAU,IAAA,GAEZ,OAAQ,EAAR,CACE,IAAK,KACH,MAAO,CAAE,eAAgB,OAAQ,WAAY,EAAG,OAAO,KAAK,KA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AW,KACxB,GAAI,iBAAiB,EAAM,EAAQ,CAGjC,MAAO,CAAE,eAAgB,OAAQ,WAAY,EAAM,CAErD,IAAM,EAAiB,qBAAqB,EAAM,EAAO,OAAQ,EAAQ,CACzE,OAAO,IAAmB,IAAA,GACtB,IAAA,GACA,CAAE,iBAAgB,WAAY,EAAM,CAI1C,SAAgB,sBACd,EACA,EACQ,CACR,IAAM,EAAQ,EAAa,EAAO,CAC5B,EACJ,IAAY,KACR,2BACA,IAAY,QACV,4DACA,OAUR,OATI,IAAU,IAAA,GAAkB,EASzB,GAPL,IAAY,KACR,IAAW,QAAU,IAAW,SAC9B,cACA,QACF,IAAY,QACV,UAAU,EAAM,eAAe,EAAM,SACrC,OACS,IAAI,IC5OvB,SAAgB,2BACd,EACsB,CACtB,IAAM,EAAa,EAAc,EAAa,SAAS,CAGvD,OAFI,IAAe,IAAA,GAAkB,OACjC,EAAW,OAAS,UAAkB,cACnC,EAAW,OAAS,OAAS,YAAc"}
@@ -1,2 +0,0 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t,y as n}from"./base-z-cH5ZBI.mjs";import{i as r}from"./validation--qS7OPmg.mjs";import{n as i}from"./suppressed-failure-CQkQsMVS.mjs";import{t as a}from"./settle-1cy5x_52.mjs";const o=`SELECT pg_advisory_unlock_all()`,s=`could not prove the advisory-lock state of a discarded migration session: its "${o}" reset failed.`,c=5e3;function unprovenLockStateError(e,t,r){return abandonedSessionError(e,s,t,n(r))}function abandonedSessionError(e,n,i,a){return new r(`Driver "${e}" ${n} ${i}`,{code:t.CONNECTION_CLOSED,cause:a,meta:{driver:e,operation:`pinnedSession`}})}function condemnedSessionError(e){return new r(`Driver "${e}" will pin no further migration session: an earlier session's "${o}" reset failed, so the advisory-lock state of its one client is unknown. That client was not closed — it is the caller's database, not a pooled connection VibORM may discard — and ordinary queries on it are unaffected.`,{code:t.CONNECTION_CLOSED,meta:{driver:e,operation:`pinnedSession`}})}const l=`The reserved connection was abandoned rather than returned to the pool. VibORM did not close the transport, which belongs to the caller, so the lock is freed when that connection is.`;async function releaseReservedPostgresSession(e){if(e.lost===!0){let{closeOwnedTransport:t,driverName:n}=e;if(t===void 0)throw abandonedSessionError(n,`lost the connection of a reserved migration session and sent nothing more on it.`,l,void 0);t().catch(()=>void 0);return}if(!e.discard){e.release();return}try{await a(e.reset(),c,()=>Error(`The advisory-lock reset went unanswered for ${c} ms.`))}catch(t){await abandon(e,s,t)}e.release()}async function abandon(e,t,r){let{closeOwnedTransport:a,driverName:o}=e;if(a===void 0)throw abandonedSessionError(o,t,l,n(r));try{await a()}catch(e){throw i(abandonedSessionError(o,t,`The reserved connection was abandoned rather than returned to the pool, and ending the transport VibORM created for it FAILED: that backend may still be running, and any advisory lock it holds is freed only when it goes away. VibORM withdrew that transport and will not use it again.`,n(r)),e)}throw abandonedSessionError(o,t,`The reserved connection was abandoned rather than returned to the pool, and the transport VibORM created for it was closed — which ends that backend, and with it every advisory lock it held.`,n(r))}const u=new WeakMap;function refuseCondemnedSession(e,t){if(t.condemned)throw condemnedSessionError(e)}function leasePinnedCommand(e,t,n){let r=physicalSessionState(t);refuseCondemnedSession(e,r);let i=r.queued.then(()=>(refuseCondemnedSession(e,r),n()));return r.queued=i.then(()=>void 0,()=>void 0),i}function condemnPhysicalSession(e){physicalSessionState(e).condemned=!0}function physicalSessionState(e){let t=u.get(e);if(t)return t;let n={queued:Promise.resolve(),condemned:!1};return u.set(e,n),n}export{unprovenLockStateError as a,releaseReservedPostgresSession as i,condemnPhysicalSession as n,leasePinnedCommand as r,c as t};
2
- //# sourceMappingURL=pinned-session-DCoAZDOz.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"pinned-session-DCoAZDOz.mjs","names":[],"sources":["../src/drivers/shared/pinned-session.ts"],"sourcesContent":["import { ConnectionError, VibORMErrorCode } from \"@errors\";\nimport { errorCause } from \"../../errors/diagnostic-safety\";\nimport { settleWithin } from \"./settle\";\nimport { withSuppressedFailure } from \"./suppressed-failure\";\n\n/** The PostgreSQL statement that resets a session's advisory-lock state. */\nconst ADVISORY_RESET = \"SELECT pg_advisory_unlock_all()\";\n\n/** Why a reserved session is abandoned, in the refusal's own words. */\nconst LOST_SESSION =\n \"lost the connection of a reserved migration session and sent nothing more on it.\";\nconst ADVISORY_RESET_FAILED = `could not prove the advisory-lock state of a discarded migration session: its \"${ADVISORY_RESET}\" reset failed.`;\n\n/**\n * How long one cleanup statement — `ROLLBACK`, the unlock, the limits reset,\n * the advisory reset — may take before its session is treated as lost.\n *\n * A healthy server answers each of them in milliseconds. A session that does\n * not answer one within this bound is a half-open socket or a dying backend,\n * and waiting on it longer only keeps the caller from the failure it already\n * has (plan S2: \"bound every cleanup statement\").\n */\nexport const CLEANUP_BOUND_MS = 5000;\n\n/**\n * One reserved physical session, as a provider hands it back.\n *\n * The plan's requirement (§3.5) is \"one physical producer across decisions and\n * commit boundaries\": a session lock is session-scoped, so acquiring it through\n * one pooled connection and running the protected work through another protects\n * nothing and can strand the lock. A reservation is therefore a connection the\n * provider has taken OUT of its pool, plus the exact way to give it back.\n */\nexport interface PinnedSessionReservation<TSession> {\n /** The reserved producer. Every statement of the session runs on it. */\n readonly session: TSession;\n /**\n * The failure the provider itself saw end this session's connection, or\n * `undefined` while it has seen none.\n *\n * Only a provider that observes its connection has one (`pg`, through the\n * client's `error` event). Elsewhere a lost connection is recognized by the\n * failure that reported it.\n */\n readonly lost?: () => unknown;\n /**\n * Returns the producer to the provider.\n *\n * `discard` is true when the session's state is unknown — a failed unlock, a\n * failed cleanup, or a thrown body — and the provider must then destroy the\n * connection rather than hand a session carrying unknown state back to a\n * pool. A provider whose session can never be made clean again (MySQL2, which\n * has executed `USE` and possibly author-owned statements) destroys\n * unconditionally and ignores the flag.\n *\n * `lost` is true when the connection itself is gone or stopped answering:\n * the provider must send nothing more on it — not even the reset a discard\n * otherwise runs — and abandon or destroy it.\n */\n release(discard: boolean, lost?: boolean): Promise<void>;\n}\n\n/**\n * The handle the pinned body uses to condemn its own producer.\n *\n * A thrown body already condemns the session. This exists for the case that\n * does not throw: an unlock statement that RETURNS a result proving the lock\n * was not released. That session is still usable in the provider's eyes and\n * would be returned to the pool holding a lock nobody owns.\n */\nexport interface PinnedSessionControl {\n /** Condemn this producer; it will be destroyed instead of released. */\n discard(): void;\n /**\n * Whether this session's connection is gone: the provider saw it end,\n * `failure` reports it, or a cleanup statement went unanswered. Once true it\n * stays true, and nothing more is sent on the session (plan S2).\n */\n lost(failure?: unknown): boolean;\n /** Runs one cleanup statement within `CLEANUP_BOUND_MS`; past it, the session is lost. */\n cleanup<T>(run: () => Promise<T>): Promise<T>;\n}\n\n/**\n * The refusal a discarded session whose reset FAILED raises.\n *\n * A session is discarded because its state is unknown, and the reset is what\n * makes it known again. When the reset fails too, the session may still hold\n * the migration lock every other command is excluded by — so it must not go\n * back to the provider, and saying nothing about that is not an option either:\n * a swallowed cleanup failure is how a pool ends up serving a connection that\n * blocks the next migration forever.\n *\n * The reset's own failure is the evidence, and it is the PROVIDER's value: it\n * goes through the one total normalizer rather than a bare `instanceof`, which\n * a rejection whose `getPrototypeOf` trap throws turns into a throw inside this\n * constructor — replacing the whole typed refusal with the trap's error.\n */\nexport function unprovenLockStateError(\n driverName: string,\n containment: string,\n cause: unknown\n): ConnectionError {\n return abandonedSessionError(\n driverName,\n ADVISORY_RESET_FAILED,\n containment,\n errorCause(cause)\n );\n}\n\nfunction abandonedSessionError(\n driverName: string,\n reason: string,\n containment: string,\n cause: Error | undefined\n): ConnectionError {\n return new ConnectionError(\n `Driver \"${driverName}\" ${reason} ${containment}`,\n {\n code: VibORMErrorCode.CONNECTION_CLOSED,\n cause,\n meta: { driver: driverName, operation: \"pinnedSession\" },\n }\n );\n}\n\n/**\n * The refusal raised afterwards by EVERY driver whose one client was condemned.\n *\n * A transport that pools connections recovers by reserving a different one, so\n * this is only for the driver whose single client IS the session: there is no\n * other connection to reach for, and running the next migration command on a\n * session that may still hold the lock is precisely what the condemnation\n * exists to prevent. Two drivers over that one client are two callers of this\n * same refusal, because the session they would both pin is the same session.\n */\nexport function condemnedSessionError(driverName: string): ConnectionError {\n return new ConnectionError(\n `Driver \"${driverName}\" will pin no further migration session: an earlier session's \"${ADVISORY_RESET}\" reset failed, so the advisory-lock state of its one client is unknown. That client was not closed — it is the caller's database, not a pooled connection VibORM may discard — and ordinary queries on it are unaffected.`,\n {\n code: VibORMErrorCode.CONNECTION_CLOSED,\n meta: { driver: driverName, operation: \"pinnedSession\" },\n }\n );\n}\n\n/**\n * What was actually DONE about the abandoned connection, in the refusal's own\n * words.\n *\n * Three outcomes, three sentences, each chosen once the outcome is known\n * rather than once the ownership is known. A single sentence written before the\n * close was attempted claimed the backend had been ended even when ending it\n * threw — and the one thing a caller does with that claim is stop looking for a\n * connection that is still running, still holding the lock this refusal exists\n * to report.\n */\nconst CALLER_OWNED_CONTAINMENT =\n \"The reserved connection was abandoned rather than returned to the pool. VibORM did not close the transport, which belongs to the caller, so the lock is freed when that connection is.\";\nconst CLOSED_CONTAINMENT =\n \"The reserved connection was abandoned rather than returned to the pool, and the transport VibORM created for it was closed — which ends that backend, and with it every advisory lock it held.\";\nconst CLOSE_FAILED_CONTAINMENT =\n \"The reserved connection was abandoned rather than returned to the pool, and ending the transport VibORM created for it FAILED: that backend may still be running, and any advisory lock it holds is freed only when it goes away. VibORM withdrew that transport and will not use it again.\";\n\n/**\n * Returns a reserved PostgreSQL session to its pool, or condemns it — the ONE\n * rule for every provider that reserves a connection it cannot destroy.\n *\n * postgres.js and Bun SQL both expose `release()` and nothing else: there is no\n * destructive return to reach for, so a session whose reset failed is ABANDONED\n * — never released — which is the only way it stops being a connection the pool\n * will hand to the next caller.\n *\n * Abandoning it leaves the lock held until that backend goes away, so a\n * transport VibORM created is closed too: ending it terminates the backend, and\n * PostgreSQL frees every advisory lock the session held. A transport the CALLER\n * supplied is never closed for this — it is theirs, may be serving their own\n * code, and closing it to tidy up VibORM's cleanup failure would be a far\n * larger effect than the one being contained.\n *\n * A LOST session (plan S2) is abandoned the same way without the reset: its\n * connection is gone or stopped answering, and a statement written to it is,\n * on postgres.js, an uncaught crash from inside the provider's write loop. Its\n * owned transport is closed; a supplied one is reported, since abandoning is\n * all VibORM may do with it.\n */\nexport async function releaseReservedPostgresSession(reservation: {\n readonly driverName: string;\n readonly discard: boolean;\n readonly lost?: boolean | undefined;\n /** Runs `SELECT pg_advisory_unlock_all()` on the reserved session. */\n readonly reset: () => Promise<unknown>;\n /** Hands the reserved session back to the provider's pool. */\n readonly release: () => void;\n /** Closes the transport, or absent when the CALLER owns it. */\n readonly closeOwnedTransport: (() => Promise<void>) | undefined;\n}): Promise<void> {\n if (reservation.lost === true) {\n const { closeOwnedTransport, driverName } = reservation;\n if (closeOwnedTransport === undefined) {\n throw abandonedSessionError(\n driverName,\n LOST_SESSION,\n CALLER_OWNED_CONTAINMENT,\n undefined\n );\n }\n // Not awaited: the connection failure the caller holds is already the\n // answer, and the close lets the transport's other queries finish first\n // (postgres.js waits on the dead connection's unsettled query until its\n // bound). The transport is withdrawn before it closes, and a session the\n // close cannot end is ended by the server's idle limit.\n closeOwnedTransport().catch(() => undefined);\n return;\n }\n if (!reservation.discard) {\n reservation.release();\n return;\n }\n\n try {\n await settleWithin(\n reservation.reset(),\n CLEANUP_BOUND_MS,\n () =>\n new Error(\n `The advisory-lock reset went unanswered for ${CLEANUP_BOUND_MS} ms.`\n )\n );\n } catch (resetFailure) {\n await abandon(reservation, ADVISORY_RESET_FAILED, resetFailure);\n }\n reservation.release();\n}\n\n/**\n * Abandons a reserved session: never released, its owned transport closed,\n * and the refusal that says so thrown. A transport the caller supplied is only\n * abandoned.\n */\nasync function abandon(\n reservation: {\n readonly driverName: string;\n readonly closeOwnedTransport: (() => Promise<void>) | undefined;\n },\n reason: string,\n cause: unknown\n): Promise<void> {\n const { closeOwnedTransport, driverName } = reservation;\n if (closeOwnedTransport === undefined) {\n throw abandonedSessionError(\n driverName,\n reason,\n CALLER_OWNED_CONTAINMENT,\n errorCause(cause)\n );\n }\n try {\n await closeOwnedTransport();\n } catch (closeFailure) {\n // The reason stays primary — it is what the caller acts on — and the\n // close's own failure is cleanup evidence beside it.\n throw withSuppressedFailure(\n abandonedSessionError(\n driverName,\n reason,\n CLOSE_FAILED_CONTAINMENT,\n errorCause(cause)\n ),\n closeFailure\n );\n }\n throw abandonedSessionError(\n driverName,\n reason,\n CLOSED_CONTAINMENT,\n errorCause(cause)\n );\n}\n\n/** What VibORM knows about one PHYSICAL session it pins commands on. */\ninterface PhysicalSessionState {\n /**\n * The pinned commands already queued on this session. It never rejects, so\n * one command's failure cannot poison the queue — the next command runs\n * either way, exactly as it would after a success.\n */\n queued: Promise<void>;\n /**\n * Set when a discarded session's advisory-lock reset failed, and never\n * cleared: nothing that happens later can prove a lock was released.\n */\n condemned: boolean;\n}\n\n/**\n * What is known about each PHYSICAL session, keyed on the session itself.\n *\n * A driver's connection queue serializes the commands of THAT driver. Two\n * drivers built over one supplied client — the documented shape for two\n * schema-scoped estates over one PGlite — own two queues and one session, so\n * the queue arbitrates nothing between them, and a PostgreSQL session advisory\n * lock is REENTRANT: the second command re-acquires the lock the first is\n * holding instead of waiting for it, then reads and writes inside the first\n * command's session. The client is the only thing both drivers agree on, so it\n * is what this is keyed on.\n *\n * The condemnation shares that key because it answers for the same subject: a\n * failed reset leaves the CLIENT's lock state unknown, not the wrapper's. Kept\n * on the driver instead, it was a fact the other wrappers over that client\n * never consulted, and their next command ran inside the session it condemned.\n *\n * Weak by construction: the entry dies with the client, and a client nobody\n * holds keeps nothing alive here.\n */\nconst PHYSICAL_SESSIONS = new WeakMap<object, PhysicalSessionState>();\n\n/**\n * Refuses a command on a session whose advisory-lock state was condemned.\n *\n * One refusal, read at two moments, and each covers what the other cannot. At\n * ADMISSION, so a session condemned before this command arrived refuses now\n * rather than behind a queue whose head may itself be waiting on the very lock\n * nobody can account for. At the FRONT of the queue, because condemnation lands\n * BETWEEN the two: the command ahead of this one is the one whose reset fails,\n * and this one was admitted while that session still looked accountable.\n */\nfunction refuseCondemnedSession(\n driverName: string,\n state: PhysicalSessionState\n): void {\n if (state.condemned) {\n throw condemnedSessionError(driverName);\n }\n}\n\n/**\n * Runs `command` exclusively on this physical session, when it may still be\n * pinned at all.\n *\n * The refusal is here rather than beside it because this is the one path every\n * pinned command over a shared session takes, and it lands before `command` —\n * so no body and no statement of the refused command reaches the client.\n */\nexport function leasePinnedCommand<T>(\n driverName: string,\n session: object,\n command: () => Promise<T>\n): Promise<T> {\n const state = physicalSessionState(session);\n refuseCondemnedSession(driverName, state);\n const next = state.queued.then(() => {\n refuseCondemnedSession(driverName, state);\n return command();\n });\n state.queued = next.then(\n () => undefined,\n () => undefined\n );\n return next;\n}\n\n/**\n * Records that this physical session's advisory-lock state can no longer be\n * accounted for — for every driver that reaches it, not only the one whose\n * reset failed.\n */\nexport function condemnPhysicalSession(session: object): void {\n physicalSessionState(session).condemned = true;\n}\n\n/** This session's state, created on first use and mutated in place after. */\nfunction physicalSessionState(session: object): PhysicalSessionState {\n const existing = PHYSICAL_SESSIONS.get(session);\n if (existing) {\n return existing;\n }\n const created: PhysicalSessionState = {\n queued: Promise.resolve(),\n condemned: false,\n };\n PHYSICAL_SESSIONS.set(session, created);\n return created;\n}\n"],"mappings":"sOAMA,MAAM,EAAiB,kCAKjB,EAAwB,kFAAkF,EAAe,iBAWlH,EAAmB,IA4EhC,SAAgB,uBACd,EACA,EACA,EACiB,CACjB,OAAO,sBACL,EACA,EACA,EACA,EAAW,EAAM,CAClB,CAGH,SAAS,sBACP,EACA,EACA,EACA,EACiB,CACjB,OAAO,IAAI,EACT,WAAW,EAAW,IAAI,EAAO,GAAG,IACpC,CACE,KAAM,EAAgB,kBACtB,QACA,KAAM,CAAE,OAAQ,EAAY,UAAW,gBAAiB,CACzD,CACF,CAaH,SAAgB,sBAAsB,EAAqC,CACzE,OAAO,IAAI,EACT,WAAW,EAAW,iEAAiE,EAAe,4NACtG,CACE,KAAM,EAAgB,kBACtB,KAAM,CAAE,OAAQ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