viborm 1.3.0 → 1.3.2

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 (167) hide show
  1. package/dist/{adapter-namespace-BpMbLKpL.mjs → adapter-namespace-B8XWzCev.mjs} +1 -1
  2. package/dist/{adapter-namespace-BpMbLKpL.mjs.map → adapter-namespace-B8XWzCev.mjs.map} +1 -1
  3. package/dist/adapters.d.mts +1 -1
  4. package/dist/adapters.mjs +1 -1
  5. package/dist/{batch-refs-B4zn-FAu.mjs → batch-refs-DoWlPD2h.mjs} +1 -1
  6. package/dist/{batch-refs-B4zn-FAu.mjs.map → batch-refs-DoWlPD2h.mjs.map} +1 -1
  7. package/dist/{builder-Df24l2Bd.mjs → builder-DhxaVYP2.mjs} +2 -2
  8. package/dist/{builder-Df24l2Bd.mjs.map → builder-DhxaVYP2.mjs.map} +1 -1
  9. package/dist/bun-sql.d.mts +1 -1
  10. package/dist/bun-sql.mjs +1 -1
  11. package/dist/bun-sqlite.d.mts +1 -1
  12. package/dist/bun-sqlite.mjs +1 -1
  13. package/dist/cache/cloudflare-kv.d.mts +1 -1
  14. package/dist/cache/cloudflare-kv.mjs +1 -1
  15. package/dist/cache/memory.d.mts +1 -1
  16. package/dist/cache/memory.mjs +1 -1
  17. package/dist/cache.d.mts +1 -1
  18. package/dist/cache.mjs +1 -1
  19. package/dist/cache.mjs.map +1 -1
  20. package/dist/chain-BjJ_M7EE.mjs +2 -0
  21. package/dist/chain-BjJ_M7EE.mjs.map +1 -0
  22. package/dist/cli.mjs +1 -1
  23. package/dist/client-BCgMXn6N.mjs +2 -0
  24. package/dist/client-BCgMXn6N.mjs.map +1 -0
  25. package/dist/{client-70MrTq1E.d.mts → client-Df81J4oB.d.mts} +1 -1
  26. package/dist/{client-DM1UHfYG.mjs → client-q6ccRgdO.mjs} +2 -2
  27. package/dist/{client-DM1UHfYG.mjs.map → client-q6ccRgdO.mjs.map} +1 -1
  28. package/dist/client.d.mts +1 -1
  29. package/dist/client.mjs +1 -1
  30. package/dist/{clock-C24RcpwO.mjs → clock-YTLtjLFS.mjs} +1 -1
  31. package/dist/{clock-C24RcpwO.mjs.map → clock-YTLtjLFS.mjs.map} +1 -1
  32. package/dist/config.d.mts +1 -1
  33. package/dist/config.mjs +1 -1
  34. package/dist/d1.d.mts +1 -1
  35. package/dist/d1.mjs +1 -1
  36. package/dist/{driver-CPD0Xxw2.mjs → driver-D6_Ik58x.mjs} +2 -2
  37. package/dist/{driver-CPD0Xxw2.mjs.map → driver-D6_Ik58x.mjs.map} +1 -1
  38. package/dist/{driver-B9fIori_.mjs → driver-Ddt147dK.mjs} +2 -2
  39. package/dist/{driver-B9fIori_.mjs.map → driver-Ddt147dK.mjs.map} +1 -1
  40. package/dist/driver.d.mts +1 -1
  41. package/dist/driver.mjs +1 -1
  42. package/dist/every-dpzVDwzu.mjs +2 -0
  43. package/dist/{every-1pKZteeB.mjs.map → every-dpzVDwzu.mjs.map} +1 -1
  44. package/dist/{fs-estate-i8Zlr1OQ.mjs → fs-estate-azK36i9V.mjs} +2 -2
  45. package/dist/{fs-estate-i8Zlr1OQ.mjs.map → fs-estate-azK36i9V.mjs.map} +1 -1
  46. package/dist/{hydration-DsyHNSDS.mjs → hydration-C2uXmJy6.mjs} +2 -2
  47. package/dist/{hydration-DsyHNSDS.mjs.map → hydration-C2uXmJy6.mjs.map} +1 -1
  48. package/dist/{identifier-conversion-DaZ9yNpv.mjs → identifier-conversion-C2pwwFOS.mjs} +2 -2
  49. package/dist/{identifier-conversion-DaZ9yNpv.mjs.map → identifier-conversion-C2pwwFOS.mjs.map} +1 -1
  50. package/dist/identity-Bj2EN6Ss.mjs +2 -0
  51. package/dist/identity-Bj2EN6Ss.mjs.map +1 -0
  52. package/dist/{index-VsM29vYN.d.mts → index-D4O0Twvs.d.mts} +16 -8
  53. package/dist/index.d.mts +1 -1
  54. package/dist/index.mjs +1 -1
  55. package/dist/instrumentation.d.mts +1 -1
  56. package/dist/instrumentation.mjs +1 -1
  57. package/dist/{key-D_kagnFv.mjs → key-B7vuAYPG.mjs} +2 -2
  58. package/dist/{key-D_kagnFv.mjs.map → key-B7vuAYPG.mjs.map} +1 -1
  59. package/dist/{libsql-DFAoHXrI.mjs → libsql-DUO6vHad.mjs} +2 -2
  60. package/dist/{libsql-DFAoHXrI.mjs.map → libsql-DUO6vHad.mjs.map} +1 -1
  61. package/dist/libsql.d.mts +1 -1
  62. package/dist/libsql.mjs +1 -1
  63. package/dist/{memory-GTWgeDNY.mjs → memory-BApsTkt1.mjs} +2 -2
  64. package/dist/{memory-GTWgeDNY.mjs.map → memory-BApsTkt1.mjs.map} +1 -1
  65. package/dist/migrations/mysql.d.mts +4 -4
  66. package/dist/migrations/mysql.mjs +1 -1
  67. package/dist/migrations/postgres.d.mts +4 -4
  68. package/dist/migrations/postgres.mjs +1 -1
  69. package/dist/migrations/sqlite.d.mts +4 -4
  70. package/dist/migrations/sqlite.mjs +1 -1
  71. package/dist/migrations/storage/durable-object.mjs +1 -1
  72. package/dist/migrations/storage/fs.mjs +1 -1
  73. package/dist/migrations/storage/r2.mjs +1 -1
  74. package/dist/migrations/tenant.d.mts +2 -2
  75. package/dist/migrations/tenant.mjs +1 -1
  76. package/dist/migrations.d.mts +4 -4
  77. package/dist/migrations.mjs +1 -1
  78. package/dist/{mysql-xChEivOe.mjs → mysql-D1GlcktG.mjs} +2 -2
  79. package/dist/{mysql-xChEivOe.mjs.map → mysql-D1GlcktG.mjs.map} +1 -1
  80. package/dist/{mysql-adapter-C6c5govr.mjs → mysql-adapter-ClOoHKpn.mjs} +2 -2
  81. package/dist/{mysql-adapter-C6c5govr.mjs.map → mysql-adapter-ClOoHKpn.mjs.map} +1 -1
  82. package/dist/mysql2.d.mts +1 -1
  83. package/dist/mysql2.mjs +1 -1
  84. package/dist/neon-http.d.mts +1 -1
  85. package/dist/neon-http.mjs +1 -1
  86. package/dist/{object-store-D9mvOHP4.d.mts → object-store-BN64q8Zn.d.mts} +3 -3
  87. package/dist/{object-store-ChYHlOMD.mjs → object-store-CZADAv4c.mjs} +2 -2
  88. package/dist/{object-store-ChYHlOMD.mjs.map → object-store-CZADAv4c.mjs.map} +1 -1
  89. package/dist/permissions.d.mts +2 -2
  90. package/dist/permissions.mjs +1 -1
  91. package/dist/permissions.mjs.map +1 -1
  92. package/dist/pg.d.mts +1 -1
  93. package/dist/pg.mjs +1 -1
  94. package/dist/pglite.d.mts +1 -1
  95. package/dist/pglite.mjs +1 -1
  96. package/dist/{pinned-session-BTplL3iZ.mjs → pinned-session-CjvR0Ge2.mjs} +2 -2
  97. package/dist/{pinned-session-BTplL3iZ.mjs.map → pinned-session-CjvR0Ge2.mjs.map} +1 -1
  98. package/dist/planetscale.d.mts +1 -1
  99. package/dist/planetscale.mjs +1 -1
  100. package/dist/{planner-C1NzLBge.d.mts → planner-8smxUOt9.d.mts} +1 -1
  101. package/dist/{postgres-BqAxDWTQ.mjs → postgres-Be0jMJWI.mjs} +2 -2
  102. package/dist/{postgres-BqAxDWTQ.mjs.map → postgres-Be0jMJWI.mjs.map} +1 -1
  103. package/dist/{postgres-adapter-CxEit2-v.mjs → postgres-adapter-BoQ4RRwr.mjs} +2 -2
  104. package/dist/{postgres-adapter-CxEit2-v.mjs.map → postgres-adapter-BoQ4RRwr.mjs.map} +1 -1
  105. package/dist/{postgres-adapter-CGthb5yh.mjs → postgres-adapter-C_Mt8lVC.mjs} +2 -2
  106. package/dist/{postgres-adapter-CGthb5yh.mjs.map → postgres-adapter-C_Mt8lVC.mjs.map} +1 -1
  107. package/dist/{postgres-result-KyBKBNJr.mjs → postgres-result-CYu1dyI_.mjs} +1 -1
  108. package/dist/{postgres-result-KyBKBNJr.mjs.map → postgres-result-CYu1dyI_.mjs.map} +1 -1
  109. package/dist/postgres.d.mts +1 -1
  110. package/dist/postgres.mjs +1 -1
  111. package/dist/result-shape-DQc-tDJ5.mjs +2 -0
  112. package/dist/{result-shape-CDgX_vzn.mjs.map → result-shape-DQc-tDJ5.mjs.map} +1 -1
  113. package/dist/rows-JXjhWwyb.mjs +2 -0
  114. package/dist/rows-JXjhWwyb.mjs.map +1 -0
  115. package/dist/{scalar-S8yMvdmx.mjs → scalar-CqqZ6jWd.mjs} +2 -2
  116. package/dist/{scalar-S8yMvdmx.mjs.map → scalar-CqqZ6jWd.mjs.map} +1 -1
  117. package/dist/schema/json.d.mts +1 -1
  118. package/dist/schema/json.mjs +1 -1
  119. package/dist/{schema-9N9jQlVL.mjs → schema-Cv-hhpl5.mjs} +2 -2
  120. package/dist/{schema-9N9jQlVL.mjs.map → schema-Cv-hhpl5.mjs.map} +1 -1
  121. package/dist/{schema-introspection-CyXKReK1.mjs → schema-introspection-B2Rvqgut.mjs} +3 -3
  122. package/dist/{schema-introspection-CyXKReK1.mjs.map → schema-introspection-B2Rvqgut.mjs.map} +1 -1
  123. package/dist/schema.d.mts +1 -1
  124. package/dist/schema.mjs +1 -1
  125. package/dist/{select-assembly-CkGe2ABs.mjs → select-assembly-BxtETbG9.mjs} +1 -1
  126. package/dist/{select-assembly-CkGe2ABs.mjs.map → select-assembly-BxtETbG9.mjs.map} +1 -1
  127. package/dist/{settle-CS_k6Ztm.mjs → settle-etgtP1WM.mjs} +2 -2
  128. package/dist/{settle-CS_k6Ztm.mjs.map → settle-etgtP1WM.mjs.map} +1 -1
  129. package/dist/sha256-CEYo7k7R.mjs +2 -0
  130. package/dist/sha256-CEYo7k7R.mjs.map +1 -0
  131. package/dist/soft-delete.d.mts +1 -1
  132. package/dist/{sql-statement-tokens-CFi1y3bK.mjs → sql-statement-tokens-BW7Q-rF-.mjs} +1 -1
  133. package/dist/{sql-statement-tokens-CFi1y3bK.mjs.map → sql-statement-tokens-BW7Q-rF-.mjs.map} +1 -1
  134. package/dist/{sqlite-adapter-BXAJy3mI.mjs → sqlite-adapter-B_LNxPA0.mjs} +2 -2
  135. package/dist/{sqlite-adapter-BXAJy3mI.mjs.map → sqlite-adapter-B_LNxPA0.mjs.map} +1 -1
  136. package/dist/{sqlite-utils-D_cypcyW.mjs → sqlite-utils-DIOll4P7.mjs} +1 -1
  137. package/dist/{sqlite-utils-D_cypcyW.mjs.map → sqlite-utils-DIOll4P7.mjs.map} +1 -1
  138. package/dist/sqlite3.d.mts +1 -1
  139. package/dist/sqlite3.mjs +1 -1
  140. package/dist/{standard-sql-CoGqv-iX.mjs → standard-sql-mJt0RHHE.mjs} +1 -1
  141. package/dist/{standard-sql-CoGqv-iX.mjs.map → standard-sql-mJt0RHHE.mjs.map} +1 -1
  142. package/dist/{to-many-C1PuFIpf.mjs → to-many-BSipkSbK.mjs} +2 -2
  143. package/dist/{to-many-C1PuFIpf.mjs.map → to-many-BSipkSbK.mjs.map} +1 -1
  144. package/dist/{utils-CtFUE8UN.mjs → utils-DjXObbUK.mjs} +2 -2
  145. package/dist/{utils-CtFUE8UN.mjs.map → utils-DjXObbUK.mjs.map} +1 -1
  146. package/dist/v-CrJYqdzu.mjs +2 -0
  147. package/dist/v-CrJYqdzu.mjs.map +1 -0
  148. package/dist/validation.d.mts +1 -1
  149. package/dist/validation.mjs +1 -1
  150. package/dist/{validator-DgffZq9C.mjs → validator-BqzpyNmt.mjs} +2 -2
  151. package/dist/{validator-DgffZq9C.mjs.map → validator-BqzpyNmt.mjs.map} +1 -1
  152. package/dist/version-Dus3if78.mjs +2 -0
  153. package/dist/{version-CXuJzC-q.mjs.map → version-Dus3if78.mjs.map} +1 -1
  154. package/package.json +16 -15
  155. package/dist/chain-C7c1YTXD.mjs +0 -2
  156. package/dist/chain-C7c1YTXD.mjs.map +0 -1
  157. package/dist/client-_WKrPNmm.mjs +0 -2
  158. package/dist/client-_WKrPNmm.mjs.map +0 -1
  159. package/dist/controls-Da-efekX.mjs +0 -2
  160. package/dist/controls-Da-efekX.mjs.map +0 -1
  161. package/dist/every-1pKZteeB.mjs +0 -2
  162. package/dist/identity-oQvIe7u8.mjs +0 -2
  163. package/dist/identity-oQvIe7u8.mjs.map +0 -1
  164. package/dist/result-shape-CDgX_vzn.mjs +0 -2
  165. package/dist/v-CYTUI0H5.mjs +0 -2
  166. package/dist/v-CYTUI0H5.mjs.map +0 -1
  167. package/dist/version-CXuJzC-q.mjs +0 -2
package/dist/client.d.mts CHANGED
@@ -1,2 +1,2 @@
1
- import { A as Schema, Bt as CountResultType, C as Client, D as OperationPayloadSchema, Dt as renderSchemaType, E as OperationPayload, Et as renderOperationResultType, F as LinkedClientConfig, Gn as IndexOptions, Ht as InferSelectInclude, I as Links, L as RelationLinks, M as ClientSchema, N as FlatSchema, O as OperationResult, Ot as validateOperationPayload, P as Linked, Qt as StatementHandler, Rt as AggregateResultType, S as CachedClient, T as MutationOperations, Tt as getOperationPayloadSchema, Ut as defaultOmit, Vt as GroupByResultType, Wn as IndexDefinition, Xt as defineExtension, Y as VibSchema, Yt as ClientExtension, Zt as StatementContext, _ as ObservationCompletion, _n as UnwrapPendingOperation, dr as ObjectSchema, gn as PendingOperation, in as ExtensionResultConsumerState, j as ValidatedOperationPayload, jt as ExtendedClient, k as Operations, kt as ClientTypeState, nn as ExtensionCacheState, on as RawOperation, qt as PlacedControl, v as ObservationUnit, vn as UnwrapPendingOperations, w as InferDatabase, x as CacheableOperations, y as ObserveHandler, yn as isPendingOperation, zt as BatchPayload } from "./index-VsM29vYN.mjs";
1
+ import { A as Schema, Bt as CountResultType, C as Client, D as OperationPayloadSchema, Dt as renderSchemaType, E as OperationPayload, Et as renderOperationResultType, F as LinkedClientConfig, Gn as IndexOptions, Ht as InferSelectInclude, I as Links, L as RelationLinks, M as ClientSchema, N as FlatSchema, O as OperationResult, Ot as validateOperationPayload, P as Linked, Qt as StatementHandler, Rt as AggregateResultType, S as CachedClient, T as MutationOperations, Tt as getOperationPayloadSchema, Ut as defaultOmit, Vt as GroupByResultType, Wn as IndexDefinition, Xt as defineExtension, Y as VibSchema, Yt as ClientExtension, Zt as StatementContext, _ as ObservationCompletion, _n as UnwrapPendingOperation, dr as ObjectSchema, gn as PendingOperation, in as ExtensionResultConsumerState, j as ValidatedOperationPayload, jt as ExtendedClient, k as Operations, kt as ClientTypeState, nn as ExtensionCacheState, on as RawOperation, qt as PlacedControl, v as ObservationUnit, vn as UnwrapPendingOperations, w as InferDatabase, x as CacheableOperations, y as ObserveHandler, yn as isPendingOperation, zt as BatchPayload } from "./index-D4O0Twvs.mjs";
2
2
  export { type AggregateResultType, type BatchPayload, type CacheableOperations, type CachedClient, type Client, type ClientExtension, type ClientSchema, type ClientTypeState, type CountResultType, type ExtendedClient, type ExtensionCacheState, type ExtensionResultConsumerState, type FlatSchema, type GroupByResultType, type IndexDefinition, type IndexOptions, type InferDatabase, type InferSelectInclude, type Linked, type LinkedClientConfig, type Links, type MutationOperations, type ObjectSchema, type ObservationCompletion, type ObservationUnit, type ObserveHandler, type OperationPayload, type OperationPayloadSchema, type OperationResult, type Operations, PendingOperation, type PlacedControl, type RawOperation, type RelationLinks, type Schema, type StatementContext, type StatementHandler, type UnwrapPendingOperation, type UnwrapPendingOperations, type ValidatedOperationPayload, type VibSchema, defaultOmit, defineExtension, getOperationPayloadSchema, isPendingOperation, renderOperationResultType, renderSchemaType, validateOperationPayload };
package/dist/client.mjs CHANGED
@@ -1 +1 @@
1
- import{d as e,o as t}from"./chain-C7c1YTXD.mjs";import{d as n,m as r}from"./result-shape-CDgX_vzn.mjs";import{i,n as a,r as o,t as s}from"./schema-introspection-CyXKReK1.mjs";export{n as PendingOperation,e as defaultOmit,t as defineExtension,s as getOperationPayloadSchema,r as isPendingOperation,a as renderOperationResultType,o as renderSchemaType,i as validateOperationPayload};
1
+ import{a as e,s as t}from"./chain-BjJ_M7EE.mjs";import{d as n,m as r}from"./result-shape-DQc-tDJ5.mjs";import{i,n as a,r as o,t as s}from"./schema-introspection-B2Rvqgut.mjs";export{n as PendingOperation,t as defaultOmit,e as defineExtension,s as getOperationPayloadSchema,r as isPendingOperation,a as renderOperationResultType,o as renderSchemaType,i as validateOperationPayload};
@@ -1,2 +1,2 @@
1
1
  import{n as e}from"./chunk-BuuaeEvq.mjs";const t={now:()=>Date.now(),setTimeout(e,t){let n=setTimeout(e,t);return{cancel:()=>clearTimeout(n),unref:()=>{typeof n.unref==`function`&&n.unref()}}}};export{t};
2
- //# sourceMappingURL=clock-C24RcpwO.mjs.map
2
+ //# sourceMappingURL=clock-YTLtjLFS.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"clock-C24RcpwO.mjs","names":[],"sources":["../src/clock.ts"],"sourcesContent":["/**\n * The time seam.\n *\n * Two subsystems decide things by reading the wall clock and arming timers:\n * cache freshness (TTL, and the stale window SWR serves from) and the\n * transaction `timeout` / `maxWait` bounds. Both are behavior worth testing,\n * and testing either through the host clock means sleeping — which buys a slow\n * suite and a timing race, not a proof.\n *\n * So both take their time from a `Clock`. The default is the host's own, and\n * nothing here is public API: the override exists so a test can advance time\n * instead of waiting for it. Driver-internal timers are deliberately out of\n * scope — they belong to the database client, not to us.\n */\n\n/**\n * A timer armed by a `Clock`. The handle owns its own cancellation, so a call\n * site never reaches for a host timer function to undo what a clock started.\n */\nexport interface ClockTimer {\n /** Cancel the pending callback. Safe to call after it has already fired. */\n cancel(): void;\n /**\n * Release the host's hold on the event loop, where the host has one to\n * release. Node timers do; a virtual clock has nothing to release and says\n * so by omitting this.\n */\n unref?(): void;\n}\n\n/** The reading of time and the arming of timers, as one injectable thing. */\nexport interface Clock {\n /** Milliseconds since the epoch, exactly as `Date.now()` reports them. */\n now(): number;\n /** Arm `callback` to run `ms` from now. Cancel through the returned handle. */\n setTimeout(callback: () => void, ms: number): ClockTimer;\n}\n\n/** The host clock: `Date.now` and the global timer functions. The default. */\nexport const systemClock: Clock = {\n now: () => Date.now(),\n setTimeout(callback: () => void, ms: number): ClockTimer {\n const timer = setTimeout(callback, ms);\n return {\n cancel: () => clearTimeout(timer),\n // Hosts that are not Node (browsers, some edge runtimes) hand back a\n // number with no `unref`. Asking is cheaper than assuming.\n unref: () => {\n if (typeof timer.unref === \"function\") timer.unref();\n },\n };\n },\n};\n"],"mappings":"yCAuCA,MAAa,EAAqB,CAChC,QAAW,KAAK,KAAK,CACrB,WAAW,EAAsB,EAAwB,CACvD,IAAM,EAAQ,WAAW,EAAU,EAAG,CACtC,MAAO,CACL,WAAc,aAAa,EAAM,CAGjC,UAAa,CACP,OAAO,EAAM,OAAU,YAAY,EAAM,OAAO,EAEvD,EAEJ"}
1
+ {"version":3,"file":"clock-YTLtjLFS.mjs","names":[],"sources":["../src/clock.ts"],"sourcesContent":["/**\n * The time seam.\n *\n * Two subsystems decide things by reading the wall clock and arming timers:\n * cache freshness (TTL, and the stale window SWR serves from) and the\n * transaction `timeout` / `maxWait` bounds. Both are behavior worth testing,\n * and testing either through the host clock means sleeping — which buys a slow\n * suite and a timing race, not a proof.\n *\n * So both take their time from a `Clock`. The default is the host's own, and\n * nothing here is public API: the override exists so a test can advance time\n * instead of waiting for it. Driver-internal timers are deliberately out of\n * scope — they belong to the database client, not to us.\n */\n\n/**\n * A timer armed by a `Clock`. The handle owns its own cancellation, so a call\n * site never reaches for a host timer function to undo what a clock started.\n */\nexport interface ClockTimer {\n /** Cancel the pending callback. Safe to call after it has already fired. */\n cancel(): void;\n /**\n * Release the host's hold on the event loop, where the host has one to\n * release. Node timers do; a virtual clock has nothing to release and says\n * so by omitting this.\n */\n unref?(): void;\n}\n\n/** The reading of time and the arming of timers, as one injectable thing. */\nexport interface Clock {\n /** Milliseconds since the epoch, exactly as `Date.now()` reports them. */\n now(): number;\n /** Arm `callback` to run `ms` from now. Cancel through the returned handle. */\n setTimeout(callback: () => void, ms: number): ClockTimer;\n}\n\n/** The host clock: `Date.now` and the global timer functions. The default. */\nexport const systemClock: Clock = {\n now: () => Date.now(),\n setTimeout(callback: () => void, ms: number): ClockTimer {\n const timer = setTimeout(callback, ms);\n return {\n cancel: () => clearTimeout(timer),\n // Hosts that are not Node (browsers, some edge runtimes) hand back a\n // number with no `unref`. Asking is cheaper than assuming.\n unref: () => {\n if (typeof timer.unref === \"function\") timer.unref();\n },\n };\n },\n};\n"],"mappings":"yCAuCA,MAAa,EAAqB,CAChC,QAAW,KAAK,KAAK,CACrB,WAAW,EAAsB,EAAwB,CACvD,IAAM,EAAQ,WAAW,EAAU,EAAG,CACtC,MAAO,CACL,WAAc,aAAa,EAAM,CAGjC,UAAa,CACP,OAAO,EAAM,OAAU,YAAY,EAAM,OAAO,EAEvD,EAEJ"}
package/dist/config.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { i as ResolveCallback, t as MigrationClient } from "./planner-C1NzLBge.mjs";
1
+ import { i as ResolveCallback, t as MigrationClient } from "./planner-8smxUOt9.mjs";
2
2
  import { n as MigrationStorageWriter } from "./contract-Dw0FR78e.mjs";
3
3
 
4
4
  //#region src/cli/utils.d.ts
package/dist/config.mjs CHANGED
@@ -1 +1 @@
1
- import{t as e}from"./utils-CtFUE8UN.mjs";export{e as defineConfig};
1
+ import{t as e}from"./utils-DjXObbUK.mjs";export{e as defineConfig};
package/dist/d1.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { A as Schema, An as BatchQuery, At as DriverConfig, F as LinkedClientConfig, Ft as VibORMClient, Nn as QueryExecutionContext, Pn as QueryResult, Pt as NoExtraDriverConfigKeys, h as DriverResultParser, jn as CommittedBatchNotification, kn as TransactionOptionSupport, s as DatabaseAdapter, u as Driver } from "./index-VsM29vYN.mjs";
1
+ import { A as Schema, An as BatchQuery, At as DriverConfig, F as LinkedClientConfig, Ft as VibORMClient, Nn as QueryExecutionContext, Pn as QueryResult, Pt as NoExtraDriverConfigKeys, h as DriverResultParser, jn as CommittedBatchNotification, kn as TransactionOptionSupport, s as DatabaseAdapter, u as Driver } from "./index-D4O0Twvs.mjs";
2
2
  import { D1Database, D1DatabaseSession } from "@cloudflare/workers-types";
3
3
 
4
4
  //#region src/drivers/d1/index.d.ts
package/dist/d1.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t,o as n}from"./bind-parameter-capacity-qfEejeOX.mjs";import{m as r}from"./error-mapping-C9WgitPi.mjs";import{p as i}from"./validation-BamBwne9.mjs";import{a,n as o,r as s}from"./client-_WKrPNmm.mjs";import{c,t as l}from"./driver-B9fIori_.mjs";import{l as u,o as d,r as f}from"./sqlite-utils-D_cypcyW.mjs";import{t as p}from"./sql-statement-tokens-CFi1y3bK.mjs";import{t as m}from"./sqlite-adapter-BXAJy3mI.mjs";const h=new Set([`EXPLAIN`,`SELECT`,`VALUES`]),g=new Set([`DELETE`,`INSERT`,`REPLACE`,`UPDATE`]),_=new Set([`ALTER`,`ANALYZE`,`ATTACH`,`BEGIN`,`COMMIT`,`CREATE`,`DETACH`,`DROP`,`END`,`REINDEX`,`RELEASE`,`ROLLBACK`,`SAVEPOINT`,`VACUUM`]),v=new Set([`CASE_SENSITIVE_LIKE`,`DEFER_FOREIGN_KEYS`,`FOREIGN_KEYS`,`IGNORE_CHECK_CONSTRAINTS`,`LEGACY_ALTER_TABLE`,`RECURSIVE_TRIGGERS`,`REVERSE_UNORDERED_SELECTS`]),y=new Set([`OPTIMIZE`]),b=new Set([...h,...g]);function classifySQLiteStatementResult(e){let t=p(e);if(!t)return`unknown`;let n=topLevelCommand(t),r=n?.value;return r?h.has(r)?`rows`:g.has(r)?t.slice(n.index+1).some(e=>e.kind===`word`&&e.value===`RETURNING`)?`rows`:`no-rows`:r===`PRAGMA`?classifyPragma(t):_.has(r)?`no-rows`:`unknown`:`unknown`}function isSQLiteInsertStatement(e){let t=topLevelCommand(p(e))?.value;return t===`INSERT`||t===`REPLACE`}function topLevelCommand(e){let t=e?.[0];if(!t||t.kind!==`word`)return;if(t.value!==`WITH`)return{index:0,value:t.value};let n=e.findIndex((e,t)=>t>0&&e.kind===`word`&&b.has(e.value)),r=e[n];return r?.kind===`word`?{index:n,value:r.value}:void 0}function classifyPragma(e){let t=e.findIndex(e=>e.kind===`symbol`&&e.value===`=`),n=e.findIndex(e=>e.kind===`symbol`&&e.value===`(`),r=t>=0?t:n,i=r<0?e.length:r,a;for(let t=i-1;t>0;--t){let n=e[t];if(n&&(n.kind===`word`||n.kind===`identifier`)){a=n.value;break}}return r<0?a&&y.has(a)?`no-rows`:`rows`:a&&v.has(a)?`no-rows`:`rows`}const x={database:!0};function convertD1Parameters(e){return f(e).map(e=>typeof e==`bigint`?e.toString():e)}const S=new Set([`aggregate`,`count`,`create`,`createManyAndReturn`,`delete`,`deleteManyAndReturn`,`exist`,`findFirst`,`findMany`,`findUnique`,`groupBy`,`update`,`updateManyAndReturn`,`upsert`]);function malformedD1Result(e,t){let n=e.operation??`execute`;return new i(`Driver "d1" returned a malformed result payload for operation "${n}": ${t}.`,{meta:{driver:`d1`,...e,operation:n}})}function assertD1BindingResult(e,t){if(!n(e)||e.success!==!0||e.results!==null&&!(Array.isArray(e.results)&&e.results.every(n))||!n(e.meta)||typeof e.meta.changes!=`number`||!Number.isFinite(e.meta.changes)||!Number.isSafeInteger(e.meta.changes)||e.meta.changes<0||typeof e.meta.last_row_id!=`number`||!Number.isFinite(e.meta.last_row_id)||!Number.isInteger(e.meta.last_row_id))throw malformedD1Result(t,`expected explicit object rows (or null), non-negative changes, and an integer last_row_id`)}function normalizeD1Result(e,t,n,r){let i=n.operation??`execute`;assertD1BindingResult(e,n);let a;if(e.results===null){if(r&&S.has(i)||classifySQLiteStatementResult(t)!==`no-rows`)throw malformedD1Result(n,`null results are not valid for a row-producing or unknown statement`);a=[]}else a=e.results;let o=isSQLiteInsertStatement(t)&&Number.isSafeInteger(e.meta.last_row_id)?e.meta.last_row_id:void 0;return{rows:a,rowCount:e.meta.changes===0?a.length:e.meta.changes,...o!==void 0&&o>0?{insertId:o}:{}}}var C=class D1Driver extends l{static canonicalExecuteEntry=D1Driver.prototype._execute;static canonicalExecute=D1Driver.prototype.execute;static canonicalTypedStatement=D1Driver.prototype.executeTypedStatement;static canonicalPositionalExecute=D1Driver.prototype.executePositional;adapter=new m({temporaryObjects:!1,deepExpressions:!1,sharedRelationBodies:!0});maxBindParametersPerStatement=100;result=u;supportsTransactions=!1;supportsBatch=!0;supportsOrderedCommittedSegments=!0;driverOptions;canonicalAdapter=this.adapter;canonicalAdapterResult=this.adapter.result;canonicalAdapterParseField=this.adapter.result.parseField;canonicalAdapterParseRelation=this.adapter.result.parseRelation;canonicalAdapterParseResult=this.adapter.result.parseResult;constructor(e){super(`sqlite`,`d1`),this.driverOptions=e,this.client=e.database,a(this,(e,t)=>this.executePositional(e,t),D1Driver.isPositionalCandidate)}executePositional(e,n){return this.executeTypedStatement(e,n,async(e,n,r,i)=>{if(!D1Driver.isPositionalCandidate(this)){let a=await this.execute(e,n,r,i);return t(a,{provider:this.driverName,operation:i.operation??`execute`}),{kind:`borrowed`,result:a}}let a=convertD1Parameters(r),o=await e.prepare(n).bind(...a).raw({columnNames:!0}),[c,...l]=Array.isArray(o)?o:[],u=c??[];if(!(Array.isArray(o)&&Array.isArray(u)&&u.every(e=>typeof e==`string`)))throw malformedD1Result(i,`the positional rows are malformed`);return s(l,u,{provider:this.driverName,operation:i.operation??`execute`}),{kind:`positional`,rows:l,columns:u}})}static isPositionalCandidate(e){return e instanceof D1Driver?Object.getPrototypeOf(e)===D1Driver.prototype&&e._execute===D1Driver.canonicalExecuteEntry&&e.execute===D1Driver.canonicalExecute&&e.executeTypedStatement===D1Driver.canonicalTypedStatement&&e.executePositional===D1Driver.canonicalPositionalExecute&&e.result===u&&e.result.parseField===d&&e.result.parseRelation===void 0&&e.result.parseResult===void 0&&e.adapter===e.canonicalAdapter&&e.adapter.result===e.canonicalAdapterResult&&e.adapter.result.parseField===e.canonicalAdapterParseField&&e.adapter.result.parseRelation===e.canonicalAdapterParseRelation&&e.adapter.result.parseResult===e.canonicalAdapterParseResult:!1}async initClient(){return this.driverOptions.database}async closeClient(e){}async execute(e,t,n,r){return this.executeStatement(e,t,n,r??{operation:`execute`})}async executeStatement(e,t,n,r){let i=convertD1Parameters(n);return normalizeD1Result(await e.prepare(t).bind(...i).run(),t,r,!0)}async executeRaw(e,t,n,r){return this.executeStatement(e,t,n??[],r??{operation:`executeRaw`})}transactionOptionSupport(){return{isolationLevel:`unsupported`,isolationLevelReason:`D1 bindings execute batches through batch(), which opens no transaction VibORM can set an isolation level on`,timeout:!1,timeoutReason:`D1 bindings run a batch as one provider call with no interactive body to interrupt`,maxWait:`unsupported`,maxWaitReason:`D1 bindings submit the batch immediately with no connection to acquire`}}transaction(e,t){return Promise.reject(r(this.driverName))}async executeBatch(e,t,n,r){let i=n??{operation:`executeBatch`},a=[];for(let n of t){let t=n.context??i;try{let t=n.params?convertD1Parameters(n.params):[];a.push(e.prepare(n.sql).bind(...t))}catch(e){throw this.normalizeStatementFailure(e,n.sql,this.getBatchDiagnosticParameters(n),t,!0)}}let o=await e.batch(a);if(await r?.(),!Array.isArray(o)||o.length!==t.length){let e=Array.isArray(o)?o.length:0;throw malformedD1Result(i,`expected ${t.length} statement results but received ${e}`)}let s=[];for(let e=0;e<o.length;e+=1){let n=t[e];if(!n)throw malformedD1Result(i,`missing statement metadata at batch result index ${e}`);s.push(normalizeD1Result(o[e],n.sql,n.context??i,!1))}return s}};function createClient(e){c(e,`d1`,x);let{database:t}=e;return o(e,new C({database:t}))}export{C as D1Driver,createClient};
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t,o as n}from"./bind-parameter-capacity-qfEejeOX.mjs";import{m as r}from"./error-mapping-C9WgitPi.mjs";import{p as i}from"./validation-BamBwne9.mjs";import{a,n as o,r as s}from"./client-BCgMXn6N.mjs";import{c,t as l}from"./driver-Ddt147dK.mjs";import{l as u,o as d,r as f}from"./sqlite-utils-DIOll4P7.mjs";import{t as p}from"./sql-statement-tokens-BW7Q-rF-.mjs";import{t as m}from"./sqlite-adapter-B_LNxPA0.mjs";const h=new Set([`EXPLAIN`,`SELECT`,`VALUES`]),g=new Set([`DELETE`,`INSERT`,`REPLACE`,`UPDATE`]),_=new Set([`ALTER`,`ANALYZE`,`ATTACH`,`BEGIN`,`COMMIT`,`CREATE`,`DETACH`,`DROP`,`END`,`REINDEX`,`RELEASE`,`ROLLBACK`,`SAVEPOINT`,`VACUUM`]),v=new Set([`CASE_SENSITIVE_LIKE`,`DEFER_FOREIGN_KEYS`,`FOREIGN_KEYS`,`IGNORE_CHECK_CONSTRAINTS`,`LEGACY_ALTER_TABLE`,`RECURSIVE_TRIGGERS`,`REVERSE_UNORDERED_SELECTS`]),y=new Set([`OPTIMIZE`]),b=new Set([...h,...g]);function classifySQLiteStatementResult(e){let t=p(e);if(!t)return`unknown`;let n=topLevelCommand(t),r=n?.value;return r?h.has(r)?`rows`:g.has(r)?t.slice(n.index+1).some(e=>e.kind===`word`&&e.value===`RETURNING`)?`rows`:`no-rows`:r===`PRAGMA`?classifyPragma(t):_.has(r)?`no-rows`:`unknown`:`unknown`}function isSQLiteInsertStatement(e){let t=topLevelCommand(p(e))?.value;return t===`INSERT`||t===`REPLACE`}function topLevelCommand(e){let t=e?.[0];if(!t||t.kind!==`word`)return;if(t.value!==`WITH`)return{index:0,value:t.value};let n=e.findIndex((e,t)=>t>0&&e.kind===`word`&&b.has(e.value)),r=e[n];return r?.kind===`word`?{index:n,value:r.value}:void 0}function classifyPragma(e){let t=e.findIndex(e=>e.kind===`symbol`&&e.value===`=`),n=e.findIndex(e=>e.kind===`symbol`&&e.value===`(`),r=t>=0?t:n,i=r<0?e.length:r,a;for(let t=i-1;t>0;--t){let n=e[t];if(n&&(n.kind===`word`||n.kind===`identifier`)){a=n.value;break}}return r<0?a&&y.has(a)?`no-rows`:`rows`:a&&v.has(a)?`no-rows`:`rows`}const x={database:!0};function convertD1Parameters(e){return f(e).map(e=>typeof e==`bigint`?e.toString():e)}const S=new Set([`aggregate`,`count`,`create`,`createManyAndReturn`,`delete`,`deleteManyAndReturn`,`exist`,`findFirst`,`findMany`,`findUnique`,`groupBy`,`update`,`updateManyAndReturn`,`upsert`]);function malformedD1Result(e,t){let n=e.operation??`execute`;return new i(`Driver "d1" returned a malformed result payload for operation "${n}": ${t}.`,{meta:{driver:`d1`,...e,operation:n}})}function assertD1BindingResult(e,t){if(!n(e)||e.success!==!0||e.results!==null&&!(Array.isArray(e.results)&&e.results.every(n))||!n(e.meta)||typeof e.meta.changes!=`number`||!Number.isFinite(e.meta.changes)||!Number.isSafeInteger(e.meta.changes)||e.meta.changes<0||typeof e.meta.last_row_id!=`number`||!Number.isFinite(e.meta.last_row_id)||!Number.isInteger(e.meta.last_row_id))throw malformedD1Result(t,`expected explicit object rows (or null), non-negative changes, and an integer last_row_id`)}function normalizeD1Result(e,t,n,r){let i=n.operation??`execute`;assertD1BindingResult(e,n);let a;if(e.results===null){if(r&&S.has(i)||classifySQLiteStatementResult(t)!==`no-rows`)throw malformedD1Result(n,`null results are not valid for a row-producing or unknown statement`);a=[]}else a=e.results;let o=isSQLiteInsertStatement(t)&&Number.isSafeInteger(e.meta.last_row_id)?e.meta.last_row_id:void 0;return{rows:a,rowCount:e.meta.changes===0?a.length:e.meta.changes,...o!==void 0&&o>0?{insertId:o}:{}}}var C=class D1Driver extends l{static canonicalExecuteEntry=D1Driver.prototype._execute;static canonicalExecute=D1Driver.prototype.execute;static canonicalTypedStatement=D1Driver.prototype.executeTypedStatement;static canonicalPositionalExecute=D1Driver.prototype.executePositional;adapter=new m({temporaryObjects:!1,deepExpressions:!1,sharedRelationBodies:!0});maxBindParametersPerStatement=100;result=u;supportsTransactions=!1;supportsBatch=!0;supportsOrderedCommittedSegments=!0;driverOptions;canonicalAdapter=this.adapter;canonicalAdapterResult=this.adapter.result;canonicalAdapterParseField=this.adapter.result.parseField;canonicalAdapterParseRelation=this.adapter.result.parseRelation;canonicalAdapterParseResult=this.adapter.result.parseResult;constructor(e){super(`sqlite`,`d1`),this.driverOptions=e,this.client=e.database,a(this,(e,t)=>this.executePositional(e,t),D1Driver.isPositionalCandidate)}executePositional(e,n){return this.executeTypedStatement(e,n,async(e,n,r,i)=>{if(!D1Driver.isPositionalCandidate(this)){let a=await this.execute(e,n,r,i);return t(a,{provider:this.driverName,operation:i.operation??`execute`}),{kind:`borrowed`,result:a}}let a=convertD1Parameters(r),o=await e.prepare(n).bind(...a).raw({columnNames:!0}),[c,...l]=Array.isArray(o)?o:[],u=c??[];if(!(Array.isArray(o)&&Array.isArray(u)&&u.every(e=>typeof e==`string`)))throw malformedD1Result(i,`the positional rows are malformed`);return s(l,u,{provider:this.driverName,operation:i.operation??`execute`}),{kind:`positional`,rows:l,columns:u}})}static isPositionalCandidate(e){return e instanceof D1Driver?Object.getPrototypeOf(e)===D1Driver.prototype&&e._execute===D1Driver.canonicalExecuteEntry&&e.execute===D1Driver.canonicalExecute&&e.executeTypedStatement===D1Driver.canonicalTypedStatement&&e.executePositional===D1Driver.canonicalPositionalExecute&&e.result===u&&e.result.parseField===d&&e.result.parseRelation===void 0&&e.result.parseResult===void 0&&e.adapter===e.canonicalAdapter&&e.adapter.result===e.canonicalAdapterResult&&e.adapter.result.parseField===e.canonicalAdapterParseField&&e.adapter.result.parseRelation===e.canonicalAdapterParseRelation&&e.adapter.result.parseResult===e.canonicalAdapterParseResult:!1}async initClient(){return this.driverOptions.database}async closeClient(e){}async execute(e,t,n,r){return this.executeStatement(e,t,n,r??{operation:`execute`})}async executeStatement(e,t,n,r){let i=convertD1Parameters(n);return normalizeD1Result(await e.prepare(t).bind(...i).run(),t,r,!0)}async executeRaw(e,t,n,r){return this.executeStatement(e,t,n??[],r??{operation:`executeRaw`})}transactionOptionSupport(){return{isolationLevel:`unsupported`,isolationLevelReason:`D1 bindings execute batches through batch(), which opens no transaction VibORM can set an isolation level on`,timeout:!1,timeoutReason:`D1 bindings run a batch as one provider call with no interactive body to interrupt`,maxWait:`unsupported`,maxWaitReason:`D1 bindings submit the batch immediately with no connection to acquire`}}transaction(e,t){return Promise.reject(r(this.driverName))}async executeBatch(e,t,n,r){let i=n??{operation:`executeBatch`},a=[];for(let n of t){let t=n.context??i;try{let t=n.params?convertD1Parameters(n.params):[];a.push(e.prepare(n.sql).bind(...t))}catch(e){throw this.normalizeStatementFailure(e,n.sql,this.getBatchDiagnosticParameters(n),t,!0)}}let o=await e.batch(a);if(await r?.(),!Array.isArray(o)||o.length!==t.length){let e=Array.isArray(o)?o.length:0;throw malformedD1Result(i,`expected ${t.length} statement results but received ${e}`)}let s=[];for(let e=0;e<o.length;e+=1){let n=t[e];if(!n)throw malformedD1Result(i,`missing statement metadata at batch result index ${e}`);s.push(normalizeD1Result(o[e],n.sql,n.context??i,!1))}return s}};function createClient(e){c(e,`d1`,x);let{database:t}=e;return o(e,new C({database:t}))}export{C as D1Driver,createClient};
2
2
  //# sourceMappingURL=d1.mjs.map
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t,r as n}from"./cache-CIPRF-pz.mjs";import{n as r}from"./v-CYTUI0H5.mjs";import{n as i,r as a,t as o}from"./key-D_kagnFv.mjs";import{d as s,f as c,t as l}from"./observation-Co72iCd1.mjs";import{o as u}from"./execution-context-rJXTRVrJ.mjs";import{t as d}from"./clock-C24RcpwO.mjs";const f=`:reval`,p=3e4;function scheduleBackground(e,t){let n=e.catch(()=>void 0);if(t)try{t(n)}catch{}}const m={ms:1,millisecond:1,milliseconds:1,s:1e3,sec:1e3,second:1e3,seconds:1e3,m:60*1e3,min:60*1e3,minute:60*1e3,minutes:60*1e3,h:3600*1e3,hr:3600*1e3,hour:3600*1e3,hours:3600*1e3,d:1440*60*1e3,day:1440*60*1e3,days:1440*60*1e3,w:10080*60*1e3,week:10080*60*1e3,weeks:10080*60*1e3,month:720*60*60*1e3,months:720*60*60*1e3},h=Object.keys(m).join(`, `),g=/^(\d+(?:\.\d+)?)\s*([a-z]+)$/;function parseTTL(e){if(typeof e==`number`){if(!Number.isFinite(e)||e<=0||e>2**53-1)throw new n(`TTL must be positive, got: ${e}`);return e}let t=e.trim().toLowerCase().match(g);if(!t)throw new n(`Invalid TTL format: "${e}". Expected format: "<number> <unit>" (e.g., "1 hour", "20 seconds")`);let r=t[1],i=t[2],a=Number.parseFloat(r),o=m[i];if(o===void 0)throw new n(`Unknown time unit: "${i}". Valid units: ${h}`);let s=Math.floor(a*o);if(!Number.isSafeInteger(s)||s<=0)throw new n(`TTL must be positive, got: ${s}ms from "${e}"`);return s}const _=r.object({invalidate:r.string({array:!0,optional:!0}),autoInvalidate:r.boolean({optional:!0,default:!0})},{optional:!0,default:{autoInvalidate:!0}});function hasCacheInvalidationWork(e){return e===void 0||e.autoInvalidate===!0||e?.invalidate!==void 0&&e.invalidate.length>0}const v=300*1e3,y=r.object({ttl:r.coerce(r.optional(r.union([r.string(),r.number()]),v),e=>parseTTL(e)),swr:r.coerce(r.optional(r.union([r.boolean(),r.string(),r.number()])),e=>e===void 0||typeof e==`boolean`?e:parseTTL(e)),key:r.string({optional:!0}),bypass:r.boolean({optional:!0})},{optional:!0,default:{ttl:v,swr:!1,bypass:!1}});let executeCachedWithResultCodecFriend,invalidateOfficialCacheFriend;const b=new WeakMap,x=new WeakMap,completeWithoutFacts=()=>void 0;function createCacheOutcome(e,t,n){return{event:e,status:t,at:Date.now(),error:n}}function recordCacheOutcome(e,t,n,r){if(e===void 0||l(u(e))?.wants(`cache-outcomes`)!==!0)return;let i=x.get(e);i===void 0&&(i={outcomes:[],completed:!1},x.set(e,i)),i.outcomes.push(createCacheOutcome(t,n,r))}function placeCacheSetFailure(e,t){let n=createCacheOutcome(`miss`,`cache-set-failed`,t),r=x.get(e);if(r!==void 0&&!r.completed){r.outcomes.push(n);return}return Object.freeze({kind:`cache`,outcomes:[n]})}function readCacheExecutionOutcomes(e){let t=x.get(e);if(t!==void 0)return()=>(t.completed=!0,Object.freeze([...t.outcomes]))}function createOfficialCacheScope(e){let t=Object.freeze({});return b.set(t,e),t}function readOfficialCacheNamespace(e){let n=b.get(e);if(n===void 0)throw new t(`Official cache scope is not authentic for this cache execution.`);return n}function refuseExternalScope(e){if(e!==void 0)throw new t(`Cache driver methods do not accept an external cache scope.`)}var CacheDriver=class{#e=0;driverName;clock;static{executeCachedWithResultCodecFriend=(e,t,n,r,i,a,o,s)=>{let c=readOfficialCacheNamespace(s);return e.#t(t,n,r,i,a,o,c)},invalidateOfficialCacheFriend=(e,t,n,r,i)=>e.#d(t,n,r,readOfficialCacheNamespace(i))}constructor(e,t=d){this.driverName=e,this.clock=t}async#t(e,t,n,r,i,o,s){let c=a(e,t,n),l=`${c.key}${i.key===void 0?``:`:${i.key}`}`,u=JSON.stringify([c.identity,i.key]),d=this.#e,executeCore=async()=>{if(i.bypass){let e=await r();return this.#r(l,e,i,o,s,u,d),recordCacheOutcome(i.executionContext,`bypass`),e}let n=await this.#n(l,i.executionContext,s,o,u);if(n){let a=this.clock.now()-n.createdAt;if(!(a>=n.ttl))return recordCacheOutcome(i.executionContext,`hit`),n.value;let c=i.swr;if(c!==!1&&a<c&&(n.expiresAt===void 0||this.clock.now()<n.expiresAt))return scheduleBackground(this.#a(e,t,l,r,i,c,o,s,u,d),i.waitUntil),recordCacheOutcome(i.executionContext,`hit`,`stale`),n.value}let a=await r();return this.#r(l,a,i,o,s,u,d),recordCacheOutcome(i.executionContext,`miss`),a};return executeCore()}async#n(e,t,n,r,i){let a=await this.#s(e,t,n);return a===null||a.identity!==i||!Number.isFinite(a.createdAt)||!Number.isFinite(a.ttl)||a.ttl<=0||a.expiresAt===void 0||!Number.isFinite(a.expiresAt)||a.expiresAt<a.createdAt?null:{createdAt:a.createdAt,ttl:a.ttl,expiresAt:a.expiresAt,value:r.materialize(a.value)}}#r(e,t,n,r,i,a,o){if(o!==this.#e)return;let s;try{s=r.snapshot(t)}catch(e){recordCacheOutcome(n.executionContext,`miss`,`cache-set-failed`,e);return}this.#i(e,s,n,i,a,o)}#i(e,t,n,r,i,a){scheduleBackground(this.#c(e,t,{ttl:n.ttlMs,swrTtl:n.swr===!1?void 0:n.swr},n.executionContext,r,n.executionContext,i,a).catch(()=>void 0),n.waitUntil)}async#a(e,t,n,r,i,a,o,c,l,d){let f;try{f=await this.#l(n,c)}catch{return}if(!f)return;let p=u(i.executionContext)?.observe,m=p===void 0||p.length===0?void 0:{failed:!1,error:void 0},h,doRevalidate=async()=>{let e;try{let t=await r(),s=o.snapshot(t);await this.#c(n,s,{ttl:i.ttlMs,swrTtl:a},i.executionContext,c,void 0,l,d),e=createCacheOutcome(`revalidate`,`success`)}catch(t){m!==void 0&&(m.failed=!0,m.error=t),e=createCacheOutcome(`revalidate`,`error`,t)}finally{if(m===void 0)await this.#u(n,c).catch(()=>void 0);else try{await this.#u(n,c)}catch(e){if(m.failed){let t=m.error;m.error=AggregateError([t,e],`Cache revalidation work and cleanup both failed.`,{cause:t})}else m.failed=!0,m.error=e}}return e};await(m===void 0?doRevalidate():s({kind:`cache`,operation:`revalidate`},p,async()=>{if(h=Object.freeze({kind:`cache`,outcomes:[await doRevalidate()]}),m.failed)throw m.error},void 0,()=>Object.freeze({kind:`cache`,context:i.executionContext,read:Object.freeze({model:e,operation:t,identity:i.driverIdentity}),complete:()=>h})))}#o(e,t,n,r=completeWithoutFacts,i){let a=u(t)?.observe;if(a===void 0||a.length===0)return n();let o=e===`clear`||e===`delete`;return s({kind:`cache`,operation:o?`invalidate`:e},o?c(a):a,n,void 0,()=>Object.freeze(o?{kind:`cache-backend`,boundary:e,driverName:this.driverName,complete:completeWithoutFacts}:{kind:`cache`,context:t,driverName:this.driverName,...i===void 0?{}:{ttl:i},complete:r}))}async _get(e,t,n){return refuseExternalScope(n),this.#s(e,t)}async#s(e,t,n){let r=this.#m(e,n),i;return this.#o(`get`,t,async()=>{let e=await this.get(r);return i=e?this.clock.now()-e.createdAt>e.ttl?`stale`:`hit`:`miss`,e},()=>i===void 0?void 0:Object.freeze({kind:`cache`,result:i}))}async _set(e,t,n,r,i){return refuseExternalScope(i),this.#c(e,t,n,r)}async#c(e,t,n,r,i,a,o,s){if(s!==void 0&&s!==this.#e)return;let c=this.#m(e,i),l={value:t,createdAt:this.clock.now(),ttl:n.ttl,...o===void 0?{}:{identity:o,expiresAt:this.clock.now()+(n.swrTtl??n.ttl)}},u=n.swrTtl??n.ttl;return this.#o(`set`,r,async()=>{await this.set(c,u,l),s!==void 0&&s!==this.#e&&await this.delete([c])},a===void 0?void 0:e=>e.status===`failure`?placeCacheSetFailure(a,e.failure):void 0,n.ttl)}async _delete(e,t,n){refuseExternalScope(n);let r=this.#m(e);return this.#f(r,t)}async _clear(e,t,n){refuseExternalScope(n);let r=this.#m(e??``);return this.#p(r,t)}async _markRevalidating(e,t){return refuseExternalScope(t),this.#l(e)}async#l(e,t){let n=`${this.#m(e,t)}${f}`,r=await this.get(n);if(r&&this.clock.now()-r.createdAt<r.ttl)return!1;let i={value:!0,createdAt:this.clock.now(),ttl:p};return await this.set(n,p,i),!0}async _clearRevalidating(e,t){return refuseExternalScope(t),this.#u(e)}async#u(e,t){let n=`${this.#m(e,t)}${f}`;await this.delete([n])}async _invalidate(e,t,n,r){return refuseExternalScope(r),this.#d(e,t,n)}async#d(e,t,n,r){if(!hasCacheInvalidationWork(t))return;this.#e+=1;let i=[];if((t===void 0||t.autoInvalidate===!0)&&i.push({kind:`clear`,prefixedKey:this.#m(r===void 0?`${e}:`:``,r)}),t?.invalidate)for(let e of t.invalidate){let t=e.endsWith(`*`),n=t?e.slice(0,-1):e;i.push({kind:t?`clear`:`delete`,prefixedKey:this.#m(n,r)})}return this.#o(`invalidate`,n,async()=>{let e=[];for(let t of i)e.push(t.kind===`clear`?this.#p(t.prefixedKey,n):this.#f(t.prefixedKey,n));await Promise.all(e)})}#f(e,t){this.#e+=1;let n=[e,`${e}${f}`];return this.#o(`delete`,t,()=>this.delete(n))}#p(e,t){return this.#e+=1,this.#o(`clear`,t,()=>this.clear(e))}#m(e,n){if(n!==void 0){if(e.startsWith(`${o}:`))throw new t(`Official cache keys and prefixes must be relative and cannot begin with 'viborm:'.`);return`${n}:${e}`}let r=e.startsWith(`${o}:`)?e:e?`${o}:${e}`:o;if(r===i||r.startsWith(`${i}:`))throw new t(`The official cache namespace requires an authenticated cache extension.`);return r}};function executeCachedWithResultCodec(e,t,n,r,i,a,o,s){return executeCachedWithResultCodecFriend(e,t,n,r,i,a,o,s)}function invalidateOfficialCache(e,t,n,r,i){return invalidateOfficialCacheFriend(e,t,n,r,i)}export{readCacheExecutionOutcomes as a,invalidateOfficialCache as i,createOfficialCacheScope as n,_ as o,executeCachedWithResultCodec as r,y as s,CacheDriver as t};
2
- //# sourceMappingURL=driver-CPD0Xxw2.mjs.map
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t,r as n}from"./cache-CIPRF-pz.mjs";import{n as r}from"./v-CrJYqdzu.mjs";import{n as i,r as a,t as o}from"./key-B7vuAYPG.mjs";import{d as s,f as c,t as l}from"./observation-Co72iCd1.mjs";import{o as u}from"./execution-context-rJXTRVrJ.mjs";import{t as d}from"./clock-YTLtjLFS.mjs";const f=`:reval`,p=3e4;function scheduleBackground(e,t){let n=e.catch(()=>void 0);if(t)try{t(n)}catch{}}const m={ms:1,millisecond:1,milliseconds:1,s:1e3,sec:1e3,second:1e3,seconds:1e3,m:60*1e3,min:60*1e3,minute:60*1e3,minutes:60*1e3,h:3600*1e3,hr:3600*1e3,hour:3600*1e3,hours:3600*1e3,d:1440*60*1e3,day:1440*60*1e3,days:1440*60*1e3,w:10080*60*1e3,week:10080*60*1e3,weeks:10080*60*1e3,month:720*60*60*1e3,months:720*60*60*1e3},h=Object.keys(m).join(`, `),g=/^(\d+(?:\.\d+)?)\s*([a-z]+)$/;function parseTTL(e){if(typeof e==`number`){if(!Number.isFinite(e)||e<=0||e>2**53-1)throw new n(`TTL must be positive, got: ${e}`);return e}let t=e.trim().toLowerCase().match(g);if(!t)throw new n(`Invalid TTL format: "${e}". Expected format: "<number> <unit>" (e.g., "1 hour", "20 seconds")`);let r=t[1],i=t[2],a=Number.parseFloat(r),o=m[i];if(o===void 0)throw new n(`Unknown time unit: "${i}". Valid units: ${h}`);let s=Math.floor(a*o);if(!Number.isSafeInteger(s)||s<=0)throw new n(`TTL must be positive, got: ${s}ms from "${e}"`);return s}const _=r.object({invalidate:r.string({array:!0,optional:!0}),autoInvalidate:r.boolean({optional:!0,default:!0})},{optional:!0,default:{autoInvalidate:!0}});function hasCacheInvalidationWork(e){return e===void 0||e.autoInvalidate===!0||e?.invalidate!==void 0&&e.invalidate.length>0}const v=300*1e3,y=r.object({ttl:r.coerce(r.optional(r.union([r.string(),r.number()]),v),e=>parseTTL(e)),swr:r.coerce(r.optional(r.union([r.boolean(),r.string(),r.number()])),e=>e===void 0||typeof e==`boolean`?e:parseTTL(e)),key:r.string({optional:!0}),bypass:r.boolean({optional:!0})},{optional:!0,default:{ttl:v,swr:!1,bypass:!1}});let executeCachedWithResultCodecFriend,invalidateOfficialCacheFriend;const b=new WeakMap,x=new WeakMap,completeWithoutFacts=()=>void 0;function createCacheOutcome(e,t,n){return{event:e,status:t,at:Date.now(),error:n}}function recordCacheOutcome(e,t,n,r){if(e===void 0||l(u(e))?.wants(`cache-outcomes`)!==!0)return;let i=x.get(e);i===void 0&&(i={outcomes:[],completed:!1},x.set(e,i)),i.outcomes.push(createCacheOutcome(t,n,r))}function placeCacheSetFailure(e,t){let n=createCacheOutcome(`miss`,`cache-set-failed`,t),r=x.get(e);if(r!==void 0&&!r.completed){r.outcomes.push(n);return}return Object.freeze({kind:`cache`,outcomes:[n]})}function readCacheExecutionOutcomes(e){let t=x.get(e);if(t!==void 0)return()=>(t.completed=!0,Object.freeze([...t.outcomes]))}function createOfficialCacheScope(e){let t=Object.freeze({});return b.set(t,e),t}function readOfficialCacheNamespace(e){let n=b.get(e);if(n===void 0)throw new t(`Official cache scope is not authentic for this cache execution.`);return n}function refuseExternalScope(e){if(e!==void 0)throw new t(`Cache driver methods do not accept an external cache scope.`)}var CacheDriver=class{#e=0;driverName;clock;static{executeCachedWithResultCodecFriend=(e,t,n,r,i,a,o,s)=>{let c=readOfficialCacheNamespace(s);return e.#t(t,n,r,i,a,o,c)},invalidateOfficialCacheFriend=(e,t,n,r,i)=>e.#d(t,n,r,readOfficialCacheNamespace(i))}constructor(e,t=d){this.driverName=e,this.clock=t}async#t(e,t,n,r,i,o,s){let c=a(e,t,n),l=`${c.key}${i.key===void 0?``:`:${i.key}`}`,u=JSON.stringify([c.identity,i.key]),d=this.#e,executeCore=async()=>{if(i.bypass){let e=await r();return this.#r(l,e,i,o,s,u,d),recordCacheOutcome(i.executionContext,`bypass`),e}let n=await this.#n(l,i.executionContext,s,o,u);if(n){let a=this.clock.now()-n.createdAt;if(!(a>=n.ttl))return recordCacheOutcome(i.executionContext,`hit`),n.value;let c=i.swr;if(c!==!1&&a<c&&(n.expiresAt===void 0||this.clock.now()<n.expiresAt))return scheduleBackground(this.#a(e,t,l,r,i,c,o,s,u,d),i.waitUntil),recordCacheOutcome(i.executionContext,`hit`,`stale`),n.value}let a=await r();return this.#r(l,a,i,o,s,u,d),recordCacheOutcome(i.executionContext,`miss`),a};return executeCore()}async#n(e,t,n,r,i){let a=await this.#s(e,t,n);return a===null||a.identity!==i||!Number.isFinite(a.createdAt)||!Number.isFinite(a.ttl)||a.ttl<=0||a.expiresAt===void 0||!Number.isFinite(a.expiresAt)||a.expiresAt<a.createdAt?null:{createdAt:a.createdAt,ttl:a.ttl,expiresAt:a.expiresAt,value:r.materialize(a.value)}}#r(e,t,n,r,i,a,o){if(o!==this.#e)return;let s;try{s=r.snapshot(t)}catch(e){recordCacheOutcome(n.executionContext,`miss`,`cache-set-failed`,e);return}this.#i(e,s,n,i,a,o)}#i(e,t,n,r,i,a){scheduleBackground(this.#c(e,t,{ttl:n.ttlMs,swrTtl:n.swr===!1?void 0:n.swr},n.executionContext,r,n.executionContext,i,a).catch(()=>void 0),n.waitUntil)}async#a(e,t,n,r,i,a,o,c,l,d){let f;try{f=await this.#l(n,c)}catch{return}if(!f)return;let p=u(i.executionContext)?.observe,m=p===void 0||p.length===0?void 0:{failed:!1,error:void 0},h,doRevalidate=async()=>{let e;try{let t=await r(),s=o.snapshot(t);await this.#c(n,s,{ttl:i.ttlMs,swrTtl:a},i.executionContext,c,void 0,l,d),e=createCacheOutcome(`revalidate`,`success`)}catch(t){m!==void 0&&(m.failed=!0,m.error=t),e=createCacheOutcome(`revalidate`,`error`,t)}finally{if(m===void 0)await this.#u(n,c).catch(()=>void 0);else try{await this.#u(n,c)}catch(e){if(m.failed){let t=m.error;m.error=AggregateError([t,e],`Cache revalidation work and cleanup both failed.`,{cause:t})}else m.failed=!0,m.error=e}}return e};await(m===void 0?doRevalidate():s({kind:`cache`,operation:`revalidate`},p,async()=>{if(h=Object.freeze({kind:`cache`,outcomes:[await doRevalidate()]}),m.failed)throw m.error},void 0,()=>Object.freeze({kind:`cache`,context:i.executionContext,read:Object.freeze({model:e,operation:t,identity:i.driverIdentity}),complete:()=>h})))}#o(e,t,n,r=completeWithoutFacts,i){let a=u(t)?.observe;if(a===void 0||a.length===0)return n();let o=e===`clear`||e===`delete`;return s({kind:`cache`,operation:o?`invalidate`:e},o?c(a):a,n,void 0,()=>Object.freeze(o?{kind:`cache-backend`,boundary:e,driverName:this.driverName,complete:completeWithoutFacts}:{kind:`cache`,context:t,driverName:this.driverName,...i===void 0?{}:{ttl:i},complete:r}))}async _get(e,t,n){return refuseExternalScope(n),this.#s(e,t)}async#s(e,t,n){let r=this.#m(e,n),i;return this.#o(`get`,t,async()=>{let e=await this.get(r);return i=e?this.clock.now()-e.createdAt>e.ttl?`stale`:`hit`:`miss`,e},()=>i===void 0?void 0:Object.freeze({kind:`cache`,result:i}))}async _set(e,t,n,r,i){return refuseExternalScope(i),this.#c(e,t,n,r)}async#c(e,t,n,r,i,a,o,s){if(s!==void 0&&s!==this.#e)return;let c=this.#m(e,i),l={value:t,createdAt:this.clock.now(),ttl:n.ttl,...o===void 0?{}:{identity:o,expiresAt:this.clock.now()+(n.swrTtl??n.ttl)}},u=n.swrTtl??n.ttl;return this.#o(`set`,r,async()=>{await this.set(c,u,l),s!==void 0&&s!==this.#e&&await this.delete([c])},a===void 0?void 0:e=>e.status===`failure`?placeCacheSetFailure(a,e.failure):void 0,n.ttl)}async _delete(e,t,n){refuseExternalScope(n);let r=this.#m(e);return this.#f(r,t)}async _clear(e,t,n){refuseExternalScope(n);let r=this.#m(e??``);return this.#p(r,t)}async _markRevalidating(e,t){return refuseExternalScope(t),this.#l(e)}async#l(e,t){let n=`${this.#m(e,t)}${f}`,r=await this.get(n);if(r&&this.clock.now()-r.createdAt<r.ttl)return!1;let i={value:!0,createdAt:this.clock.now(),ttl:p};return await this.set(n,p,i),!0}async _clearRevalidating(e,t){return refuseExternalScope(t),this.#u(e)}async#u(e,t){let n=`${this.#m(e,t)}${f}`;await this.delete([n])}async _invalidate(e,t,n,r){return refuseExternalScope(r),this.#d(e,t,n)}async#d(e,t,n,r){if(!hasCacheInvalidationWork(t))return;this.#e+=1;let i=[];if((t===void 0||t.autoInvalidate===!0)&&i.push({kind:`clear`,prefixedKey:this.#m(r===void 0?`${e}:`:``,r)}),t?.invalidate)for(let e of t.invalidate){let t=e.endsWith(`*`),n=t?e.slice(0,-1):e;i.push({kind:t?`clear`:`delete`,prefixedKey:this.#m(n,r)})}return this.#o(`invalidate`,n,async()=>{let e=[];for(let t of i)e.push(t.kind===`clear`?this.#p(t.prefixedKey,n):this.#f(t.prefixedKey,n));await Promise.all(e)})}#f(e,t){this.#e+=1;let n=[e,`${e}${f}`];return this.#o(`delete`,t,()=>this.delete(n))}#p(e,t){return this.#e+=1,this.#o(`clear`,t,()=>this.clear(e))}#m(e,n){if(n!==void 0){if(e.startsWith(`${o}:`))throw new t(`Official cache keys and prefixes must be relative and cannot begin with 'viborm:'.`);return`${n}:${e}`}let r=e.startsWith(`${o}:`)?e:e?`${o}:${e}`:o;if(r===i||r.startsWith(`${i}:`))throw new t(`The official cache namespace requires an authenticated cache extension.`);return r}};function executeCachedWithResultCodec(e,t,n,r,i,a,o,s){return executeCachedWithResultCodecFriend(e,t,n,r,i,a,o,s)}function invalidateOfficialCache(e,t,n,r,i){return invalidateOfficialCacheFriend(e,t,n,r,i)}export{readCacheExecutionOutcomes as a,invalidateOfficialCache as i,createOfficialCacheScope as n,_ as o,executeCachedWithResultCodec as r,y as s,CacheDriver as t};
2
+ //# sourceMappingURL=driver-D6_Ik58x.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"driver-CPD0Xxw2.mjs","names":["v","#executeCached","#invalidateScoped","#fillRevision","result","#setResultInBackground","#getCachedResult","#revalidateInBackground","#getScoped","#setInBackground","#setScoped","#markRevalidatingScoped","#clearRevalidatingScoped","#prefixKey","#observe","#deletePrefixed","#clearPrefixed"],"sources":["../src/cache/cache-background.ts","../src/cache/ttl.ts","../src/cache/schema.ts","../src/cache/driver.ts"],"sourcesContent":["import type { WaitUntilFn } from \"./driver\";\n\nexport const REVALIDATING_SUFFIX = \":reval\";\nexport const REVALIDATING_TTL_MS = 30_000;\n\nexport function scheduleBackground(\n promise: Promise<unknown>,\n waitUntil: WaitUntilFn | undefined\n): void {\n const observed = promise.catch(() => undefined);\n if (!waitUntil) return;\n try {\n waitUntil(observed);\n } catch {\n // Background scheduling cannot alter the authoritative query outcome.\n }\n}\n","/**\n * TTL Parser\n *\n * Converts human-readable TTL strings to milliseconds.\n */\n\nimport { CacheInvalidTTLError } from \"@errors\";\n\n/**\n * Time unit multipliers in milliseconds\n */\nconst TIME_UNITS: Record<string, number> = {\n ms: 1,\n millisecond: 1,\n milliseconds: 1,\n s: 1000,\n sec: 1000,\n second: 1000,\n seconds: 1000,\n m: 60 * 1000,\n min: 60 * 1000,\n minute: 60 * 1000,\n minutes: 60 * 1000,\n h: 60 * 60 * 1000,\n hr: 60 * 60 * 1000,\n hour: 60 * 60 * 1000,\n hours: 60 * 60 * 1000,\n d: 24 * 60 * 60 * 1000,\n day: 24 * 60 * 60 * 1000,\n days: 24 * 60 * 60 * 1000,\n w: 7 * 24 * 60 * 60 * 1000,\n week: 7 * 24 * 60 * 60 * 1000,\n weeks: 7 * 24 * 60 * 60 * 1000,\n month: 30 * 24 * 60 * 60 * 1000,\n months: 30 * 24 * 60 * 60 * 1000,\n};\n\nconst VALID_UNITS = Object.keys(TIME_UNITS).join(\", \");\n\n/**\n * Parse a TTL string into milliseconds\n *\n * @example\n * parseTTL(\"1 hour\") // 3600000\n * parseTTL(\"20 seconds\") // 20000\n * parseTTL(\"5m\") // 300000\n * parseTTL(\"2.5 hours\") // 9000000\n * parseTTL(3000) // 3000 (passthrough)\n *\n * @throws CacheInvalidTTLError if format is invalid\n */\nconst TTL_PATTERN = /^(\\d+(?:\\.\\d+)?)\\s*([a-z]+)$/;\n\nexport function parseTTL(ttl: string | number): number {\n if (typeof ttl === \"number\") {\n if (!Number.isFinite(ttl) || ttl <= 0 || ttl > Number.MAX_SAFE_INTEGER) {\n throw new CacheInvalidTTLError(`TTL must be positive, got: ${ttl}`);\n }\n return ttl;\n }\n\n const normalized = ttl.trim().toLowerCase();\n\n // Match patterns like \"1 hour\", \"20seconds\", \"2.5 h\"\n const match = normalized.match(TTL_PATTERN);\n\n if (!match) {\n throw new CacheInvalidTTLError(\n `Invalid TTL format: \"${ttl}\". Expected format: \"<number> <unit>\" (e.g., \"1 hour\", \"20 seconds\")`\n );\n }\n\n const valueStr = match[1] as string;\n const unit = match[2] as string;\n const value = Number.parseFloat(valueStr);\n const multiplier = TIME_UNITS[unit];\n\n if (multiplier === undefined) {\n throw new CacheInvalidTTLError(\n `Unknown time unit: \"${unit}\". Valid units: ${VALID_UNITS}`\n );\n }\n\n const result = Math.floor(value * multiplier);\n\n if (!Number.isSafeInteger(result) || result <= 0) {\n throw new CacheInvalidTTLError(\n `TTL must be positive, got: ${result}ms from \"${ttl}\"`\n );\n }\n\n return result;\n}\n","import v, { type V } from \"@validation/primitives/v\";\nimport { parseTTL } from \"./ttl\";\n\n// =============================================================================\n// CACHE INVALIDATION SCHEMA (for mutations)\n// =============================================================================\n\nexport type CacheInvalidationSchemaEntries = {\n invalidate: V.String<{ array: true; optional: true }>;\n autoInvalidate: V.Boolean<{ optional: true }>;\n};\n\nexport type CacheInvalidationSchema = V.Object<\n CacheInvalidationSchemaEntries,\n { optional: true }\n>;\n\nexport const cacheInvalidationSchema = v.object(\n {\n /**\n * Specific keys to clear from cache\n * Can end with a * to invalidate all keys starting with the given prefix\n */\n invalidate: v.string({ array: true, optional: true }),\n /**\n * Automatically invalidate all entries in the bound cache scope after a durable mutation\n * @default true\n */\n autoInvalidate: v.boolean({ optional: true, default: true }),\n },\n { optional: true, default: { autoInvalidate: true } }\n);\n\n/**\n * Input type for cache invalidation options (inferred from schema)\n */\nexport type CacheInvalidationOptions =\n CacheInvalidationSchema[\" vibInferred\"][\"0\"];\n\n/** Whether normalized mutation options request any invalidation work. */\nexport function hasCacheInvalidationWork(\n options: CacheInvalidationOptions | undefined\n): boolean {\n return (\n options === undefined ||\n options.autoInvalidate === true ||\n (options?.invalidate !== undefined && options.invalidate.length > 0)\n );\n}\n\n// =============================================================================\n// WITH CACHE OPTIONS SCHEMA (for $withCache method)\n// =============================================================================\n\n/**\n * Default TTL: 5 minutes (in milliseconds)\n */\nexport const DEFAULT_CACHE_TTL = 5 * 60 * 1000;\n\nexport type WithCacheSchemaEntries = {\n ttl: V.Optional<V.Union<[V.String, V.Number]>>;\n swr: V.Optional<V.Union<[V.Boolean, V.String, V.Number]>>;\n key: V.String<{ optional: true }>;\n bypass: V.Boolean<{ optional: true }>;\n};\n\nexport type WithCacheSchema = V.Object<\n WithCacheSchemaEntries,\n { optional: true }\n>;\n\nexport const withCacheSchema = v.object(\n {\n /**\n * Time to live for cache entries\n * Can be a number (milliseconds) or a string like \"1 hour\", \"20 seconds\"\n * @default 300000 (5 minutes)\n */\n ttl: v.coerce(\n v.optional(v.union([v.string(), v.number()]), DEFAULT_CACHE_TTL),\n (value: string | number) => {\n return parseTTL(value);\n }\n ),\n /**\n * Enable stale-while-revalidate pattern\n * When true, returns stale data immediately and revalidates in background\n *\n * The value represents the \"stale window\" - how long data can be served stale.\n * Storage TTL is automatically calculated as `ttl + staleWindow`.\n *\n * Can be a boolean or a duration value (number in ms or string like \"1 hour\")\n * - true: stale window = ttl (storage TTL = 2x ttl)\n * - false/undefined: SWR disabled\n * - number/string: custom stale window duration (storage TTL = ttl + swr)\n * @default false\n */\n swr: v.coerce(\n v.optional(v.union([v.boolean(), v.string(), v.number()])),\n (value: boolean | string | number | undefined) => {\n if (value === undefined || typeof value === \"boolean\") {\n return value;\n }\n return parseTTL(value);\n }\n ),\n /**\n * The official cache extension retains the canonical model/operation/args\n * key and appends this value as a suffix contribution.\n */\n key: v.string({ optional: true }),\n /**\n * Bypass cache read and force fresh data\n * Still writes result to cache for subsequent requests\n * @default false\n */\n bypass: v.boolean({ optional: true }),\n },\n {\n optional: true,\n default: {\n ttl: DEFAULT_CACHE_TTL,\n swr: false,\n bypass: false,\n },\n }\n);\n\n/**\n * Input type for $withCache options (inferred from schema)\n */\nexport type WithCacheOptions = WithCacheSchema[\" vibInferred\"][\"0\"];\n","/**\n * Cache Driver\n *\n * Abstract base class for cache implementations.\n * Follows the same pattern as the database Driver class.\n * Handles both storage operations and cache orchestration (hit/miss/stale/SWR).\n */\n\nimport type { DriverIdentity } from \"@drivers/driver-identity\";\nimport { getExecutionExtensionChain } from \"@drivers/execution-context\";\nimport type { QueryExecutionContext } from \"@drivers/exports\";\nimport { CacheInvalidKeyError } from \"@errors\";\nimport {\n getOfficialInstrumentationChainCapability,\n runProtectedObservers,\n selectTrustedObservers,\n} from \"@extensions/observation\";\nimport type {\n CacheCompletionFacts,\n CacheOutcome,\n CacheUnitFacts,\n} from \"@extensions/official-facts\";\nimport { type Clock, systemClock } from \"../clock\";\nimport {\n REVALIDATING_SUFFIX,\n REVALIDATING_TTL_MS,\n scheduleBackground,\n} from \"./cache-background\";\nimport {\n CACHE_PREFIX,\n cacheLookupOf,\n OFFICIAL_CACHE_NAMESPACE_ROOT,\n} from \"./key\";\nimport {\n type CacheInvalidationOptions,\n hasCacheInvalidationWork,\n} from \"./schema\";\n\n/** Extend a request lifetime until background cache work settles. */\nexport type WaitUntilFn = (promise: Promise<unknown>) => void;\n\n/** Cache entry with freshness metadata for stale-while-revalidate. */\nexport interface CacheEntry<T = unknown> {\n value: T;\n createdAt: number;\n ttl: number;\n /** Exact operation identity on official detached entries. */\n identity?: string;\n /** Logical expiry, independent of a backend minimum physical TTL. */\n expiresAt?: number;\n}\n\n/** Storage options for a cache write. */\nexport interface CacheSetOptions {\n /** Time to live in milliseconds. */\n ttl: number;\n /** Storage TTL including the stale window, when SWR is enabled. */\n swrTtl?: number;\n}\n\n/** Parsed options for one cached ORM execution. */\nexport interface CacheExecutionOptions {\n ttlMs: number;\n swr: number | false;\n bypass: boolean;\n key?: string;\n waitUntil?: WaitUntilFn;\n /**\n * The database driver's identity, read once at `$withCache`; absent when\n * that read throws, and the revalidation root is presented without it.\n */\n driverIdentity?: DriverIdentity | undefined;\n executionContext?: QueryExecutionContext;\n}\n\nexport interface DetachedCacheResultCodec<T> {\n snapshot(value: T): unknown;\n materialize(snapshot: unknown): T;\n}\n\ninterface ObservedRevalidationFailure {\n failed: boolean;\n error: unknown;\n}\n\ntype ExecuteCachedWithResultCodec = <T>(\n cache: CacheDriver,\n modelName: string,\n operation: string,\n args: unknown,\n executor: () => Promise<T>,\n options: CacheExecutionOptions,\n codec: DetachedCacheResultCodec<T>,\n scope: object\n) => Promise<T>;\n\nlet executeCachedWithResultCodecFriend: ExecuteCachedWithResultCodec;\n\ntype InvalidateOfficialCache = (\n cache: CacheDriver,\n modelName: string,\n options: CacheInvalidationOptions | undefined,\n context: QueryExecutionContext | undefined,\n scope: object\n) => Promise<void>;\n\nlet invalidateOfficialCacheFriend: InvalidateOfficialCache;\n\nconst officialCacheNamespaces = new WeakMap<object, string>();\n\ninterface CacheOutcomeList {\n readonly outcomes: CacheOutcome[];\n /** Set once the operation completion has read the list. */\n completed: boolean;\n}\n\n/** One outcome list per logical cache execution, keyed by its context. */\nconst executionOutcomes = new WeakMap<\n QueryExecutionContext,\n CacheOutcomeList\n>();\n\nconst completeWithoutFacts = (): undefined => undefined;\n\nfunction createCacheOutcome(\n event: CacheOutcome[\"event\"],\n status?: string,\n error?: unknown\n): CacheOutcome {\n return { event, status, at: Date.now(), error };\n}\n\n/** Record one decision of this execution when its capability wants outcomes. */\nfunction recordCacheOutcome(\n context: QueryExecutionContext | undefined,\n event: CacheOutcome[\"event\"],\n status?: string,\n error?: unknown\n): void {\n if (\n context === undefined ||\n getOfficialInstrumentationChainCapability(\n getExecutionExtensionChain(context)\n )?.wants(\"cache-outcomes\") !== true\n ) {\n return;\n }\n let list = executionOutcomes.get(context);\n if (list === undefined) {\n list = { outcomes: [], completed: false };\n executionOutcomes.set(context, list);\n }\n list.outcomes.push(createCacheOutcome(event, status, error));\n}\n\n/**\n * A background set failure joins its execution's list while that list is still\n * open, so it presents after the logical miss; otherwise it completes the set\n * unit itself.\n */\nfunction placeCacheSetFailure(\n context: QueryExecutionContext,\n failure: unknown\n): CacheCompletionFacts | undefined {\n const outcome = createCacheOutcome(\"miss\", \"cache-set-failed\", failure);\n const list = executionOutcomes.get(context);\n if (list !== undefined && !list.completed) {\n list.outcomes.push(outcome);\n return undefined;\n }\n return Object.freeze({ kind: \"cache\", outcomes: [outcome] });\n}\n\n/** Close and read one execution's outcome list at its operation completion. */\nexport function readCacheExecutionOutcomes(\n context: QueryExecutionContext\n): (() => readonly CacheOutcome[]) | undefined {\n const list = executionOutcomes.get(context);\n if (list === undefined) return undefined;\n return () => {\n list.completed = true;\n return Object.freeze([...list.outcomes]);\n };\n}\n\n/** Create one opaque scope recognized only by this module's private namespace map. */\nexport function createOfficialCacheScope(namespace: string): object {\n const scope = Object.freeze({});\n officialCacheNamespaces.set(scope, namespace);\n return scope;\n}\n\nfunction readOfficialCacheNamespace(scope: object): string {\n const namespace = officialCacheNamespaces.get(scope);\n if (namespace === undefined) {\n throw new CacheInvalidKeyError(\n \"Official cache scope is not authentic for this cache execution.\"\n );\n }\n return namespace;\n}\n\nfunction refuseExternalScope(scope: unknown): void {\n if (scope === undefined) return;\n throw new CacheInvalidKeyError(\n \"Cache driver methods do not accept an external cache scope.\"\n );\n}\n\ninterface PreparedInvalidationTarget {\n readonly kind: \"clear\" | \"delete\";\n readonly prefixedKey: string;\n}\n\n/**\n * Abstract base class for cache drivers.\n *\n * Follows the same pattern as the database Driver class:\n * - Protected abstract methods for concrete implementations (non-underscored)\n * - Public underscored methods handle key prefixing, instrumentation, and delegation\n * - Instrumentation support\n * - Cache orchestration (hit/miss/stale/SWR logic)\n */\nexport abstract class CacheDriver {\n #fillRevision = 0;\n readonly driverName: string;\n /**\n * Every freshness decision this class makes reads from here. Internal seam,\n * not public API: it exists so tests can advance time rather than sleep\n * through a TTL. Defaults to the host clock.\n */\n protected readonly clock: Clock;\n\n static {\n executeCachedWithResultCodecFriend = (\n cache,\n modelName,\n operation,\n args,\n executor,\n options,\n codec,\n scope\n ) => {\n const namespace = readOfficialCacheNamespace(scope);\n return cache.#executeCached(\n modelName,\n operation,\n args,\n executor,\n options,\n codec,\n namespace\n );\n };\n invalidateOfficialCacheFriend = (\n cache,\n modelName,\n options,\n context,\n scope\n ) =>\n cache.#invalidateScoped(\n modelName,\n options,\n context,\n readOfficialCacheNamespace(scope)\n );\n }\n\n constructor(driverName: string, clock: Clock = systemClock) {\n this.driverName = driverName;\n this.clock = clock;\n }\n\n // ============================================================\n // ABSTRACT METHODS - Concrete drivers implement these\n // ============================================================\n\n /**\n * Get a value from cache\n */\n protected abstract get<T>(key: string): Promise<CacheEntry<T> | null>;\n\n /**\n * Set a value in cache\n * @param key - The cache key\n * @param storageTtl - TTL for the backing store (already SWR-compliant)\n * @param entry - Cache entry with user's original TTL for staleness checks\n */\n protected abstract set<T>(\n key: string,\n storageTtl: number,\n entry: CacheEntry<T>\n ): Promise<void>;\n\n /**\n * Delete keys from cache\n * @param keys - Array of keys to delete\n */\n protected abstract delete(keys: string[]): Promise<void>;\n\n /**\n * Clear cache by prefix\n * @param prefix - Always provided (at minimum CACHE_PREFIX to avoid clearing unrelated data)\n */\n protected abstract clear(prefix: string): Promise<void>;\n\n // ============================================================\n // CACHE ORCHESTRATION - Hit/Miss/Stale/SWR logic\n // ============================================================\n\n async #executeCached<T>(\n modelName: string,\n operation: string,\n args: unknown,\n executor: () => Promise<T>,\n options: CacheExecutionOptions,\n codec: DetachedCacheResultCodec<T>,\n namespace: string\n ): Promise<T> {\n const lookup = cacheLookupOf(modelName, operation, args);\n const cacheKey = `${lookup.key}${options.key === undefined ? \"\" : `:${options.key}`}`;\n const identity = JSON.stringify([lookup.identity, options.key]);\n const revision = this.#fillRevision;\n\n // Core execution logic\n const executeCore = async (): Promise<T> => {\n // Bypass cache read if requested\n if (options.bypass) {\n const result = await executor();\n this.#setResultInBackground(\n cacheKey,\n result,\n options,\n codec,\n namespace,\n identity,\n revision\n );\n recordCacheOutcome(options.executionContext, \"bypass\");\n return result;\n }\n\n // Try to get from cache\n const cached = await this.#getCachedResult<T>(\n cacheKey,\n options.executionContext,\n namespace,\n codec,\n identity\n );\n\n if (cached) {\n const age = this.clock.now() - cached.createdAt;\n const isStale = age >= cached.ttl;\n\n if (!isStale) {\n // Fresh cache hit\n recordCacheOutcome(options.executionContext, \"hit\");\n return cached.value;\n }\n\n const swrTtl = options.swr;\n if (\n swrTtl !== false &&\n age < swrTtl &&\n (cached.expiresAt === undefined ||\n this.clock.now() < cached.expiresAt)\n ) {\n // Stale but SWR enabled - return stale and revalidate in background\n scheduleBackground(\n this.#revalidateInBackground(\n modelName,\n operation,\n cacheKey,\n executor,\n options,\n swrTtl,\n codec,\n namespace,\n identity,\n revision\n ),\n options.waitUntil\n );\n recordCacheOutcome(options.executionContext, \"hit\", \"stale\");\n return cached.value;\n }\n\n // Stale and no SWR - fall through to fetch fresh\n }\n\n // Cache miss or stale without SWR - execute query\n const result = await executor();\n this.#setResultInBackground(\n cacheKey,\n result,\n options,\n codec,\n namespace,\n identity,\n revision\n );\n recordCacheOutcome(options.executionContext, \"miss\");\n return result;\n };\n\n return executeCore();\n }\n\n async #getCachedResult<T>(\n key: string,\n context: QueryExecutionContext | undefined,\n namespace: string,\n codec: DetachedCacheResultCodec<T>,\n identity: string\n ): Promise<CacheEntry<T> | null> {\n const cached = await this.#getScoped<unknown>(key, context, namespace);\n return cached === null ||\n cached.identity !== identity ||\n !Number.isFinite(cached.createdAt) ||\n !Number.isFinite(cached.ttl) ||\n cached.ttl <= 0 ||\n cached.expiresAt === undefined ||\n !Number.isFinite(cached.expiresAt) ||\n cached.expiresAt < cached.createdAt\n ? null\n : {\n createdAt: cached.createdAt,\n ttl: cached.ttl,\n expiresAt: cached.expiresAt,\n value: codec.materialize(cached.value),\n };\n }\n\n #setResultInBackground<T>(\n key: string,\n value: T,\n options: CacheExecutionOptions,\n codec: DetachedCacheResultCodec<T>,\n namespace: string,\n identity: string,\n revision: number\n ): void {\n if (revision !== this.#fillRevision) return;\n let stored: unknown;\n try {\n stored = codec.snapshot(value);\n } catch (error) {\n recordCacheOutcome(\n options.executionContext,\n \"miss\",\n \"cache-set-failed\",\n error\n );\n return;\n }\n this.#setInBackground(key, stored, options, namespace, identity, revision);\n }\n\n /**\n * Set cache value in background (non-blocking)\n */\n #setInBackground<T>(\n key: string,\n value: T,\n options: CacheExecutionOptions,\n namespace: string,\n identity: string,\n revision: number\n ): void {\n // The observed set unit presents a failure; without the catch it would\n // become an unhandled rejection.\n const cachePromise = this.#setScoped(\n key,\n value,\n {\n ttl: options.ttlMs,\n swrTtl: options.swr !== false ? options.swr : undefined,\n },\n options.executionContext,\n namespace,\n options.executionContext,\n identity,\n revision\n ).catch(() => undefined);\n\n scheduleBackground(cachePromise, options.waitUntil);\n }\n\n /**\n * Revalidate cache entry in background (for SWR)\n * Uses the backing cache marker for best-effort duplicate suppression.\n */\n async #revalidateInBackground<T>(\n modelName: string,\n operation: string,\n cacheKey: string,\n executor: () => Promise<T>,\n options: CacheExecutionOptions,\n swrTtl: number,\n codec: DetachedCacheResultCodec<T>,\n namespace: string,\n identity: string,\n revision: number\n ): Promise<void> {\n // Check whether another request has already published this marker.\n let shouldRevalidate: boolean;\n try {\n shouldRevalidate = await this.#markRevalidatingScoped(\n cacheKey,\n namespace\n );\n } catch {\n // If marking fails, skip revalidation to avoid request failure\n return;\n }\n if (!shouldRevalidate) {\n // Another request is handling revalidation, skip\n return;\n }\n\n const observers = getExecutionExtensionChain(\n options.executionContext\n )?.observe;\n const observedFailure: ObservedRevalidationFailure | undefined =\n observers === undefined || observers.length === 0\n ? undefined\n : { failed: false, error: undefined };\n // The observed child stores its terminal outcome before it settles, and the\n // rail reads completion facts only after that.\n let completion: CacheCompletionFacts | undefined;\n\n const doRevalidate = async (): Promise<CacheOutcome> => {\n let terminal: CacheOutcome;\n try {\n const result = await executor();\n const stored = codec.snapshot(result);\n await this.#setScoped(\n cacheKey,\n stored,\n {\n ttl: options.ttlMs,\n swrTtl,\n },\n options.executionContext,\n namespace,\n undefined,\n identity,\n revision\n );\n terminal = createCacheOutcome(\"revalidate\", \"success\");\n } catch (error) {\n // Log error but don't throw - this is background operation\n if (observedFailure !== undefined) {\n observedFailure.failed = true;\n observedFailure.error = error;\n }\n terminal = createCacheOutcome(\"revalidate\", \"error\", error);\n } finally {\n if (observedFailure === undefined) {\n await this.#clearRevalidatingScoped(cacheKey, namespace).catch(\n () => undefined\n );\n } else {\n try {\n await this.#clearRevalidatingScoped(cacheKey, namespace);\n } catch (cleanupFailure) {\n if (observedFailure.failed) {\n const workerFailure = observedFailure.error;\n observedFailure.error = new AggregateError(\n [workerFailure, cleanupFailure],\n \"Cache revalidation work and cleanup both failed.\",\n { cause: workerFailure }\n );\n } else {\n observedFailure.failed = true;\n observedFailure.error = cleanupFailure;\n }\n }\n }\n }\n return terminal;\n };\n\n const revalidationPromise =\n observedFailure === undefined\n ? doRevalidate()\n : runProtectedObservers(\n { kind: \"cache\", operation: \"revalidate\" },\n observers,\n async () => {\n completion = Object.freeze({\n kind: \"cache\",\n outcomes: [await doRevalidate()],\n });\n if (observedFailure.failed) throw observedFailure.error;\n },\n undefined,\n (): CacheUnitFacts =>\n Object.freeze({\n kind: \"cache\",\n context: options.executionContext,\n read: Object.freeze({\n model: modelName,\n operation,\n identity: options.driverIdentity,\n }),\n complete: () => completion,\n })\n );\n\n await revalidationPromise;\n }\n\n // ============================================================\n // PUBLIC API - Storage operations\n // ============================================================\n\n /**\n * Run one cache step inside its exact chain's observers. A backend delete or\n * clear has no public unit and reaches only the trusted observer.\n */\n #observe<T>(\n step: \"clear\" | \"delete\" | \"get\" | \"invalidate\" | \"set\",\n context: QueryExecutionContext | undefined,\n execute: () => Promise<T>,\n complete: CacheUnitFacts[\"complete\"] = completeWithoutFacts,\n ttl?: number\n ): Promise<T> {\n const observers = getExecutionExtensionChain(context)?.observe;\n // An unobserved step builds no unit and no facts closure, as the\n // revalidation above does. Measured on a no-op backend: without this, a get\n // allocates about 330 B more and takes about 16 ns longer.\n if (observers === undefined || observers.length === 0) return execute();\n const backend = step === \"clear\" || step === \"delete\";\n return runProtectedObservers(\n { kind: \"cache\", operation: backend ? \"invalidate\" : step },\n backend ? selectTrustedObservers(observers) : observers,\n execute,\n undefined,\n () =>\n Object.freeze(\n backend\n ? {\n kind: \"cache-backend\",\n boundary: step,\n driverName: this.driverName,\n complete: completeWithoutFacts,\n }\n : {\n kind: \"cache\",\n context,\n driverName: this.driverName,\n ...(ttl === undefined ? {} : { ttl }),\n complete,\n }\n )\n );\n }\n\n /**\n * Get a value from cache\n * @param key - Cache key (will be prefixed automatically)\n */\n _get<T>(\n key: string,\n context?: QueryExecutionContext\n ): Promise<CacheEntry<T> | null>;\n async _get<T>(\n key: string,\n context?: QueryExecutionContext,\n externalScope?: unknown\n ): Promise<CacheEntry<T> | null> {\n refuseExternalScope(externalScope);\n return this.#getScoped<T>(key, context);\n }\n\n async #getScoped<T>(\n key: string,\n context?: QueryExecutionContext,\n namespace?: string\n ): Promise<CacheEntry<T> | null> {\n const prefixedKey = this.#prefixKey(key, namespace);\n let cacheResult: \"hit\" | \"miss\" | \"stale\" | undefined;\n\n return this.#observe(\n \"get\",\n context,\n async () => {\n const entry = await this.get<T>(prefixedKey);\n if (entry) {\n const isStale = this.clock.now() - entry.createdAt > entry.ttl;\n cacheResult = isStale ? \"stale\" : \"hit\";\n } else {\n cacheResult = \"miss\";\n }\n return entry;\n },\n () =>\n cacheResult === undefined\n ? undefined\n : Object.freeze({ kind: \"cache\", result: cacheResult })\n );\n }\n\n /**\n * Set a value in cache\n * @param key - Cache key (will be prefixed automatically)\n * @param value - Value to cache\n * @param options - Cache options including TTL\n */\n _set<T>(\n key: string,\n value: T,\n options: CacheSetOptions,\n context?: QueryExecutionContext\n ): Promise<void>;\n async _set<T>(\n key: string,\n value: T,\n options: CacheSetOptions,\n context?: QueryExecutionContext,\n externalScope?: unknown\n ): Promise<void> {\n refuseExternalScope(externalScope);\n return this.#setScoped(key, value, options, context);\n }\n\n async #setScoped<T>(\n key: string,\n value: T,\n options: CacheSetOptions,\n context?: QueryExecutionContext,\n namespace?: string,\n /** The logical execution a background set belongs to, which a failure joins. */\n backgroundOf?: QueryExecutionContext,\n identity?: string,\n revision?: number\n ): Promise<void> {\n if (revision !== undefined && revision !== this.#fillRevision) return;\n const prefixedKey = this.#prefixKey(key, namespace);\n const entry: CacheEntry<T> = {\n value,\n createdAt: this.clock.now(),\n ttl: options.ttl,\n ...(identity === undefined\n ? {}\n : {\n identity,\n expiresAt: this.clock.now() + (options.swrTtl ?? options.ttl),\n }),\n };\n\n // Use SWR TTL if provided, otherwise just use regular TTL\n const storageTtl = options.swrTtl ?? options.ttl;\n\n return this.#observe(\n \"set\",\n context,\n async () => {\n await this.set(prefixedKey, storageTtl, entry);\n // A durable invalidation may finish while a backend set is pending.\n // Suppress this obsolete fill locally; generic KV remains eventual.\n if (revision !== undefined && revision !== this.#fillRevision)\n await this.delete([prefixedKey]);\n },\n backgroundOf === undefined\n ? undefined\n : (outcome) =>\n outcome.status === \"failure\"\n ? placeCacheSetFailure(backgroundOf, outcome.failure)\n : undefined,\n options.ttl\n );\n }\n\n /**\n * Delete a specific key (and its revalidating key)\n * @param key - Cache key (will be prefixed automatically)\n */\n _delete(key: string, context?: QueryExecutionContext): Promise<void>;\n async _delete(\n key: string,\n context?: QueryExecutionContext,\n externalScope?: unknown\n ): Promise<void> {\n refuseExternalScope(externalScope);\n const prefixedKey = this.#prefixKey(key);\n return this.#deletePrefixed(prefixedKey, context);\n }\n\n /**\n * Clear cache by prefix or all within the public unscoped namespace.\n * @param prefix - Optional prefix to clear (will be prefixed automatically)\n */\n _clear(prefix?: string, context?: QueryExecutionContext): Promise<void>;\n async _clear(\n prefix?: string,\n context?: QueryExecutionContext,\n externalScope?: unknown\n ): Promise<void> {\n refuseExternalScope(externalScope);\n const prefixedPrefix = this.#prefixKey(prefix ?? \"\");\n return this.#clearPrefixed(prefixedPrefix, context);\n }\n\n /**\n * Mark entry as revalidating (for SWR coordination)\n * Returns true if this caller should perform revalidation\n * @param key - Cache key (will be prefixed automatically)\n */\n _markRevalidating(key: string): Promise<boolean>;\n async _markRevalidating(\n key: string,\n externalScope?: unknown\n ): Promise<boolean> {\n refuseExternalScope(externalScope);\n return this.#markRevalidatingScoped(key);\n }\n\n async #markRevalidatingScoped(\n key: string,\n namespace?: string\n ): Promise<boolean> {\n const revalidatingKey = `${this.#prefixKey(key, namespace)}${REVALIDATING_SUFFIX}`;\n\n // Check if already revalidating\n const existing = await this.get(revalidatingKey);\n if (existing && this.clock.now() - existing.createdAt < existing.ttl)\n return false;\n\n // Set revalidating flag with short TTL\n const entry: CacheEntry<boolean> = {\n value: true,\n createdAt: this.clock.now(),\n ttl: REVALIDATING_TTL_MS,\n };\n await this.set(revalidatingKey, REVALIDATING_TTL_MS, entry);\n\n return true;\n }\n\n /**\n * Clear revalidating flag\n * @param key - Cache key (will be prefixed automatically)\n */\n _clearRevalidating(key: string): Promise<void>;\n async _clearRevalidating(\n key: string,\n externalScope?: unknown\n ): Promise<void> {\n refuseExternalScope(externalScope);\n return this.#clearRevalidatingScoped(key);\n }\n\n async #clearRevalidatingScoped(\n key: string,\n namespace?: string\n ): Promise<void> {\n const revalidatingKey = `${this.#prefixKey(key, namespace)}${REVALIDATING_SUFFIX}`;\n await this.delete([revalidatingKey]);\n }\n\n /**\n * Invalidate cache entries after a mutation\n * @param modelName - The model name for auto-invalidation\n * @param options - Cache invalidation options\n */\n _invalidate(\n modelName: string,\n options?: CacheInvalidationOptions,\n context?: QueryExecutionContext\n ): Promise<void>;\n async _invalidate(\n modelName: string,\n options?: CacheInvalidationOptions,\n context?: QueryExecutionContext,\n externalScope?: unknown\n ): Promise<void> {\n refuseExternalScope(externalScope);\n return this.#invalidateScoped(modelName, options, context);\n }\n\n async #invalidateScoped(\n modelName: string,\n options?: CacheInvalidationOptions,\n context?: QueryExecutionContext,\n namespace?: string\n ): Promise<void> {\n if (!hasCacheInvalidationWork(options)) return;\n this.#fillRevision += 1;\n const targets: PreparedInvalidationTarget[] = [];\n if (options === undefined || options.autoInvalidate === true) {\n targets.push({\n kind: \"clear\",\n prefixedKey: this.#prefixKey(\n namespace === undefined ? `${modelName}:` : \"\",\n namespace\n ),\n });\n }\n if (options?.invalidate) {\n for (const entry of options.invalidate) {\n const isPrefix = entry.endsWith(\"*\");\n const key = isPrefix ? entry.slice(0, -1) : entry;\n targets.push({\n kind: isPrefix ? \"clear\" : \"delete\",\n prefixedKey: this.#prefixKey(key, namespace),\n });\n }\n }\n return this.#observe(\"invalidate\", context, async () => {\n const promises: Promise<void>[] = [];\n for (const target of targets) {\n promises.push(\n target.kind === \"clear\"\n ? this.#clearPrefixed(target.prefixedKey, context)\n : this.#deletePrefixed(target.prefixedKey, context)\n );\n }\n await Promise.all(promises);\n });\n }\n\n /**\n * Optional: connect to cache backend\n */\n connect?(): Promise<void>;\n\n /**\n * Optional: disconnect from cache backend\n */\n disconnect?(): Promise<void>;\n\n // ============================================================\n // INTERNAL HELPERS\n // ============================================================\n\n #deletePrefixed(\n prefixedKey: string,\n context?: QueryExecutionContext\n ): Promise<void> {\n this.#fillRevision += 1;\n const keys = [prefixedKey, `${prefixedKey}${REVALIDATING_SUFFIX}`];\n return this.#observe(\"delete\", context, () => this.delete(keys));\n }\n\n #clearPrefixed(\n prefixedKey: string,\n context?: QueryExecutionContext\n ): Promise<void> {\n this.#fillRevision += 1;\n return this.#observe(\"clear\", context, () => this.clear(prefixedKey));\n }\n\n /**\n * Prefix a public storage key, or rebase an official relative key into its\n * authenticated extension namespace.\n *\n * An EMPTY relative key is the whole scope — `$invalidate(\"*\")` — and it\n * rebases to `<scope>:`, WITH the separator, because the storage backends\n * clear by `startsWith`. A bare `<scope>` would also match every sibling scope\n * whose namespace string merely extends this one, and one axis of the scope\n * grammar can do that: the cache `version` is the last component and its `s:`\n * body is variable-length, so `version: \"a\"` is a strict prefix of\n * `version: \"ab\"` at the same dialect and namespace. That axis is exactly what\n * §7.1 leaves users to partition SQLite and unbound MySQL databases with, so a\n * clear-all crossing it would empty a physically different database's entries.\n *\n * Adding the separator loses nothing: every key this scope can hold is written\n * through `#executeCached`, whose relative key is always\n * `<model>:<operation>:<hash>`, so no stored key is ever equal to the bare\n * scope. The unscoped arm below deliberately keeps its bare `viborm` root — a\n * public caller CAN store at exactly that key, there is only one such root,\n * and no sibling exists for a clear to cross into.\n */\n #prefixKey(key: string, namespace?: string): string {\n if (namespace !== undefined) {\n if (key.startsWith(`${CACHE_PREFIX}:`)) {\n throw new CacheInvalidKeyError(\n \"Official cache keys and prefixes must be relative and cannot begin with 'viborm:'.\"\n );\n }\n return `${namespace}:${key}`;\n }\n\n const prefixedKey = key.startsWith(`${CACHE_PREFIX}:`)\n ? key\n : key\n ? `${CACHE_PREFIX}:${key}`\n : CACHE_PREFIX;\n if (\n prefixedKey === OFFICIAL_CACHE_NAMESPACE_ROOT ||\n prefixedKey.startsWith(`${OFFICIAL_CACHE_NAMESPACE_ROOT}:`)\n ) {\n throw new CacheInvalidKeyError(\n \"The official cache namespace requires an authenticated cache extension.\"\n );\n }\n return prefixedKey;\n }\n}\n\n/** Internal cache-result seam; absent from the package cache barrel. */\nexport function executeCachedWithResultCodec<T>(\n cache: CacheDriver,\n modelName: string,\n operation: string,\n args: unknown,\n executor: () => Promise<T>,\n options: CacheExecutionOptions,\n codec: DetachedCacheResultCodec<T>,\n scope: object\n): Promise<T> {\n return executeCachedWithResultCodecFriend(\n cache,\n modelName,\n operation,\n args,\n executor,\n options,\n codec,\n scope\n );\n}\n\n/** Internal official invalidation seam; absent from the package cache barrel. */\nexport function invalidateOfficialCache(\n cache: CacheDriver,\n modelName: string,\n options: CacheInvalidationOptions | undefined,\n context: QueryExecutionContext | undefined,\n scope: object\n): Promise<void> {\n return invalidateOfficialCacheFriend(\n cache,\n modelName,\n options,\n context,\n scope\n );\n}\n"],"mappings":"8UAEA,MAAa,EAAsB,SACtB,EAAsB,IAEnC,SAAgB,mBACd,EACA,EACM,CACN,IAAM,EAAW,EAAQ,UAAY,IAAA,GAAU,CAC1C,KACL,GAAI,CACF,EAAU,EAAS,MACb,GCFV,MAAM,EAAqC,CACzC,GAAI,EACJ,YAAa,EACb,aAAc,EACd,EAAG,IACH,IAAK,IACL,OAAQ,IACR,QAAS,IACT,EAAG,GAAK,IACR,IAAK,GAAK,IACV,OAAQ,GAAK,IACb,QAAS,GAAK,IACd,EAAG,KAAU,IACb,GAAI,KAAU,IACd,KAAM,KAAU,IAChB,MAAO,KAAU,IACjB,EAAG,KAAU,GAAK,IAClB,IAAK,KAAU,GAAK,IACpB,KAAM,KAAU,GAAK,IACrB,EAAG,MAAc,GAAK,IACtB,KAAM,MAAc,GAAK,IACzB,MAAO,MAAc,GAAK,IAC1B,MAAO,IAAU,GAAK,GAAK,IAC3B,OAAQ,IAAU,GAAK,GAAK,IAC7B,CAEK,EAAc,OAAO,KAAK,EAAW,CAAC,KAAK,KAAK,CAchD,EAAc,+BAEpB,SAAgB,SAAS,EAA8B,CACrD,GAAI,OAAO,GAAQ,SAAU,CAC3B,GAAI,CAAC,OAAO,SAAS,EAAI,EAAI,GAAO,GAAK,UACvC,MAAM,IAAI,EAAqB,8BAA8B,IAAM,CAErE,OAAO,EAMT,IAAM,EAHa,EAAI,MAAM,CAAC,aAAa,CAGlB,MAAM,EAAY,CAE3C,GAAI,CAA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MADA,OAAA,GAAsB,EACf,MAAA,EAAc,QAAS,MAAe,KAAK,MAAM,EAAY,CAAC,CAwBvE,GAAW,EAAa,EAA4B,CAClD,GAAI,IAAc,IAAA,GAAW,CAC3B,GAAI,EAAI,WAAW,GAAG,EAAa,GAAG,CACpC,MAAM,IAAI,EACR,qFACD,CAEH,MAAO,GAAG,EAAU,GAAG,IAGzB,IAAM,EAAc,EAAI,WAAW,GAAG,EAAa,GAAG,CAClD,EACA,EACE,GAAG,EAAa,GAAG,IACnB,EACN,GACE,IAAgB,GAChB,EAAY,WAAW,GAAG,EAA8B,GAAG,CAE3D,MAAM,IAAI,EACR,0EACD,CAEH,OAAO,IAKX,SAAgB,6BACd,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACY,CACZ,OAAO,mCACL,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACD,CAIH,SAAgB,wBACd,EACA,EACA,EACA,EACA,EACe,CACf,OAAO,8BACL,EACA,EACA,EACA,EACA,EACD"}
1
+ {"version":3,"file":"driver-D6_Ik58x.mjs","names":["v","#executeCached","#invalidateScoped","#fillRevision","result","#setResultInBackground","#getCachedResult","#revalidateInBackground","#getScoped","#setInBackground","#setScoped","#markRevalidatingScoped","#clearRevalidatingScoped","#prefixKey","#observe","#deletePrefixed","#clearPrefixed"],"sources":["../src/cache/cache-background.ts","../src/cache/ttl.ts","../src/cache/schema.ts","../src/cache/driver.ts"],"sourcesContent":["import type { WaitUntilFn } from \"./driver\";\n\nexport const REVALIDATING_SUFFIX = \":reval\";\nexport const REVALIDATING_TTL_MS = 30_000;\n\nexport function scheduleBackground(\n promise: Promise<unknown>,\n waitUntil: WaitUntilFn | undefined\n): void {\n const observed = promise.catch(() => undefined);\n if (!waitUntil) return;\n try {\n waitUntil(observed);\n } catch {\n // Background scheduling cannot alter the authoritative query outcome.\n }\n}\n","/**\n * TTL Parser\n *\n * Converts human-readable TTL strings to milliseconds.\n */\n\nimport { CacheInvalidTTLError } from \"@errors\";\n\n/**\n * Time unit multipliers in milliseconds\n */\nconst TIME_UNITS: Record<string, number> = {\n ms: 1,\n millisecond: 1,\n milliseconds: 1,\n s: 1000,\n sec: 1000,\n second: 1000,\n seconds: 1000,\n m: 60 * 1000,\n min: 60 * 1000,\n minute: 60 * 1000,\n minutes: 60 * 1000,\n h: 60 * 60 * 1000,\n hr: 60 * 60 * 1000,\n hour: 60 * 60 * 1000,\n hours: 60 * 60 * 1000,\n d: 24 * 60 * 60 * 1000,\n day: 24 * 60 * 60 * 1000,\n days: 24 * 60 * 60 * 1000,\n w: 7 * 24 * 60 * 60 * 1000,\n week: 7 * 24 * 60 * 60 * 1000,\n weeks: 7 * 24 * 60 * 60 * 1000,\n month: 30 * 24 * 60 * 60 * 1000,\n months: 30 * 24 * 60 * 60 * 1000,\n};\n\nconst VALID_UNITS = Object.keys(TIME_UNITS).join(\", \");\n\n/**\n * Parse a TTL string into milliseconds\n *\n * @example\n * parseTTL(\"1 hour\") // 3600000\n * parseTTL(\"20 seconds\") // 20000\n * parseTTL(\"5m\") // 300000\n * parseTTL(\"2.5 hours\") // 9000000\n * parseTTL(3000) // 3000 (passthrough)\n *\n * @throws CacheInvalidTTLError if format is invalid\n */\nconst TTL_PATTERN = /^(\\d+(?:\\.\\d+)?)\\s*([a-z]+)$/;\n\nexport function parseTTL(ttl: string | number): number {\n if (typeof ttl === \"number\") {\n if (!Number.isFinite(ttl) || ttl <= 0 || ttl > Number.MAX_SAFE_INTEGER) {\n throw new CacheInvalidTTLError(`TTL must be positive, got: ${ttl}`);\n }\n return ttl;\n }\n\n const normalized = ttl.trim().toLowerCase();\n\n // Match patterns like \"1 hour\", \"20seconds\", \"2.5 h\"\n const match = normalized.match(TTL_PATTERN);\n\n if (!match) {\n throw new CacheInvalidTTLError(\n `Invalid TTL format: \"${ttl}\". Expected format: \"<number> <unit>\" (e.g., \"1 hour\", \"20 seconds\")`\n );\n }\n\n const valueStr = match[1] as string;\n const unit = match[2] as string;\n const value = Number.parseFloat(valueStr);\n const multiplier = TIME_UNITS[unit];\n\n if (multiplier === undefined) {\n throw new CacheInvalidTTLError(\n `Unknown time unit: \"${unit}\". Valid units: ${VALID_UNITS}`\n );\n }\n\n const result = Math.floor(value * multiplier);\n\n if (!Number.isSafeInteger(result) || result <= 0) {\n throw new CacheInvalidTTLError(\n `TTL must be positive, got: ${result}ms from \"${ttl}\"`\n );\n }\n\n return result;\n}\n","import v, { type V } from \"@validation/primitives/v\";\nimport { parseTTL } from \"./ttl\";\n\n// =============================================================================\n// CACHE INVALIDATION SCHEMA (for mutations)\n// =============================================================================\n\nexport type CacheInvalidationSchemaEntries = {\n invalidate: V.String<{ array: true; optional: true }>;\n autoInvalidate: V.Boolean<{ optional: true }>;\n};\n\nexport type CacheInvalidationSchema = V.Object<\n CacheInvalidationSchemaEntries,\n { optional: true }\n>;\n\nexport const cacheInvalidationSchema = v.object(\n {\n /**\n * Specific keys to clear from cache\n * Can end with a * to invalidate all keys starting with the given prefix\n */\n invalidate: v.string({ array: true, optional: true }),\n /**\n * Automatically invalidate all entries in the bound cache scope after a durable mutation\n * @default true\n */\n autoInvalidate: v.boolean({ optional: true, default: true }),\n },\n { optional: true, default: { autoInvalidate: true } }\n);\n\n/**\n * Input type for cache invalidation options (inferred from schema)\n */\nexport type CacheInvalidationOptions =\n CacheInvalidationSchema[\" vibInferred\"][\"0\"];\n\n/** Whether normalized mutation options request any invalidation work. */\nexport function hasCacheInvalidationWork(\n options: CacheInvalidationOptions | undefined\n): boolean {\n return (\n options === undefined ||\n options.autoInvalidate === true ||\n (options?.invalidate !== undefined && options.invalidate.length > 0)\n );\n}\n\n// =============================================================================\n// WITH CACHE OPTIONS SCHEMA (for $withCache method)\n// =============================================================================\n\n/**\n * Default TTL: 5 minutes (in milliseconds)\n */\nexport const DEFAULT_CACHE_TTL = 5 * 60 * 1000;\n\nexport type WithCacheSchemaEntries = {\n ttl: V.Optional<V.Union<[V.String, V.Number]>>;\n swr: V.Optional<V.Union<[V.Boolean, V.String, V.Number]>>;\n key: V.String<{ optional: true }>;\n bypass: V.Boolean<{ optional: true }>;\n};\n\nexport type WithCacheSchema = V.Object<\n WithCacheSchemaEntries,\n { optional: true }\n>;\n\nexport const withCacheSchema = v.object(\n {\n /**\n * Time to live for cache entries\n * Can be a number (milliseconds) or a string like \"1 hour\", \"20 seconds\"\n * @default 300000 (5 minutes)\n */\n ttl: v.coerce(\n v.optional(v.union([v.string(), v.number()]), DEFAULT_CACHE_TTL),\n (value: string | number) => {\n return parseTTL(value);\n }\n ),\n /**\n * Enable stale-while-revalidate pattern\n * When true, returns stale data immediately and revalidates in background\n *\n * The value represents the \"stale window\" - how long data can be served stale.\n * Storage TTL is automatically calculated as `ttl + staleWindow`.\n *\n * Can be a boolean or a duration value (number in ms or string like \"1 hour\")\n * - true: stale window = ttl (storage TTL = 2x ttl)\n * - false/undefined: SWR disabled\n * - number/string: custom stale window duration (storage TTL = ttl + swr)\n * @default false\n */\n swr: v.coerce(\n v.optional(v.union([v.boolean(), v.string(), v.number()])),\n (value: boolean | string | number | undefined) => {\n if (value === undefined || typeof value === \"boolean\") {\n return value;\n }\n return parseTTL(value);\n }\n ),\n /**\n * The official cache extension retains the canonical model/operation/args\n * key and appends this value as a suffix contribution.\n */\n key: v.string({ optional: true }),\n /**\n * Bypass cache read and force fresh data\n * Still writes result to cache for subsequent requests\n * @default false\n */\n bypass: v.boolean({ optional: true }),\n },\n {\n optional: true,\n default: {\n ttl: DEFAULT_CACHE_TTL,\n swr: false,\n bypass: false,\n },\n }\n);\n\n/**\n * Input type for $withCache options (inferred from schema)\n */\nexport type WithCacheOptions = WithCacheSchema[\" vibInferred\"][\"0\"];\n","/**\n * Cache Driver\n *\n * Abstract base class for cache implementations.\n * Follows the same pattern as the database Driver class.\n * Handles both storage operations and cache orchestration (hit/miss/stale/SWR).\n */\n\nimport type { DriverIdentity } from \"@drivers/driver-identity\";\nimport { getExecutionExtensionChain } from \"@drivers/execution-context\";\nimport type { QueryExecutionContext } from \"@drivers/exports\";\nimport { CacheInvalidKeyError } from \"@errors\";\nimport {\n getOfficialInstrumentationChainCapability,\n runProtectedObservers,\n selectTrustedObservers,\n} from \"@extensions/observation\";\nimport type {\n CacheCompletionFacts,\n CacheOutcome,\n CacheUnitFacts,\n} from \"@extensions/official-facts\";\nimport { type Clock, systemClock } from \"../clock\";\nimport {\n REVALIDATING_SUFFIX,\n REVALIDATING_TTL_MS,\n scheduleBackground,\n} from \"./cache-background\";\nimport {\n CACHE_PREFIX,\n cacheLookupOf,\n OFFICIAL_CACHE_NAMESPACE_ROOT,\n} from \"./key\";\nimport {\n type CacheInvalidationOptions,\n hasCacheInvalidationWork,\n} from \"./schema\";\n\n/** Extend a request lifetime until background cache work settles. */\nexport type WaitUntilFn = (promise: Promise<unknown>) => void;\n\n/** Cache entry with freshness metadata for stale-while-revalidate. */\nexport interface CacheEntry<T = unknown> {\n value: T;\n createdAt: number;\n ttl: number;\n /** Exact operation identity on official detached entries. */\n identity?: string;\n /** Logical expiry, independent of a backend minimum physical TTL. */\n expiresAt?: number;\n}\n\n/** Storage options for a cache write. */\nexport interface CacheSetOptions {\n /** Time to live in milliseconds. */\n ttl: number;\n /** Storage TTL including the stale window, when SWR is enabled. */\n swrTtl?: number;\n}\n\n/** Parsed options for one cached ORM execution. */\nexport interface CacheExecutionOptions {\n ttlMs: number;\n swr: number | false;\n bypass: boolean;\n key?: string;\n waitUntil?: WaitUntilFn;\n /**\n * The database driver's identity, read once at `$withCache`; absent when\n * that read throws, and the revalidation root is presented without it.\n */\n driverIdentity?: DriverIdentity | undefined;\n executionContext?: QueryExecutionContext;\n}\n\nexport interface DetachedCacheResultCodec<T> {\n snapshot(value: T): unknown;\n materialize(snapshot: unknown): T;\n}\n\ninterface ObservedRevalidationFailure {\n failed: boolean;\n error: unknown;\n}\n\ntype ExecuteCachedWithResultCodec = <T>(\n cache: CacheDriver,\n modelName: string,\n operation: string,\n args: unknown,\n executor: () => Promise<T>,\n options: CacheExecutionOptions,\n codec: DetachedCacheResultCodec<T>,\n scope: object\n) => Promise<T>;\n\nlet executeCachedWithResultCodecFriend: ExecuteCachedWithResultCodec;\n\ntype InvalidateOfficialCache = (\n cache: CacheDriver,\n modelName: string,\n options: CacheInvalidationOptions | undefined,\n context: QueryExecutionContext | undefined,\n scope: object\n) => Promise<void>;\n\nlet invalidateOfficialCacheFriend: InvalidateOfficialCache;\n\nconst officialCacheNamespaces = new WeakMap<object, string>();\n\ninterface CacheOutcomeList {\n readonly outcomes: CacheOutcome[];\n /** Set once the operation completion has read the list. */\n completed: boolean;\n}\n\n/** One outcome list per logical cache execution, keyed by its context. */\nconst executionOutcomes = new WeakMap<\n QueryExecutionContext,\n CacheOutcomeList\n>();\n\nconst completeWithoutFacts = (): undefined => undefined;\n\nfunction createCacheOutcome(\n event: CacheOutcome[\"event\"],\n status?: string,\n error?: unknown\n): CacheOutcome {\n return { event, status, at: Date.now(), error };\n}\n\n/** Record one decision of this execution when its capability wants outcomes. */\nfunction recordCacheOutcome(\n context: QueryExecutionContext | undefined,\n event: CacheOutcome[\"event\"],\n status?: string,\n error?: unknown\n): void {\n if (\n context === undefined ||\n getOfficialInstrumentationChainCapability(\n getExecutionExtensionChain(context)\n )?.wants(\"cache-outcomes\") !== true\n ) {\n return;\n }\n let list = executionOutcomes.get(context);\n if (list === undefined) {\n list = { outcomes: [], completed: false };\n executionOutcomes.set(context, list);\n }\n list.outcomes.push(createCacheOutcome(event, status, error));\n}\n\n/**\n * A background set failure joins its execution's list while that list is still\n * open, so it presents after the logical miss; otherwise it completes the set\n * unit itself.\n */\nfunction placeCacheSetFailure(\n context: QueryExecutionContext,\n failure: unknown\n): CacheCompletionFacts | undefined {\n const outcome = createCacheOutcome(\"miss\", \"cache-set-failed\", failure);\n const list = executionOutcomes.get(context);\n if (list !== undefined && !list.completed) {\n list.outcomes.push(outcome);\n return undefined;\n }\n return Object.freeze({ kind: \"cache\", outcomes: [outcome] });\n}\n\n/** Close and read one execution's outcome list at its operation completion. */\nexport function readCacheExecutionOutcomes(\n context: QueryExecutionContext\n): (() => readonly CacheOutcome[]) | undefined {\n const list = executionOutcomes.get(context);\n if (list === undefined) return undefined;\n return () => {\n list.completed = true;\n return Object.freeze([...list.outcomes]);\n };\n}\n\n/** Create one opaque scope recognized only by this module's private namespace map. */\nexport function createOfficialCacheScope(namespace: string): object {\n const scope = Object.freeze({});\n officialCacheNamespaces.set(scope, namespace);\n return scope;\n}\n\nfunction readOfficialCacheNamespace(scope: object): string {\n const namespace = officialCacheNamespaces.get(scope);\n if (namespace === undefined) {\n throw new CacheInvalidKeyError(\n \"Official cache scope is not authentic for this cache execution.\"\n );\n }\n return namespace;\n}\n\nfunction refuseExternalScope(scope: unknown): void {\n if (scope === undefined) return;\n throw new CacheInvalidKeyError(\n \"Cache driver methods do not accept an external cache scope.\"\n );\n}\n\ninterface PreparedInvalidationTarget {\n readonly kind: \"clear\" | \"delete\";\n readonly prefixedKey: string;\n}\n\n/**\n * Abstract base class for cache drivers.\n *\n * Follows the same pattern as the database Driver class:\n * - Protected abstract methods for concrete implementations (non-underscored)\n * - Public underscored methods handle key prefixing, instrumentation, and delegation\n * - Instrumentation support\n * - Cache orchestration (hit/miss/stale/SWR logic)\n */\nexport abstract class CacheDriver {\n #fillRevision = 0;\n readonly driverName: string;\n /**\n * Every freshness decision this class makes reads from here. Internal seam,\n * not public API: it exists so tests can advance time rather than sleep\n * through a TTL. Defaults to the host clock.\n */\n protected readonly clock: Clock;\n\n static {\n executeCachedWithResultCodecFriend = (\n cache,\n modelName,\n operation,\n args,\n executor,\n options,\n codec,\n scope\n ) => {\n const namespace = readOfficialCacheNamespace(scope);\n return cache.#executeCached(\n modelName,\n operation,\n args,\n executor,\n options,\n codec,\n namespace\n );\n };\n invalidateOfficialCacheFriend = (\n cache,\n modelName,\n options,\n context,\n scope\n ) =>\n cache.#invalidateScoped(\n modelName,\n options,\n context,\n readOfficialCacheNamespace(scope)\n );\n }\n\n constructor(driverName: string, clock: Clock = systemClock) {\n this.driverName = driverName;\n this.clock = clock;\n }\n\n // ============================================================\n // ABSTRACT METHODS - Concrete drivers implement these\n // ============================================================\n\n /**\n * Get a value from cache\n */\n protected abstract get<T>(key: string): Promise<CacheEntry<T> | null>;\n\n /**\n * Set a value in cache\n * @param key - The cache key\n * @param storageTtl - TTL for the backing store (already SWR-compliant)\n * @param entry - Cache entry with user's original TTL for staleness checks\n */\n protected abstract set<T>(\n key: string,\n storageTtl: number,\n entry: CacheEntry<T>\n ): Promise<void>;\n\n /**\n * Delete keys from cache\n * @param keys - Array of keys to delete\n */\n protected abstract delete(keys: string[]): Promise<void>;\n\n /**\n * Clear cache by prefix\n * @param prefix - Always provided (at minimum CACHE_PREFIX to avoid clearing unrelated data)\n */\n protected abstract clear(prefix: string): Promise<void>;\n\n // ============================================================\n // CACHE ORCHESTRATION - Hit/Miss/Stale/SWR logic\n // ============================================================\n\n async #executeCached<T>(\n modelName: string,\n operation: string,\n args: unknown,\n executor: () => Promise<T>,\n options: CacheExecutionOptions,\n codec: DetachedCacheResultCodec<T>,\n namespace: string\n ): Promise<T> {\n const lookup = cacheLookupOf(modelName, operation, args);\n const cacheKey = `${lookup.key}${options.key === undefined ? \"\" : `:${options.key}`}`;\n const identity = JSON.stringify([lookup.identity, options.key]);\n const revision = this.#fillRevision;\n\n // Core execution logic\n const executeCore = async (): Promise<T> => {\n // Bypass cache read if requested\n if (options.bypass) {\n const result = await executor();\n this.#setResultInBackground(\n cacheKey,\n result,\n options,\n codec,\n namespace,\n identity,\n revision\n );\n recordCacheOutcome(options.executionContext, \"bypass\");\n return result;\n }\n\n // Try to get from cache\n const cached = await this.#getCachedResult<T>(\n cacheKey,\n options.executionContext,\n namespace,\n codec,\n identity\n );\n\n if (cached) {\n const age = this.clock.now() - cached.createdAt;\n const isStale = age >= cached.ttl;\n\n if (!isStale) {\n // Fresh cache hit\n recordCacheOutcome(options.executionContext, \"hit\");\n return cached.value;\n }\n\n const swrTtl = options.swr;\n if (\n swrTtl !== false &&\n age < swrTtl &&\n (cached.expiresAt === undefined ||\n this.clock.now() < cached.expiresAt)\n ) {\n // Stale but SWR enabled - return stale and revalidate in background\n scheduleBackground(\n this.#revalidateInBackground(\n modelName,\n operation,\n cacheKey,\n executor,\n options,\n swrTtl,\n codec,\n namespace,\n identity,\n revision\n ),\n options.waitUntil\n );\n recordCacheOutcome(options.executionContext, \"hit\", \"stale\");\n return cached.value;\n }\n\n // Stale and no SWR - fall through to fetch fresh\n }\n\n // Cache miss or stale without SWR - execute query\n const result = await executor();\n this.#setResultInBackground(\n cacheKey,\n result,\n options,\n codec,\n namespace,\n identity,\n revision\n );\n recordCacheOutcome(options.executionContext, \"miss\");\n return result;\n };\n\n return executeCore();\n }\n\n async #getCachedResult<T>(\n key: string,\n context: QueryExecutionContext | undefined,\n namespace: string,\n codec: DetachedCacheResultCodec<T>,\n identity: string\n ): Promise<CacheEntry<T> | null> {\n const cached = await this.#getScoped<unknown>(key, context, namespace);\n return cached === null ||\n cached.identity !== identity ||\n !Number.isFinite(cached.createdAt) ||\n !Number.isFinite(cached.ttl) ||\n cached.ttl <= 0 ||\n cached.expiresAt === undefined ||\n !Number.isFinite(cached.expiresAt) ||\n cached.expiresAt < cached.createdAt\n ? null\n : {\n createdAt: cached.createdAt,\n ttl: cached.ttl,\n expiresAt: cached.expiresAt,\n value: codec.materialize(cached.value),\n };\n }\n\n #setResultInBackground<T>(\n key: string,\n value: T,\n options: CacheExecutionOptions,\n codec: DetachedCacheResultCodec<T>,\n namespace: string,\n identity: string,\n revision: number\n ): void {\n if (revision !== this.#fillRevision) return;\n let stored: unknown;\n try {\n stored = codec.snapshot(value);\n } catch (error) {\n recordCacheOutcome(\n options.executionContext,\n \"miss\",\n \"cache-set-failed\",\n error\n );\n return;\n }\n this.#setInBackground(key, stored, options, namespace, identity, revision);\n }\n\n /**\n * Set cache value in background (non-blocking)\n */\n #setInBackground<T>(\n key: string,\n value: T,\n options: CacheExecutionOptions,\n namespace: string,\n identity: string,\n revision: number\n ): void {\n // The observed set unit presents a failure; without the catch it would\n // become an unhandled rejection.\n const cachePromise = this.#setScoped(\n key,\n value,\n {\n ttl: options.ttlMs,\n swrTtl: options.swr !== false ? options.swr : undefined,\n },\n options.executionContext,\n namespace,\n options.executionContext,\n identity,\n revision\n ).catch(() => undefined);\n\n scheduleBackground(cachePromise, options.waitUntil);\n }\n\n /**\n * Revalidate cache entry in background (for SWR)\n * Uses the backing cache marker for best-effort duplicate suppression.\n */\n async #revalidateInBackground<T>(\n modelName: string,\n operation: string,\n cacheKey: string,\n executor: () => Promise<T>,\n options: CacheExecutionOptions,\n swrTtl: number,\n codec: DetachedCacheResultCodec<T>,\n namespace: string,\n identity: string,\n revision: number\n ): Promise<void> {\n // Check whether another request has already published this marker.\n let shouldRevalidate: boolean;\n try {\n shouldRevalidate = await this.#markRevalidatingScoped(\n cacheKey,\n namespace\n );\n } catch {\n // If marking fails, skip revalidation to avoid request failure\n return;\n }\n if (!shouldRevalidate) {\n // Another request is handling revalidation, skip\n return;\n }\n\n const observers = getExecutionExtensionChain(\n options.executionContext\n )?.observe;\n const observedFailure: ObservedRevalidationFailure | undefined =\n observers === undefined || observers.length === 0\n ? undefined\n : { failed: false, error: undefined };\n // The observed child stores its terminal outcome before it settles, and the\n // rail reads completion facts only after that.\n let completion: CacheCompletionFacts | undefined;\n\n const doRevalidate = async (): Promise<CacheOutcome> => {\n let terminal: CacheOutcome;\n try {\n const result = await executor();\n const stored = codec.snapshot(result);\n await this.#setScoped(\n cacheKey,\n stored,\n {\n ttl: options.ttlMs,\n swrTtl,\n },\n options.executionContext,\n namespace,\n undefined,\n identity,\n revision\n );\n terminal = createCacheOutcome(\"revalidate\", \"success\");\n } catch (error) {\n // Log error but don't throw - this is background operation\n if (observedFailure !== undefined) {\n observedFailure.failed = true;\n observedFailure.error = error;\n }\n terminal = createCacheOutcome(\"revalidate\", \"error\", error);\n } finally {\n if (observedFailure === undefined) {\n await this.#clearRevalidatingScoped(cacheKey, namespace).catch(\n () => undefined\n );\n } else {\n try {\n await this.#clearRevalidatingScoped(cacheKey, namespace);\n } catch (cleanupFailure) {\n if (observedFailure.failed) {\n const workerFailure = observedFailure.error;\n observedFailure.error = new AggregateError(\n [workerFailure, cleanupFailure],\n \"Cache revalidation work and cleanup both failed.\",\n { cause: workerFailure }\n );\n } else {\n observedFailure.failed = true;\n observedFailure.error = cleanupFailure;\n }\n }\n }\n }\n return terminal;\n };\n\n const revalidationPromise =\n observedFailure === undefined\n ? doRevalidate()\n : runProtectedObservers(\n { kind: \"cache\", operation: \"revalidate\" },\n observers,\n async () => {\n completion = Object.freeze({\n kind: \"cache\",\n outcomes: [await doRevalidate()],\n });\n if (observedFailure.failed) throw observedFailure.error;\n },\n undefined,\n (): CacheUnitFacts =>\n Object.freeze({\n kind: \"cache\",\n context: options.executionContext,\n read: Object.freeze({\n model: modelName,\n operation,\n identity: options.driverIdentity,\n }),\n complete: () => completion,\n })\n );\n\n await revalidationPromise;\n }\n\n // ============================================================\n // PUBLIC API - Storage operations\n // ============================================================\n\n /**\n * Run one cache step inside its exact chain's observers. A backend delete or\n * clear has no public unit and reaches only the trusted observer.\n */\n #observe<T>(\n step: \"clear\" | \"delete\" | \"get\" | \"invalidate\" | \"set\",\n context: QueryExecutionContext | undefined,\n execute: () => Promise<T>,\n complete: CacheUnitFacts[\"complete\"] = completeWithoutFacts,\n ttl?: number\n ): Promise<T> {\n const observers = getExecutionExtensionChain(context)?.observe;\n // An unobserved step builds no unit and no facts closure, as the\n // revalidation above does. Measured on a no-op backend: without this, a get\n // allocates about 330 B more and takes about 16 ns longer.\n if (observers === undefined || observers.length === 0) return execute();\n const backend = step === \"clear\" || step === \"delete\";\n return runProtectedObservers(\n { kind: \"cache\", operation: backend ? \"invalidate\" : step },\n backend ? selectTrustedObservers(observers) : observers,\n execute,\n undefined,\n () =>\n Object.freeze(\n backend\n ? {\n kind: \"cache-backend\",\n boundary: step,\n driverName: this.driverName,\n complete: completeWithoutFacts,\n }\n : {\n kind: \"cache\",\n context,\n driverName: this.driverName,\n ...(ttl === undefined ? {} : { ttl }),\n complete,\n }\n )\n );\n }\n\n /**\n * Get a value from cache\n * @param key - Cache key (will be prefixed automatically)\n */\n _get<T>(\n key: string,\n context?: QueryExecutionContext\n ): Promise<CacheEntry<T> | null>;\n async _get<T>(\n key: string,\n context?: QueryExecutionContext,\n externalScope?: unknown\n ): Promise<CacheEntry<T> | null> {\n refuseExternalScope(externalScope);\n return this.#getScoped<T>(key, context);\n }\n\n async #getScoped<T>(\n key: string,\n context?: QueryExecutionContext,\n namespace?: string\n ): Promise<CacheEntry<T> | null> {\n const prefixedKey = this.#prefixKey(key, namespace);\n let cacheResult: \"hit\" | \"miss\" | \"stale\" | undefined;\n\n return this.#observe(\n \"get\",\n context,\n async () => {\n const entry = await this.get<T>(prefixedKey);\n if (entry) {\n const isStale = this.clock.now() - entry.createdAt > entry.ttl;\n cacheResult = isStale ? \"stale\" : \"hit\";\n } else {\n cacheResult = \"miss\";\n }\n return entry;\n },\n () =>\n cacheResult === undefined\n ? undefined\n : Object.freeze({ kind: \"cache\", result: cacheResult })\n );\n }\n\n /**\n * Set a value in cache\n * @param key - Cache key (will be prefixed automatically)\n * @param value - Value to cache\n * @param options - Cache options including TTL\n */\n _set<T>(\n key: string,\n value: T,\n options: CacheSetOptions,\n context?: QueryExecutionContext\n ): Promise<void>;\n async _set<T>(\n key: string,\n value: T,\n options: CacheSetOptions,\n context?: QueryExecutionContext,\n externalScope?: unknown\n ): Promise<void> {\n refuseExternalScope(externalScope);\n return this.#setScoped(key, value, options, context);\n }\n\n async #setScoped<T>(\n key: string,\n value: T,\n options: CacheSetOptions,\n context?: QueryExecutionContext,\n namespace?: string,\n /** The logical execution a background set belongs to, which a failure joins. */\n backgroundOf?: QueryExecutionContext,\n identity?: string,\n revision?: number\n ): Promise<void> {\n if (revision !== undefined && revision !== this.#fillRevision) return;\n const prefixedKey = this.#prefixKey(key, namespace);\n const entry: CacheEntry<T> = {\n value,\n createdAt: this.clock.now(),\n ttl: options.ttl,\n ...(identity === undefined\n ? {}\n : {\n identity,\n expiresAt: this.clock.now() + (options.swrTtl ?? options.ttl),\n }),\n };\n\n // Use SWR TTL if provided, otherwise just use regular TTL\n const storageTtl = options.swrTtl ?? options.ttl;\n\n return this.#observe(\n \"set\",\n context,\n async () => {\n await this.set(prefixedKey, storageTtl, entry);\n // A durable invalidation may finish while a backend set is pending.\n // Suppress this obsolete fill locally; generic KV remains eventual.\n if (revision !== undefined && revision !== this.#fillRevision)\n await this.delete([prefixedKey]);\n },\n backgroundOf === undefined\n ? undefined\n : (outcome) =>\n outcome.status === \"failure\"\n ? placeCacheSetFailure(backgroundOf, outcome.failure)\n : undefined,\n options.ttl\n );\n }\n\n /**\n * Delete a specific key (and its revalidating key)\n * @param key - Cache key (will be prefixed automatically)\n */\n _delete(key: string, context?: QueryExecutionContext): Promise<void>;\n async _delete(\n key: string,\n context?: QueryExecutionContext,\n externalScope?: unknown\n ): Promise<void> {\n refuseExternalScope(externalScope);\n const prefixedKey = this.#prefixKey(key);\n return this.#deletePrefixed(prefixedKey, context);\n }\n\n /**\n * Clear cache by prefix or all within the public unscoped namespace.\n * @param prefix - Optional prefix to clear (will be prefixed automatically)\n */\n _clear(prefix?: string, context?: QueryExecutionContext): Promise<void>;\n async _clear(\n prefix?: string,\n context?: QueryExecutionContext,\n externalScope?: unknown\n ): Promise<void> {\n refuseExternalScope(externalScope);\n const prefixedPrefix = this.#prefixKey(prefix ?? \"\");\n return this.#clearPrefixed(prefixedPrefix, context);\n }\n\n /**\n * Mark entry as revalidating (for SWR coordination)\n * Returns true if this caller should perform revalidation\n * @param key - Cache key (will be prefixed automatically)\n */\n _markRevalidating(key: string): Promise<boolean>;\n async _markRevalidating(\n key: string,\n externalScope?: unknown\n ): Promise<boolean> {\n refuseExternalScope(externalScope);\n return this.#markRevalidatingScoped(key);\n }\n\n async #markRevalidatingScoped(\n key: string,\n namespace?: string\n ): Promise<boolean> {\n const revalidatingKey = `${this.#prefixKey(key, namespace)}${REVALIDATING_SUFFIX}`;\n\n // Check if already revalidating\n const existing = await this.get(revalidatingKey);\n if (existing && this.clock.now() - existing.createdAt < existing.ttl)\n return false;\n\n // Set revalidating flag with short TTL\n const entry: CacheEntry<boolean> = {\n value: true,\n createdAt: this.clock.now(),\n ttl: REVALIDATING_TTL_MS,\n };\n await this.set(revalidatingKey, REVALIDATING_TTL_MS, entry);\n\n return true;\n }\n\n /**\n * Clear revalidating flag\n * @param key - Cache key (will be prefixed automatically)\n */\n _clearRevalidating(key: string): Promise<void>;\n async _clearRevalidating(\n key: string,\n externalScope?: unknown\n ): Promise<void> {\n refuseExternalScope(externalScope);\n return this.#clearRevalidatingScoped(key);\n }\n\n async #clearRevalidatingScoped(\n key: string,\n namespace?: string\n ): Promise<void> {\n const revalidatingKey = `${this.#prefixKey(key, namespace)}${REVALIDATING_SUFFIX}`;\n await this.delete([revalidatingKey]);\n }\n\n /**\n * Invalidate cache entries after a mutation\n * @param modelName - The model name for auto-invalidation\n * @param options - Cache invalidation options\n */\n _invalidate(\n modelName: string,\n options?: CacheInvalidationOptions,\n context?: QueryExecutionContext\n ): Promise<void>;\n async _invalidate(\n modelName: string,\n options?: CacheInvalidationOptions,\n context?: QueryExecutionContext,\n externalScope?: unknown\n ): Promise<void> {\n refuseExternalScope(externalScope);\n return this.#invalidateScoped(modelName, options, context);\n }\n\n async #invalidateScoped(\n modelName: string,\n options?: CacheInvalidationOptions,\n context?: QueryExecutionContext,\n namespace?: string\n ): Promise<void> {\n if (!hasCacheInvalidationWork(options)) return;\n this.#fillRevision += 1;\n const targets: PreparedInvalidationTarget[] = [];\n if (options === undefined || options.autoInvalidate === true) {\n targets.push({\n kind: \"clear\",\n prefixedKey: this.#prefixKey(\n namespace === undefined ? `${modelName}:` : \"\",\n namespace\n ),\n });\n }\n if (options?.invalidate) {\n for (const entry of options.invalidate) {\n const isPrefix = entry.endsWith(\"*\");\n const key = isPrefix ? entry.slice(0, -1) : entry;\n targets.push({\n kind: isPrefix ? \"clear\" : \"delete\",\n prefixedKey: this.#prefixKey(key, namespace),\n });\n }\n }\n return this.#observe(\"invalidate\", context, async () => {\n const promises: Promise<void>[] = [];\n for (const target of targets) {\n promises.push(\n target.kind === \"clear\"\n ? this.#clearPrefixed(target.prefixedKey, context)\n : this.#deletePrefixed(target.prefixedKey, context)\n );\n }\n await Promise.all(promises);\n });\n }\n\n /**\n * Optional: connect to cache backend\n */\n connect?(): Promise<void>;\n\n /**\n * Optional: disconnect from cache backend\n */\n disconnect?(): Promise<void>;\n\n // ============================================================\n // INTERNAL HELPERS\n // ============================================================\n\n #deletePrefixed(\n prefixedKey: string,\n context?: QueryExecutionContext\n ): Promise<void> {\n this.#fillRevision += 1;\n const keys = [prefixedKey, `${prefixedKey}${REVALIDATING_SUFFIX}`];\n return this.#observe(\"delete\", context, () => this.delete(keys));\n }\n\n #clearPrefixed(\n prefixedKey: string,\n context?: QueryExecutionContext\n ): Promise<void> {\n this.#fillRevision += 1;\n return this.#observe(\"clear\", context, () => this.clear(prefixedKey));\n }\n\n /**\n * Prefix a public storage key, or rebase an official relative key into its\n * authenticated extension namespace.\n *\n * An EMPTY relative key is the whole scope — `$invalidate(\"*\")` — and it\n * rebases to `<scope>:`, WITH the separator, because the storage backends\n * clear by `startsWith`. A bare `<scope>` would also match every sibling scope\n * whose namespace string merely extends this one, and one axis of the scope\n * grammar can do that: the cache `version` is the last component and its `s:`\n * body is variable-length, so `version: \"a\"` is a strict prefix of\n * `version: \"ab\"` at the same dialect and namespace. That axis is exactly what\n * §7.1 leaves users to partition SQLite and unbound MySQL databases with, so a\n * clear-all crossing it would empty a physically different database's entries.\n *\n * Adding the separator loses nothing: every key this scope can hold is written\n * through `#executeCached`, whose relative key is always\n * `<model>:<operation>:<hash>`, so no stored key is ever equal to the bare\n * scope. The unscoped arm below deliberately keeps its bare `viborm` root — a\n * public caller CAN store at exactly that key, there is only one such root,\n * and no sibling exists for a clear to cross into.\n */\n #prefixKey(key: string, namespace?: string): string {\n if (namespace !== undefined) {\n if (key.startsWith(`${CACHE_PREFIX}:`)) {\n throw new CacheInvalidKeyError(\n \"Official cache keys and prefixes must be relative and cannot begin with 'viborm:'.\"\n );\n }\n return `${namespace}:${key}`;\n }\n\n const prefixedKey = key.startsWith(`${CACHE_PREFIX}:`)\n ? key\n : key\n ? `${CACHE_PREFIX}:${key}`\n : CACHE_PREFIX;\n if (\n prefixedKey === OFFICIAL_CACHE_NAMESPACE_ROOT ||\n prefixedKey.startsWith(`${OFFICIAL_CACHE_NAMESPACE_ROOT}:`)\n ) {\n throw new CacheInvalidKeyError(\n \"The official cache namespace requires an authenticated cache extension.\"\n );\n }\n return prefixedKey;\n }\n}\n\n/** Internal cache-result seam; absent from the package cache barrel. */\nexport function executeCachedWithResultCodec<T>(\n cache: CacheDriver,\n modelName: string,\n operation: string,\n args: unknown,\n executor: () => Promise<T>,\n options: CacheExecutionOptions,\n codec: DetachedCacheResultCodec<T>,\n scope: object\n): Promise<T> {\n return executeCachedWithResultCodecFriend(\n cache,\n modelName,\n operation,\n args,\n executor,\n options,\n codec,\n scope\n );\n}\n\n/** Internal official invalidation seam; absent from the package cache barrel. */\nexport function invalidateOfficialCache(\n cache: CacheDriver,\n modelName: string,\n options: CacheInvalidationOptions | undefined,\n context: QueryExecutionContext | undefined,\n scope: object\n): Promise<void> {\n return invalidateOfficialCacheFriend(\n cache,\n modelName,\n options,\n context,\n scope\n );\n}\n"],"mappings":"8UAEA,MAAa,EAAsB,SACtB,EAAsB,IAEnC,SAAgB,mBACd,EACA,EACM,CACN,IAAM,EAAW,EAAQ,UAAY,IAAA,GAAU,CAC1C,KACL,GAAI,CACF,EAAU,EAAS,MACb,GCFV,MAAM,EAAqC,CACzC,GAAI,EACJ,YAAa,EACb,aAAc,EACd,EAAG,IACH,IAAK,IACL,OAAQ,IACR,QAAS,IACT,EAAG,GAAK,IACR,IAAK,GAAK,IACV,OAAQ,GAAK,IACb,QAAS,GAAK,IACd,EAAG,KAAU,IACb,GAAI,K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import{i as t,o as n}from"./value-guards-CK9guf2Z.mjs";import{_ as r,d as i,f as a,g as o,h as s,i as c,l,n as u,p as d,r as f,t as p}from"./bind-parameter-capacity-qfEejeOX.mjs";import{S as m,b as h,i as g,m as _,n as v,s as y,t as b}from"./base-D3m1S7Uc.mjs";import{c as x,f as S,g as C,m as w,n as T,o as E,r as D,s as O,u as ee}from"./error-mapping-C9WgitPi.mjs";import{i as k,m as A,p as j,r as M}from"./validation-BamBwne9.mjs";import{n as N}from"./transaction-4dfqals6.mjs";import{r as P,t as F}from"./sql-Bhxq9arK.mjs";import{a as I,r as te,t as ne}from"./observation-Co72iCd1.mjs";import{n as L}from"./suppressed-failure-Bdo2aK81.mjs";import{a as R,c as z,o as B,t as V}from"./execution-context-rJXTRVrJ.mjs";import{t as H}from"./clock-C24RcpwO.mjs";import{t as U}from"./settle-CS_k6Ztm.mjs";function applyStatementTransforms(e,n,r,i){if(i===void 0||i.length===0)return e;let a=e;for(let e of i){let i=Object.freeze({statement:a,model:n,operation:r}),o;try{o=Reflect.apply(e.handler,void 0,[i])}catch(t){throw statementTransformFailure(e.extension,n,r,`threw`,normalizeThrown(t))}try{if(P(o)){let e=Reflect.get(o,`toStatement`);if(!t(e))throw TypeError(`Statement transform returned a Sql value without a callable toStatement method`);if(typeof Reflect.apply(e,o,[`?`])!=`string`)throw TypeError(`Statement transform returned a Sql value whose toStatement method did not return a string`);a=o;continue}}catch(t){throw statementTransformFailure(e.extension,n,r,`returned an unreadable value`,normalizeUnreadableReturn(t))}let s;try{s=isThenable(o)}catch(t){throw statementTransformFailure(e.extension,n,r,`returned an unreadable value`,normalizeUnreadableReturn(t))}let c=s?`returned a promise or thenable`:`returned a non-Sql value`;throw statementTransformFailure(e.extension,n,r,c,TypeError(`Statement transform ${c}`))}return a}function isThenable(e){return n(e)||t(e)?t(Reflect.get(e,`then`)):!1}function normalizeThrown(e){return m(e)?e:Error(`Statement transform threw a non-Error value`)}function normalizeUnreadableReturn(e){return m(e)?e:Error(`Statement transform returned an unreadable value`)}function statementTransformFailure(e,t,n,r,i){return new j(`Extension "${e}" statement handler for ${t===void 0?n:`${t}.${n}`} ${r}.`,{cause:i,meta:{method:`statement`,model:t,operation:n}})}var NumberedSql=class extends F{#e;#t;constructor(e,t){super([``],[]);let n=e.strings,r=[],i=new Map,a=n[0];for(let[o,s]of e.values.entries()){let e=s instanceof Date?`date:${s.getTime()}`:s===null||typeof s!=`object`&&typeof s!=`function`?`${typeof s}:${String(s)}`:s,c=i.get(e);c===void 0&&(c=r.push(s),i.set(e,c)),a+=`${t}${c}${n[o+1]}`}this.#e=a,this.#t=r}get values(){return this.#t}toStatement(){return this.#e}};const W=Symbol(`viborm.batchDiagnosticParams`),G=[];Object.freeze(G);function snapshotDiagnosticParameters(e){let t=_(e,{includeParams:!0,includeSql:!0});return Object.freeze(t),t}function findUniqueExecutionContextIndex(e,t){if(!g(e))return t.length===1?0:void 0;let n=readTrustedErrorExecutionContext(e);if(!n?.correlationId)return t.length===1?0:void 0;let r;for(let e=0;e<t.length;e+=1){let i=t[e]?.context;if(i&&i.correlationId===n.correlationId&&i.model===n.model&&i.operation===n.operation){if(r!==void 0)return;r=e}}return r}function findUniqueErrorLogDetails(e,t){if(!t)return;let n=findUniqueExecutionContextIndex(e,t);return n===void 0?void 0:t[n]}function getErrorExecutionContext(e,t){return g(e)?z(readTrustedErrorExecutionContext(e),t,t.operation):t}function readTrustedErrorExecutionContext(e){let t=b.prototype.toJSON.call(e).meta;if(n(t))return{model:typeof t.model==`string`?t.model:void 0,operation:typeof t.operation==`string`?t.operation:void 0,correlationId:typeof t.correlationId==`string`?t.correlationId:void 0}}var SavepointQueue=class{queue=[];head=0;processing=!1;enqueue(e,t){return new Promise((n,r)=>{let i=!1,a;t&&(a=setTimeout(()=>{i=!0,r(t.onMaxWaitExceeded())},t.maxWaitMs)),this.queue.push(async()=>{if(a&&clearTimeout(a),!i)try{n(await e())}catch(e){r(e)}}),this.scheduleFlush()})}run(e,t){if(this.processing)return this.enqueue(e,t);this.processing=!0;let n=e(),release=()=>this.flush();return n.then(release,release),n}scheduleFlush(){this.processing||(this.processing=!0,queueMicrotask(()=>this.flush()))}async flush(){for(;this.head<this.queue.length;){let e=this.queue[this.head++];e&&await e()}this.queue=[],this.head=0,this.processing=!1}};function readOptionOnce(e,t){try{return Object.hasOwn(e,t)?Reflect.get(e,t):void 0}catch(e){throw new M(`The "${t}" option could not be read.`,{cause:h(e)})}}function resolveNamespaceOption(e){let t=readOptionOnce(e,`namespace`);if(t===void 0||typeof t==`string`)return t;throw new M(`The "namespace" option must be a string; received type "${typeof t}".`)}function resolveAttestationOption(e,t,n){let r=readOptionOnce(e,t);if(r!==void 0){if(r===n)return n;throw new M(`The "${t}" option admits only "${n}".`)}}function resolveMigrationNamespaceAttestationOption(e){return resolveAttestationOption(e,`migrationNamespaceAttestation`,`non-redirecting`)}function resolveMigrationSessionAttestationOption(e){return resolveAttestationOption(e,`migrationSessionAttestation`,`dedicated-session`)}function refuseEmptyDatabaseUrl(e,t,n){if(!(n||t.databaseUrl||!Object.hasOwn(t,`databaseUrl`)))throw new M(`Driver "${e}" was given an empty databaseUrl and no host; set the URL or name the host in options.`,{meta:{driver:e,operation:`configuration`}})}function systemRootAsVerifyFull(e){let t;try{t=new URL(e)}catch{return e}return t.searchParams.get(`sslrootcert`)===`system`?(t.searchParams.delete(`sslrootcert`),t.searchParams.set(`sslmode`,`verify-full`),t.href):e}function defineImmutableDriverFact(e,t,n){Object.defineProperty(e,t,{value:n,writable:!1,enumerable:!0,configurable:!1})}const K={schema:!0,skipSchemaValidation:!0};function refuseUnknownDriverConfigKeys(e,t,n,r={}){for(let i of Object.keys(e)){if(Object.hasOwn(K,i)||Object.hasOwn(n,i))continue;let e=Object.hasOwn(r,i)?r[i]:void 0,a=[...Object.keys(K),...Object.keys(n)];throw new M(`viborm/${t} does not accept "${i}"; ${e??`it accepts ${a.join(`, `)}`}.`,{meta:{driver:t,operation:`configuration`}})}}const q=Object.freeze({execute:(e,t)=>t()}),J=Object.freeze({execute:e=>e()});function createDeferredDispatch(){let e,t=new Promise(t=>{e=t}),n=!1,settleDispatch=t=>{n||(n=!0,e?.(t))},execute=(e,t)=>{let n,r,i=new Promise((e,t)=>{n=e,r=t}),a=!1,start=()=>{if(a)return;a=!0;let e;try{e=t()}catch(e){r?.(e);return}e.then(n,r)};return settleDispatch(e(start)),i};return Object.freeze({dispatch:t,execute,settleSkipped:()=>settleDispatch(void 0)})}var Y=class DriverInstrumentationBase{supportsTransactions=!0;supportsBatch=!1;supportsOrderedCommittedSegments=!1;maxBindParametersPerStatement=void 0;driverName;result;client=null;inTransaction=!1;serializeTransactions=!1;connectionQueue=new SavepointQueue;initPromise=null;closeRetryClient=null;isDisconnecting=!1;transactionPoisonError;boundContext;transactionOptionSupport(){return{isolationLevel:`unsupported`,isolationLevelReason:`this driver has not declared an isolation-level contract`,timeout:!1,timeoutReason:`this driver has not declared a timeout contract`,maxWait:`unsupported`,maxWaitReason:`this driver has not declared a maxWait contract`}}constructor(e,t,n={},r){defineImmutableDriverFact(this,`dialect`,e),this.driverName=t,this.boundContext=z(n),defineImmutableDriverFact(this,`migrationNamespaceAttestation`,r)}get numbersPlaceholders(){return!0}applyTrustedStatementTransforms(e,t,n){let r=(B(t)??B(this.boundContext))?.statement,i=e;if(r!==void 0&&r.length>0){let a=this.resolveExecutionContext(t,n);i=applyStatementTransforms(e,a.model,a.operation??n,r)}let a=u(this.maxBindParametersPerStatement);return a!==void 0&&i.values.length>a&&this.dialect!==`mysql`&&this.numbersPlaceholders&&(i=new NumberedSql(i,this.dialect===`postgresql`?`$`:`?`)),p(i,this.driverName,a,`operation`),i}hasTrustedObservers(e){return((B(e)??B(this.boundContext))?.observe.length??0)>0}observeTrustedStatement(e,t,n){let r=B(e)?.observe;if(r===void 0||r.length===0)return t(void 0);let i=this.createOfficialStatementExecutionGate(e);return I(r,e.operation,e.model,()=>t(i),n,i?.readFacts)}observeTrustedDriverLifecycle(e,t,n,r,i){let a=B(t)?.observe;if(a===void 0||a.length===0)return r(void 0);let o=readOfficialCapability(t),s=o?.observesLifecycle===!0&&o.wants(n)?this.createOfficialDriverLifecycleExecutionGate(t,n):void 0;return te(e,a,t.operation,()=>r(s),i,s?.readFacts)}materializeTrustedBatchQuery(e,t){let n=i(e);if(n===void 0)return e;let r=this.applyTrustedStatementTransforms(n,t,`executeBatch`);return{sql:this.buildStatement(r),params:l(r.values,t),...e.context===void 0?{}:{context:e.context}}}observeTrustedBatchStatements(e,t,n,r){let i=B(t)?.observe;if(i===void 0||i.length===0)return n(e.map(e=>this.materializeTrustedBatchQuery(e,e.context??t)),void 0);let a=this.createOfficialStatementExecutionGate(t),o=!1,s=[],startAt=c=>{for(let n=c;n<e.length;n+=1){let c=e[n];if(c===void 0)continue;let l=c.context??t,u=o?void 0:a?.readFacts;return o=!0,I(i,l.operation,l.model,()=>(s.push(this.materializeTrustedBatchQuery(c,l)),startAt(n+1)),r,u)}return n(s,a)};return startAt(0)}createOfficialStatementExecutionGate(e){let t=readOfficialCapability(e);if(t?.observesLifecycle!==!0||!(t.wants(`statement`)||t.wants(`query-log`)||t.wants(`error-log`)))return;let n=createDeferredDispatch(),r,i=Object.freeze({kind:`statement`,dispatch:n.dispatch,complete:e=>{if(r===void 0){n.settleSkipped();return}let t=e.status===`failure`&&e.failure instanceof Error?e.failure:void 0;if(e.status===`failure`&&t===void 0)return;let i=t===void 0||r.forceErrorContext?void 0:findUniqueErrorLogDetails(t,r.members),a=i?.context??(t===void 0||r.forceErrorContext?r.context:getErrorExecutionContext(t,r.context)),o=readOfficialCapability(a);if(o===void 0)return;let s=o.wants(t===void 0?`query-log`:`error-log`);if(s||t&&o.wants(`statement`))return t!==void 0&&s&&C(t),Object.freeze({kind:`statement`,endedAt:Date.now(),capability:o,...s?{}:{skipLog:!0},context:a,sql:i?.sql??r.sql,params:i?.params??r.params,...t===void 0?{}:{failure:t}})}});return Object.freeze({readFacts:()=>i,execute:(e,t)=>n.execute(t=>(r=Object.freeze({...e,driver:this,startedAt:Date.now(),start:t}),r),t)})}createOfficialDriverLifecycleExecutionGate(e,t){let n=createDeferredDispatch(),r=Object.freeze({kind:`driver-lifecycle`,dispatch:n.dispatch,complete:e=>(n.settleSkipped(),e.status===`failure`&&e.failure instanceof Error?Object.freeze({kind:`driver-lifecycle`,failure:e.failure}):void 0)});return Object.freeze({readFacts:()=>r,execute:r=>n.execute(n=>Object.freeze({driver:this,context:e,boundary:t,start:n}),r)})}buildStatement(e){switch(this.dialect){case`postgresql`:return e.toStatement(`$n`);case`sqlite`:case`mysql`:return e.toStatement(`?`);default:return e.toStatement()}}getBatchDiagnosticParameters(e){try{let t=Reflect.get(e,W);return Array.isArray(t)?t:this.getDiagnosticParameters(e.params??[],e.context)}catch{return this.getDiagnosticParameters(e.params??[],e.context)}}getDiagnosticParameters(e,t,n){return this.canDiscloseParameters(t)||n!==void 0&&n!==t&&this.canDiscloseParameters(n)?snapshotDiagnosticParameters(e):G}connectedClient(){if(!(this.getClient!==DriverInstrumentationBase.prototype.getClient||this.transactionPoisonError||this.isDisconnecting||this.closeRetryClient!==null))return this.client??void 0}async getClient(e={}){if(this.transactionPoisonError||this.isDisconnecting||this.closeRetryClient!==null)throw this.unavailableClientError(e);return this.client?this.client:await this.initializeClient(e)}unavailableClientError(e){return this.transactionPoisonError?new N(`Driver "${this.driverName}" is unavailable after transaction cleanup failed.`,{cause:this.transactionPoisonError,meta:{driver:this.driverName,model:e.model,operation:e.operation,correlationId:e.correlationId}}):this.connectionClosedError(this.isDisconnecting?`Database connection is closing`:`Database connection cleanup is incomplete`,e)}connectionClosedError(e,t){return new k(e,{code:v.CONNECTION_CLOSED,diagnostics:this.getErrorDisclosure(t),meta:{driver:this.driverName,model:t.model,operation:t.operation,correlationId:t.correlationId}})}async initializeClient(e){this.initPromise||=Promise.resolve().then(()=>this.initClient()).then(e=>(this.client=e,e));try{return await this.initPromise}catch(t){throw T(t,{driverName:this.driverName,model:e.model,operation:e.operation,correlationId:e.correlationId,callsite:R(e),diagnostics:this.getErrorDisclosure(e)})}}normalizeStatementFailure(e,t,n,r,i){return D(e,{driverName:this.driverName,dialect:this.dialect,model:r.model,operation:r.operation,correlationId:r.correlationId,callsite:R(r),query:t,params:n,diagnostics:this.getErrorDisclosure(r),forceContext:i})}async executeNormalizedStatement(e,t,n,r,i){try{return await r()}catch(r){throw this.normalizeStatementFailure(r,e,t,n,i)}}resolveExecutionContext(e,t){return z(e,this.boundContext,t)}canDiscloseParameters(e){let t=readOfficialCapability(e);return t!==void 0&&(t.diagnostics.includeParams===!0||t.wants(`parameters`))}getErrorDisclosure(e){return readOfficialCapability(e)?.diagnostics??y}};function readOfficialCapability(e){return ne(B(e))}const X=[`ReadUncommitted`,`ReadCommitted`,`RepeatableRead`,`Serializable`],methodForForm=e=>e===`batch`?`$transaction([...])`:`$transaction(callback)`;function invalidTransactionOptions(e,t){return new N(e,{code:v.INVALID_TRANSACTION_INPUT,meta:{driver:t.driverName,method:methodForForm(t.form)}})}function refuseTransactionOption(e,t,n){return new A(`Driver "${n.driverName}" cannot honor the "${e}" transaction option on ${methodForForm(n.form)}: ${t}`,{meta:{driver:n.driverName,method:methodForForm(n.form)}})}function transactionTimeoutError(e,t){return new N(`Transaction on driver "${t.driverName}" exceeded its timeout of ${e}ms and was rolled back.`,{code:v.TRANSACTION_TIMEOUT,meta:{driver:t.driverName,method:methodForForm(t.form)}})}function transactionMaxWaitError(e,t){return new N(`Transaction on driver "${t.driverName}" waited longer than maxWait (${e}ms) for a transaction slot and never started.`,{code:v.TRANSACTION_TIMEOUT,meta:{driver:t.driverName,method:methodForForm(t.form)}})}const isIsolationLevel=e=>X.includes(e);function readDurationOption(e,t,n){if(typeof e!=`number`||!Number.isFinite(e)||e<=0)throw invalidTransactionOptions(`Transaction option "${t}" must be a positive finite number of milliseconds.`,n);return e}function parseTransactionOptions(e,t){if(e===void 0)return;if(!n(e))throw invalidTransactionOptions(`Transaction options must be an object.`,t);let r=t.form===`batch`?[`isolationLevel`]:[`isolationLevel`,`timeout`,`maxWait`];for(let n of Reflect.ownKeys(e))if(!(typeof n==`string`&&r.includes(n)))throw t.form===`batch`&&(n===`timeout`||n===`maxWait`)?invalidTransactionOptions(`Transaction option "${n}" is not available on $transaction([...]): an array of operations has no interactive window to bound. Use the callback form.`,t):invalidTransactionOptions(`Unknown transaction option "${String(n)}". Supported options are ${r.map(e=>`"${e}"`).join(`, `)}.`,t);let i={};if(e.isolationLevel!==void 0){if(!isIsolationLevel(e.isolationLevel))throw invalidTransactionOptions(`Unknown isolation level ${JSON.stringify(e.isolationLevel)}. Supported levels are ${X.map(e=>`"${e}"`).join(`, `)}.`,t);i.isolationLevel=e.isolationLevel}return e.timeout!==void 0&&(i.timeout=readDurationOption(e.timeout,`timeout`,t)),e.maxWait!==void 0&&(i.maxWait=readDurationOption(e.maxWait,`maxWait`,t)),i}const re={ReadUncommitted:`READ UNCOMMITTED`,ReadCommitted:`READ COMMITTED`,RepeatableRead:`REPEATABLE READ`,Serializable:`SERIALIZABLE`};function isolationLevelStatement(e){return`SET TRANSACTION ISOLATION LEVEL ${re[e]}`}function resolveIsolationLevel(e,t,n){switch(t.isolationLevel){case`provider`:return{placement:`provider`};case`post-begin`:case`pre-begin`:return{placement:t.isolationLevel,statement:isolationLevelStatement(e)};case`serializable-only`:if(e===`Serializable`)return{placement:`serializable-only`};throw refuseTransactionOption(`isolationLevel`,`${e} is not available — ${t.isolationLevelReason??`this driver offers Serializable only`}.`,n);default:throw refuseTransactionOption(`isolationLevel`,t.isolationLevelReason??`this driver does not open a transaction that can be configured`,n)}}function resolveTransactionPlan(e,t,n){if(!e||e.isolationLevel===void 0&&e.timeout===void 0&&e.maxWait===void 0)return;let r=`unsupported`,i;if(e.isolationLevel!==void 0){let a=resolveIsolationLevel(e.isolationLevel,t,n);r=a.placement,i=a.statement}if(e.timeout!==void 0&&!t.timeout)throw refuseTransactionOption(`timeout`,t.timeoutReason??`this driver does not run an interactive callback that could be interrupted`,n);if(e.maxWait!==void 0&&t.maxWait===`unsupported`)throw refuseTransactionOption(`maxWait`,t.maxWaitReason??`this driver has no transaction-slot wait that VibORM can bound`,n);let a={};return r===`pre-begin`&&e.isolationLevel!==void 0&&(a.isolationLevel=e.isolationLevel),t.maxWait===`acquisition`&&e.maxWait!==void 0&&(a.maxWaitMs=e.maxWait),{...e.isolationLevel===void 0?{}:{isolationLevel:e.isolationLevel},...i===void 0?{}:{isolationStatement:i},isolationPlacement:r,...e.timeout===void 0?{}:{timeoutMs:e.timeout},...e.maxWait===void 0?{}:{maxWaitMs:e.maxWait},maxWaitMode:t.maxWait,...Object.keys(a).length===0?{}:{driverOptions:a}}}async function runWithTransactionTimeout(e,t,n,r=H){return U(e(),t,()=>transactionTimeoutError(t,n),void 0,r)}async function acquireWithMaxWait(e,t,n,r,i=H){let a=e();return n===void 0?a:U(a,n,()=>transactionMaxWaitError(n,r),e=>{try{t(e)}catch{}},i)}const Z=new WeakMap;let Q,$;function physicalConnectionQueue(e){let t=Z.get(e);return t||(t=new SavepointQueue,Z.set(e,t)),t}function isConnectionScope(e){let t=Q?.getStore();return t!==void 0&&t.queue===e&&t.active}function connectionQueueWait(e,t){let n=e??(Q===null?5e3:void 0);return n===void 0?void 0:{maxWaitMs:n,onMaxWaitExceeded:()=>transactionMaxWaitError(n,t)}}async function withConnectionScope(e,t){if($??=import(`node:async_hooks`).then(({AsyncLocalStorage:e})=>{Q=new e}).catch(()=>{Q=null}),await $,Q===null)return t();if(!Q)throw Error(`Connection scope failed to initialize`);let n={queue:e,active:!0};return Q.run(n,async()=>{try{return await t()}finally{n.active=!1}})}function prepareAtomicBatch(e,t,n,r){let i=[],a=e.map(e=>{let r=e.params,a=z(e.context,t,`executeBatch`),c=r?l(r,a):void 0;c&&Object.freeze(c);let u={sql:e.sql,...c?{params:c}:{},context:a};s(e)&&(u=o(u)),d(e,u,c??[]);let f=n(c??[],a);return i.push(f),Object.defineProperty(u,W,{configurable:!1,enumerable:!1,value:f,writable:!1}),Object.freeze(u)}),c=a.map((e,n)=>({context:e.context??t,params:i[n]??G,sql:e.sql})),u=r?i:G;return r&&Object.freeze(u),{queries:a,diagnosticParams:u,members:c}}function toTransactionOperationError(e){return e instanceof Error?e:new N(`Transaction operation failed`,{cause:Error(`A transaction operation rejected without an Error`)})}function normalizeTransactionLifecycleError(e,t){try{if(!(e instanceof AggregateError))return t(e);let n=e.cause;return e.errors[0]===n?x(t(n),e.errors.slice(1).map(e=>t(e))):t(e)}catch{return t(e)}}function withoutTimeout(e){if(!e)return e;let{timeout:t,...n}=e;return n}var DriverTransactionBase=class extends Y{runTransactionBody(e){return e()}assertBaseOperationAllowedDuringTransaction(e){if(isConnectionScope(this.connectionQueue))throw this.transactionBoundError(e)}transactionBoundError(e){return new N(`Driver "${this.driverName}" cannot use the originating client while its single connection is transaction-bound. Use the transaction client supplied to the callback.`,{meta:{driver:this.driverName,model:e.model,operation:e.operation,correlationId:e.correlationId,method:`$transaction(callback)`}})}async runConnectionTransactionLease(e){return withConnectionScope(this.connectionQueue,e)}resolveTransactionOptions(e,t){let n={driverName:this.driverName,form:t};return resolveTransactionPlan(parseTransactionOptions(e,n),this.transactionOptionSupport(),n)}assertTransactionOptionsSupported(e,t){this.resolveTransactionOptions(e,t)}readPostBeginIsolationStatement(e){if(e?.isolationPlacement===`post-begin`)return e.isolationStatement}_execute(e,t){return this.executeTypedStatement(e,t,this.executeNormalizedProvider)}async executeNormalizedProvider(e,t,n,r,i=!1){let a=i?await this.executeRaw(e,t,n,r):await this.execute(e,t,n,r);return c(a,{provider:this.driverName,operation:r.operation??(i?`executeRaw`:`execute`)}),a}async executeTypedStatement(e,t,n){let r=this.resolveExecutionContext(t,`execute`),i=this.hasTrustedObservers(r),a=i?void 0:this.applyTrustedStatementTransforms(e,r,`execute`);return this.dispatchStatement(r,i,t=>{try{return a??=this.applyTrustedStatementTransforms(e,r,`execute`),this.sendStatement(this.buildStatement(a),a.values,r,n,t)}catch(e){return Promise.reject(e)}})}dispatchStatement(e,t,n){let r=t?()=>this.observeTrustedStatement(e,n):n;return this.serializeTransactions&&!this.inTransaction?(this.assertBaseOperationAllowedDuringTransaction(e),this.connectionQueue.run(r,connectionQueueWait(void 0,{driverName:this.driverName,form:`callback`}))):r()}async sendStatement(e,t,n,r,i=q){let a=l(t,n),o=this.getDiagnosticParameters(a,n),s=this.connectedClient()??await this.getClient(n);return i.execute({context:n,forceErrorContext:!0,params:o,sql:e},()=>this.executeNormalizedStatement(e,o,n,()=>r.call(this,s,e,a,n),!0))}_prepare(e,t){let n=new F([...e.strings],[...e.values]),r={sql:this.buildStatement(n),params:[...n.values]};return a(r,n),r}async _executeRaw(e,t,n){let r=this.resolveExecutionContext(n,`executeRaw`);return this.dispatchStatement(r,this.hasTrustedObservers(r),n=>this.sendStatement(e,t??[],r,(e,t,n)=>this.executeNormalizedProvider(e,t,n,r,!0),n))}runProviderTransactionCore(e,t,n,r=J){let i=Symbol(`noCallbackFailure`),a=i,o=t?.timeoutMs===void 0?e:n=>runWithTransactionTimeout(()=>e(n),t.timeoutMs,{driverName:this.driverName,form:`callback`}),trackedCallback=async e=>{try{return await o(e)}catch(e){throw a=e,e}},s=this.readPostBeginIsolationStatement(t),providerCallback=async e=>(s&&await this.executeRaw(e,s,void 0,{...n,operation:`transaction`}),trackedCallback(e)),runTransaction=async()=>{let e=await this.getClient(n);try{return await this.transaction(e,providerCallback,n,t?.driverOptions)}catch(e){let normalizeTransactionFailure=e=>D(e,{driverName:this.driverName,dialect:this.dialect,model:n.model,operation:n.operation,correlationId:n.correlationId,diagnostics:this.getErrorDisclosure(n)});if(a!==i){if(e===a)throw e;let t=ee(e,a).map(normalizeTransactionFailure),n=x(a,t);throw this.transactionCleanupFailed(n),n}let t=normalizeTransactionLifecycleError(e,normalizeTransactionFailure);throw(this.inTransaction||e instanceof O||e instanceof AggregateError&&e.errors[0]===e.cause&&e.errors.length>1)&&this.transactionCleanupFailed(t),t}};return r.execute(runTransaction)}observeTransactionLifecycle(e,t,n){let r=e===`transaction`?{phase:`pending`}:void 0,i=r?V(t,{readyToCommit:()=>{r.phase=`ready`},committed:()=>{r.phase=`committed`}}):t;return this.observeTrustedDriverLifecycle(e,t,e,async e=>{let t=await n(i,e);return r&&(r.phase=`committed`),t},r===void 0?void 0:()=>r.phase===`pending`?void 0:{commitCertainty:r.phase===`committed`?`committed`:`may-have-committed`})}async _transaction(e,t,n){let r=this.resolveTransactionOptions(t,`callback`);if(!this.supportsTransactions)throw w(this.driverName);let i=this.resolveExecutionContext(n,`transaction`),a=this.serializeTransactions&&!this.inTransaction;a&&this.assertBaseOperationAllowedDuringTransaction(i);let o=connectionQueueWait(r?.maxWaitMode===`queue`?r.maxWaitMs:void 0,{driverName:this.driverName,form:`callback`}),executeTransaction=(t,n)=>{let run=()=>this.runProviderTransactionCore(e,r,t,n);return a?this.connectionQueue.enqueue(()=>this.runConnectionTransactionLease(run),o):run()};return this.hasTrustedObservers(i)?this.observeTransactionLifecycle(`transaction`,i,executeTransaction):executeTransaction(i)}async withTransaction(e,t,n){let r=this.resolveTransactionOptions(t,`callback`),i=this.resolveExecutionContext(n,`transaction`),a=r?.timeoutMs,o=a===void 0?t:withoutTimeout(t),s;return this._transaction(async t=>{s=this.createTransactionBoundDriver(t,i);let n=s,scopedBody=()=>this.runTransactionBody(()=>e(n)),runBody=()=>a===void 0?scopedBody():runWithTransactionTimeout(scopedBody,a,{driverName:this.driverName,form:`callback`});try{let e=await runBody();return s.closeTransactionScope(),await s.waitForActiveOperations(),s.assertTransactionCommittable(),e}catch(e){s.closeTransactionScope(e),await s.waitForActiveOperations();let t=s.getTransactionFailure();throw t&&t!==e?L(e,t):e}},o,i)}async executeBatch(e,t,n,r,i){let a=n??{operation:`executeBatch`},o=[];try{for(let[n,r]of t.entries()){if(!r)continue;let t=r.context?this.resolveExecutionContext(r.context,r.context.operation??`executeBatch`):a,i=r,c=this.getBatchDiagnosticParameters(r),normalizeFailure=e=>D(e,{driverName:this.driverName,dialect:this.dialect,model:t.model,operation:t.operation,correlationId:t.correlationId,statementIndex:n,query:i.sql,params:c,diagnostics:this.getErrorDisclosure(t),forceContext:!0});o.push(await new Promise((n,a)=>{let o,l,u=new Promise((e,t)=>{o=e,l=t}),d=this.observeTrustedStatement(t,(a=q)=>{i=this.materializeTrustedBatchQuery(r,t),c=this.getBatchDiagnosticParameters(i);let{sql:f,params:p}=i,m=s(i);return n({execute:async()=>{try{o(await a.execute({context:t,forceErrorContext:!0,params:c,sql:f},()=>this.executeNormalizedStatement(f,c,t,()=>m?this.executeRaw(e,f,p,t):this.execute(e,f,p??[],t),!0)))}catch(e){l(normalizeFailure(e))}return d},cancel:e=>(l(e),d)}),u});d.catch(a)}).catch(e=>{throw normalizeFailure(e)}))}let n=[];for(let e of o)n.push(await e.execute());return n}catch(e){throw await Promise.allSettled(o.map(t=>t.cancel(e))),e}}async _executeBatch(e,t,n,r){if(this.resolveTransactionOptions(t,`batch`),e.length===0)return[];if(!(this.supportsBatch||this.supportsTransactions))throw new N(`Driver "${this.driverName}" supports neither transactions nor atomic batch execution.`,{meta:{driver:this.driverName,method:`$transaction([...])`}});let i=this.resolveExecutionContext(n,`executeBatch`),a={provider:this.driverName,operation:i.operation??`executeBatch`};if(this.supportsBatch){if(r&&!this.supportsOrderedCommittedSegments)throw new N(`Driver '${this.driverName}' cannot acknowledge ordered committed segments.`);let executeNativeBatch=async(n=e,o=q)=>{let{queries:s,diagnosticParams:c,members:l}=prepareAtomicBatch(n,i,(e,t)=>this.getDiagnosticParameters(e,t,i),this.canDiscloseParameters(i)),u=s.map(e=>e.sql).join(`; `),d=await this.getClient(i),executeProvider=async()=>{try{let e=await this.executeBatch(d,s,i,r,t);return f(e,s.length,a),e}catch(e){let t=findUniqueExecutionContextIndex(e,s),n=t===void 0?void 0:s[t],r=n?.context??i;throw D(e,{driverName:this.driverName,dialect:this.dialect,model:r.model,operation:r.operation,correlationId:r.correlationId,statementIndex:n?t:void 0,query:n?n.sql:u,params:n?this.getBatchDiagnosticParameters(n):c,diagnostics:this.getErrorDisclosure(r),forceContext:!0})}};return o.execute({context:i,forceErrorContext:!1,members:l,params:c,sql:u},()=>this.executeNormalizedStatement(u,c,i,executeProvider,!1))},submitNativeBatch=()=>this.observeTrustedBatchStatements(e,i,executeNativeBatch);return this.serializeTransactions&&!this.inTransaction?(this.assertBaseOperationAllowedDuringTransaction(i),this.connectionQueue.enqueue(submitNativeBatch,connectionQueueWait(void 0,{driverName:this.driverName,form:`batch`}))):submitNativeBatch()}let{queries:o}=prepareAtomicBatch(e,i,(e,t)=>this.getDiagnosticParameters(e,t,i),this.canDiscloseParameters(i)),runSequentialBatch=async e=>{let t=await this.executeBatch(e,o,i);return f(t,o.length,a),t};return this.inTransaction?runSequentialBatch(await this.getClient(i)):this._transaction(runSequentialBatch,t,i)}transactionCleanupFailed(e){this.transactionPoisonError??=e}};function observePromiseRejection(e,t){return new ie(e,t)}var ie=class RejectionObservedPromise{[Symbol.toStringTag]=`Promise`;onRejectionObserved;promise;constructor(e,t){this.promise=e,this.onRejectionObserved=t}then(e,t){return t&&this.onRejectionObserved(),new RejectionObservedPromise(this.promise.then(e,t),this.onRejectionObserved)}catch(e){return e&&this.onRejectionObserved(),new RejectionObservedPromise(this.promise.catch(e),this.onRejectionObserved)}finally(e){return new RejectionObservedPromise(this.promise.finally(e),this.onRejectionObserved)}};const ae=Object.freeze({foreignKeys:`pragma`,reservedTablePrefixes:`none`,exclusion:`database-write-lock`});var Driver=class extends DriverTransactionBase{createTransactionBoundDriver(e,t){return new oe(this,e,t)}_connect(e){return this.runConnectionLifecycle(`connect`,e,(e,t)=>t.execute(async()=>{await this.getClient(e)}))}_disconnect(e){return this.runConnectionLifecycle(`disconnect`,e,async(e,t)=>{if(this.isDisconnecting)throw this.connectionClosedError(`Database connection is closing`,e);this.isDisconnecting=!0;let doDisconnect=async()=>{if(this.initPromise)try{await this.initPromise}catch{}let t=this.closeRetryClient??this.client;if(!t){this.transactionPoisonError=void 0;return}try{await this.closeClient(t)}catch(n){throw this.closeRetryClient=t,this.client===t&&(this.client=null),this.initPromise=null,T(n,{driverName:this.driverName,model:e.model,operation:e.operation,correlationId:e.correlationId,diagnostics:this.getErrorDisclosure(e)},`Database disconnection failed`)}},n=t.execute(doDisconnect);try{await n,this.client=null,this.initPromise=null,this.closeRetryClient=null,this.transactionPoisonError=void 0}finally{this.isDisconnecting=!1}})}async runConnectionLifecycle(e,t,n){let r=this.resolveExecutionContext(t,e),run=(e=J)=>n(r,e),i=this.serializeTransactions&&!this.inTransaction;return i&&this.assertBaseOperationAllowedDuringTransaction(r),this.hasTrustedObservers(r)?this.observeTrustedDriverLifecycle(`connection`,r,e,i?e=>this.connectionQueue.enqueue(()=>run(e)):run):i?this.connectionQueue.enqueue(run):run()}async disconnect(){return this._disconnect()}};function disposeDriver(){return this.disconnect()}r!==void 0&&Object.defineProperty(Driver.prototype,r,{configurable:!0,writable:!0,enumerable:!1,value:disposeDriver});var oe=class TransactionBoundDriver extends Driver{baseDriver;parentTransactionDriver;tx;scopeQueue=new SavepointQueue;activeOperations=new Set;nestedTransactionObservations=new Set;transactionClosed=!1;signalScopeClosed;scopeClosed;isSavepointActive=!1;hasAdmittedWithTransactionDispatch=!1;rollbackOnlyError;result;inTransaction=!0;supportsTransactions;supportsBatch;supportsOrderedCommittedSegments;maxBindParametersPerStatement;constructor(e,t,n){super(e.dialect,e.driverName,n,e.migrationNamespaceAttestation);let resolveClosed=()=>void 0;this.scopeClosed=new Promise(e=>{resolveClosed=e}),this.signalScopeClosed=resolveClosed,this.baseDriver=e,this.parentTransactionDriver=e instanceof TransactionBoundDriver?e:void 0,this.tx=t,defineImmutableDriverFact(this,`adapter`,e.adapter),this.result=e.result,this.supportsTransactions=e.supportsTransactions,this.supportsBatch=e.supportsBatch,this.supportsOrderedCommittedSegments=e.supportsOrderedCommittedSegments,this.maxBindParametersPerStatement=e.maxBindParametersPerStatement}async getClient(e){return this.tx}closeTransactionScope(...e){this.transactionClosed=!0,e.length>0&&this.signalScopeClosed(e[0]);for(let e of this.nestedTransactionObservations)e.failure&&!e.isRejectionObserved&&this.markCurrentScopeRollbackOnly(e.failure)}runTransactionBody(e){return Promise.race([e(),this.scopeClosed.then(e=>{throw e})])}async waitForActiveOperations(){for(;this.activeOperations.size>0;)await Promise.allSettled([...this.activeOperations])}getTransactionFailure(){return this.parentTransactionDriver?.getTransactionFailure()??this.rollbackOnlyError}assertTransactionCommittable(){if(this.parentTransactionDriver?.assertTransactionCommittable(),this.rollbackOnlyError)throw this.rollbackOnlyError}markCurrentScopeRollbackOnly(e){this.rollbackOnlyError??=e}markRootTransactionRollbackOnly(e){if(this.parentTransactionDriver){this.parentTransactionDriver.markRootTransactionRollbackOnly(e);return}this.rollbackOnlyError??=e}assertRollbackOnlyUsable(){let e=this.getTransactionFailure();if(e)throw L(E(e,new N(`Transaction for driver "${this.driverName}" is rollback-only after an earlier failure; no further statements can execute.`,{cause:e,meta:{driver:this.driverName,method:`$transaction`}})),e)}assertTransactionOpen(){if(this.parentTransactionDriver?.assertTransactionOpen(),this.assertRollbackOnlyUsable(),this.transactionClosed)throw new N(`Transaction for driver "${this.driverName}" is no longer active.`,{meta:{driver:this.driverName,method:`$transaction`}})}getActiveSavepointUseError(e){if(this.isSavepointActive)return new N(`Transaction scope for driver "${this.driverName}" cannot be used while its nested transaction is active. At every nesting level, use the transaction client supplied to that callback.`,{meta:{driver:this.driverName,method:e}})}enqueueScopeOperation(e){return this.scopeQueue.enqueue(async()=>{this.assertRollbackOnlyUsable();try{return await e()}catch(e){throw this.markCurrentScopeRollbackOnly(toTransactionOperationError(e)),e}})}trackTransactionOperation(e,t){let n=t?void 0:{isRejectionObserved:!1};n&&this.nestedTransactionObservations.add(n);let r=Promise.resolve().then(()=>(this.assertTransactionOpen(),e()));return this.activeOperations.add(r),r.then(()=>{this.activeOperations.delete(r)},e=>{this.activeOperations.delete(r);let t=toTransactionOperationError(e);if(n){n.failure=t,this.transactionClosed&&!n.isRejectionObserved&&this.markCurrentScopeRollbackOnly(t);return}this.markCurrentScopeRollbackOnly(t)}).catch(()=>void 0),n?observePromiseRejection(r,()=>{n.isRejectionObserved=!0}):r}scoped(e,t){let n=this.getActiveSavepointUseError(e);return n?Promise.reject(n):this.trackTransactionOperation(()=>this.enqueueScopeOperation(t),!0)}_execute(e,t){return this.scoped(`execute`,()=>super._execute(e,t))}_executeRaw(e,t,n){return this.scoped(`executeRaw`,()=>super._executeRaw(e,t,n))}transactionOptionSupport(){return{isolationLevel:`unsupported`,isolationLevelReason:`a nested transaction runs as a SAVEPOINT inside the outer transaction, whose isolation level is already fixed and cannot be changed mid-transaction — set it on the outermost $transaction`,timeout:!0,maxWait:`unsupported`,maxWaitReason:`a nested transaction reuses the outer transaction's connection, so there is no transaction slot to wait for`}}resolveNestedOptions(e,t){try{return this.resolveTransactionOptions(e,t)}catch(e){return toTransactionOperationError(e)}}_executeBatch(e,t,n,r){let i=this.resolveNestedOptions(t,`batch`);return i instanceof Error?Promise.reject(i):e.length===0?Promise.resolve([]):this.scoped(`$transaction([...])`,()=>super._executeBatch(e,t,n,r))}_transaction(e,t,n){let r=this.resolveNestedOptions(t,`callback`);if(r instanceof Error)return Promise.reject(r);let i=this.hasAdmittedWithTransactionDispatch;if(!i){let e=this.getActiveSavepointUseError(`$transaction(callback)`);if(e)return Promise.reject(e);try{this.assertTransactionOpen()}catch(e){return Promise.reject(e)}}let a=this.resolveExecutionContext(n,`transaction`),o=this.hasTrustedObservers(a),executeTransaction=(t=J)=>this.scopeQueue.enqueue(async()=>{this.assertRollbackOnlyUsable(),this.isSavepointActive=!0;try{return await this.runProviderTransactionCore(e,r,a,t)}finally{this.isSavepointActive=!1}}),s=o?()=>this.observeTransactionLifecycle(`savepoint`,a,(e,t)=>executeTransaction(t)):void 0;return i?s?s():executeTransaction():this.trackTransactionOperation(s??executeTransaction,!1)}withTransaction(e,t,n){let r=this.resolveNestedOptions(t,`callback`);if(r instanceof Error)return Promise.reject(r);let i=this.getActiveSavepointUseError(`$transaction(callback)`);return i?Promise.reject(i):this.trackTransactionOperation(()=>{this.hasAdmittedWithTransactionDispatch=!0;try{return super.withTransaction(e,t,n)}finally{this.hasAdmittedWithTransactionDispatch=!1}},!1)}initClient(){throw Error(`TransactionBoundDriver does not initialize clients`)}closeClient(){return Promise.resolve()}execute(e,t,n,r){return this.baseDriver.execute(e,t,n,r)}executeRaw(e,t,n,r){return this.baseDriver.executeRaw(e,t,n,r)}async transaction(e,t,n){return this.assertTransactionCommittable(),S(e=>this.baseDriver.executeRaw(this.tx,e,void 0,n??{}),()=>t(this.tx))}transactionCleanupFailed(e){this.markRootTransactionRollbackOnly(e)}async disconnect(){}};export{isolationLevelStatement as a,refuseUnknownDriverConfigKeys as c,resolveNamespaceOption as d,systemRootAsVerifyFull as f,acquireWithMaxWait as i,resolveMigrationNamespaceAttestationOption as l,ae as n,defineImmutableDriverFact as o,physicalConnectionQueue as r,refuseEmptyDatabaseUrl as s,Driver as t,resolveMigrationSessionAttestationOption as u};
2
- //# sourceMappingURL=driver-B9fIori_.mjs.map
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t,o as n}from"./value-guards-CK9guf2Z.mjs";import{_ as r,d as i,f as a,g as o,h as s,i as c,l,n as u,p as d,r as f,t as p}from"./bind-parameter-capacity-qfEejeOX.mjs";import{S as m,b as h,i as g,m as _,n as v,s as y,t as b}from"./base-D3m1S7Uc.mjs";import{c as x,f as S,g as C,m as w,n as T,o as E,r as D,s as O,u as ee}from"./error-mapping-C9WgitPi.mjs";import{i as k,m as A,p as j,r as M}from"./validation-BamBwne9.mjs";import{n as N}from"./transaction-4dfqals6.mjs";import{r as P,t as F}from"./sql-Bhxq9arK.mjs";import{a as I,r as te,t as ne}from"./observation-Co72iCd1.mjs";import{n as L}from"./suppressed-failure-Bdo2aK81.mjs";import{a as R,c as z,o as B,t as V}from"./execution-context-rJXTRVrJ.mjs";import{t as H}from"./clock-YTLtjLFS.mjs";import{t as U}from"./settle-etgtP1WM.mjs";function applyStatementTransforms(e,n,r,i){if(i===void 0||i.length===0)return e;let a=e;for(let e of i){let i=Object.freeze({statement:a,model:n,operation:r}),o;try{o=Reflect.apply(e.handler,void 0,[i])}catch(t){throw statementTransformFailure(e.extension,n,r,`threw`,normalizeThrown(t))}try{if(P(o)){let e=Reflect.get(o,`toStatement`);if(!t(e))throw TypeError(`Statement transform returned a Sql value without a callable toStatement method`);if(typeof Reflect.apply(e,o,[`?`])!=`string`)throw TypeError(`Statement transform returned a Sql value whose toStatement method did not return a string`);a=o;continue}}catch(t){throw statementTransformFailure(e.extension,n,r,`returned an unreadable value`,normalizeUnreadableReturn(t))}let s;try{s=isThenable(o)}catch(t){throw statementTransformFailure(e.extension,n,r,`returned an unreadable value`,normalizeUnreadableReturn(t))}let c=s?`returned a promise or thenable`:`returned a non-Sql value`;throw statementTransformFailure(e.extension,n,r,c,TypeError(`Statement transform ${c}`))}return a}function isThenable(e){return n(e)||t(e)?t(Reflect.get(e,`then`)):!1}function normalizeThrown(e){return m(e)?e:Error(`Statement transform threw a non-Error value`)}function normalizeUnreadableReturn(e){return m(e)?e:Error(`Statement transform returned an unreadable value`)}function statementTransformFailure(e,t,n,r,i){return new j(`Extension "${e}" statement handler for ${t===void 0?n:`${t}.${n}`} ${r}.`,{cause:i,meta:{method:`statement`,model:t,operation:n}})}var NumberedSql=class extends F{#e;#t;constructor(e,t){super([``],[]);let n=e.strings,r=[],i=new Map,a=n[0];for(let[o,s]of e.values.entries()){let e=s instanceof Date?`date:${s.getTime()}`:s===null||typeof s!=`object`&&typeof s!=`function`?`${typeof s}:${String(s)}`:s,c=i.get(e);c===void 0&&(c=r.push(s),i.set(e,c)),a+=`${t}${c}${n[o+1]}`}this.#e=a,this.#t=r}get values(){return this.#t}toStatement(){return this.#e}};const W=Symbol(`viborm.batchDiagnosticParams`),G=[];Object.freeze(G);function snapshotDiagnosticParameters(e){let t=_(e,{includeParams:!0,includeSql:!0});return Object.freeze(t),t}function findUniqueExecutionContextIndex(e,t){if(!g(e))return t.length===1?0:void 0;let n=readTrustedErrorExecutionContext(e);if(!n?.correlationId)return t.length===1?0:void 0;let r;for(let e=0;e<t.length;e+=1){let i=t[e]?.context;if(i&&i.correlationId===n.correlationId&&i.model===n.model&&i.operation===n.operation){if(r!==void 0)return;r=e}}return r}function findUniqueErrorLogDetails(e,t){if(!t)return;let n=findUniqueExecutionContextIndex(e,t);return n===void 0?void 0:t[n]}function getErrorExecutionContext(e,t){return g(e)?z(readTrustedErrorExecutionContext(e),t,t.operation):t}function readTrustedErrorExecutionContext(e){let t=b.prototype.toJSON.call(e).meta;if(n(t))return{model:typeof t.model==`string`?t.model:void 0,operation:typeof t.operation==`string`?t.operation:void 0,correlationId:typeof t.correlationId==`string`?t.correlationId:void 0}}var SavepointQueue=class{queue=[];head=0;processing=!1;enqueue(e,t){return new Promise((n,r)=>{let i=!1,a;t&&(a=setTimeout(()=>{i=!0,r(t.onMaxWaitExceeded())},t.maxWaitMs)),this.queue.push(async()=>{if(a&&clearTimeout(a),!i)try{n(await e())}catch(e){r(e)}}),this.scheduleFlush()})}run(e,t){if(this.processing)return this.enqueue(e,t);this.processing=!0;let n=e(),release=()=>this.flush();return n.then(release,release),n}scheduleFlush(){this.processing||(this.processing=!0,queueMicrotask(()=>this.flush()))}async flush(){for(;this.head<this.queue.length;){let e=this.queue[this.head++];e&&await e()}this.queue=[],this.head=0,this.processing=!1}};function readOptionOnce(e,t){try{return Object.hasOwn(e,t)?Reflect.get(e,t):void 0}catch(e){throw new M(`The "${t}" option could not be read.`,{cause:h(e)})}}function resolveNamespaceOption(e){let t=readOptionOnce(e,`namespace`);if(t===void 0||typeof t==`string`)return t;throw new M(`The "namespace" option must be a string; received type "${typeof t}".`)}function resolveAttestationOption(e,t,n){let r=readOptionOnce(e,t);if(r!==void 0){if(r===n)return n;throw new M(`The "${t}" option admits only "${n}".`)}}function resolveMigrationNamespaceAttestationOption(e){return resolveAttestationOption(e,`migrationNamespaceAttestation`,`non-redirecting`)}function resolveMigrationSessionAttestationOption(e){return resolveAttestationOption(e,`migrationSessionAttestation`,`dedicated-session`)}function refuseEmptyDatabaseUrl(e,t,n){if(!(n||t.databaseUrl||!Object.hasOwn(t,`databaseUrl`)))throw new M(`Driver "${e}" was given an empty databaseUrl and no host; set the URL or name the host in options.`,{meta:{driver:e,operation:`configuration`}})}function systemRootAsVerifyFull(e){let t;try{t=new URL(e)}catch{return e}return t.searchParams.get(`sslrootcert`)===`system`?(t.searchParams.delete(`sslrootcert`),t.searchParams.set(`sslmode`,`verify-full`),t.href):e}function defineImmutableDriverFact(e,t,n){Object.defineProperty(e,t,{value:n,writable:!1,enumerable:!0,configurable:!1})}const K={schema:!0,skipSchemaValidation:!0};function refuseUnknownDriverConfigKeys(e,t,n,r={}){for(let i of Object.keys(e)){if(Object.hasOwn(K,i)||Object.hasOwn(n,i))continue;let e=Object.hasOwn(r,i)?r[i]:void 0,a=[...Object.keys(K),...Object.keys(n)];throw new M(`viborm/${t} does not accept "${i}"; ${e??`it accepts ${a.join(`, `)}`}.`,{meta:{driver:t,operation:`configuration`}})}}const q=Object.freeze({execute:(e,t)=>t()}),J=Object.freeze({execute:e=>e()});function createDeferredDispatch(){let e,t=new Promise(t=>{e=t}),n=!1,settleDispatch=t=>{n||(n=!0,e?.(t))},execute=(e,t)=>{let n,r,i=new Promise((e,t)=>{n=e,r=t}),a=!1,start=()=>{if(a)return;a=!0;let e;try{e=t()}catch(e){r?.(e);return}e.then(n,r)};return settleDispatch(e(start)),i};return Object.freeze({dispatch:t,execute,settleSkipped:()=>settleDispatch(void 0)})}var Y=class DriverInstrumentationBase{supportsTransactions=!0;supportsBatch=!1;supportsOrderedCommittedSegments=!1;maxBindParametersPerStatement=void 0;driverName;result;client=null;inTransaction=!1;serializeTransactions=!1;connectionQueue=new SavepointQueue;initPromise=null;closeRetryClient=null;isDisconnecting=!1;transactionPoisonError;boundContext;transactionOptionSupport(){return{isolationLevel:`unsupported`,isolationLevelReason:`this driver has not declared an isolation-level contract`,timeout:!1,timeoutReason:`this driver has not declared a timeout contract`,maxWait:`unsupported`,maxWaitReason:`this driver has not declared a maxWait contract`}}constructor(e,t,n={},r){defineImmutableDriverFact(this,`dialect`,e),this.driverName=t,this.boundContext=z(n),defineImmutableDriverFact(this,`migrationNamespaceAttestation`,r)}get numbersPlaceholders(){return!0}applyTrustedStatementTransforms(e,t,n){let r=(B(t)??B(this.boundContext))?.statement,i=e;if(r!==void 0&&r.length>0){let a=this.resolveExecutionContext(t,n);i=applyStatementTransforms(e,a.model,a.operation??n,r)}let a=u(this.maxBindParametersPerStatement);return a!==void 0&&i.values.length>a&&this.dialect!==`mysql`&&this.numbersPlaceholders&&(i=new NumberedSql(i,this.dialect===`postgresql`?`$`:`?`)),p(i,this.driverName,a,`operation`),i}hasTrustedObservers(e){return((B(e)??B(this.boundContext))?.observe.length??0)>0}observeTrustedStatement(e,t,n){let r=B(e)?.observe;if(r===void 0||r.length===0)return t(void 0);let i=this.createOfficialStatementExecutionGate(e);return I(r,e.operation,e.model,()=>t(i),n,i?.readFacts)}observeTrustedDriverLifecycle(e,t,n,r,i){let a=B(t)?.observe;if(a===void 0||a.length===0)return r(void 0);let o=readOfficialCapability(t),s=o?.observesLifecycle===!0&&o.wants(n)?this.createOfficialDriverLifecycleExecutionGate(t,n):void 0;return te(e,a,t.operation,()=>r(s),i,s?.readFacts)}materializeTrustedBatchQuery(e,t){let n=i(e);if(n===void 0)return e;let r=this.applyTrustedStatementTransforms(n,t,`executeBatch`);return{sql:this.buildStatement(r),params:l(r.values,t),...e.context===void 0?{}:{context:e.context}}}observeTrustedBatchStatements(e,t,n,r){let i=B(t)?.observe;if(i===void 0||i.length===0)return n(e.map(e=>this.materializeTrustedBatchQuery(e,e.context??t)),void 0);let a=this.createOfficialStatementExecutionGate(t),o=!1,s=[],startAt=c=>{for(let n=c;n<e.length;n+=1){let c=e[n];if(c===void 0)continue;let l=c.context??t,u=o?void 0:a?.readFacts;return o=!0,I(i,l.operation,l.model,()=>(s.push(this.materializeTrustedBatchQuery(c,l)),startAt(n+1)),r,u)}return n(s,a)};return startAt(0)}createOfficialStatementExecutionGate(e){let t=readOfficialCapability(e);if(t?.observesLifecycle!==!0||!(t.wants(`statement`)||t.wants(`query-log`)||t.wants(`error-log`)))return;let n=createDeferredDispatch(),r,i=Object.freeze({kind:`statement`,dispatch:n.dispatch,complete:e=>{if(r===void 0){n.settleSkipped();return}let t=e.status===`failure`&&e.failure instanceof Error?e.failure:void 0;if(e.status===`failure`&&t===void 0)return;let i=t===void 0||r.forceErrorContext?void 0:findUniqueErrorLogDetails(t,r.members),a=i?.context??(t===void 0||r.forceErrorContext?r.context:getErrorExecutionContext(t,r.context)),o=readOfficialCapability(a);if(o===void 0)return;let s=o.wants(t===void 0?`query-log`:`error-log`);if(s||t&&o.wants(`statement`))return t!==void 0&&s&&C(t),Object.freeze({kind:`statement`,endedAt:Date.now(),capability:o,...s?{}:{skipLog:!0},context:a,sql:i?.sql??r.sql,params:i?.params??r.params,...t===void 0?{}:{failure:t}})}});return Object.freeze({readFacts:()=>i,execute:(e,t)=>n.execute(t=>(r=Object.freeze({...e,driver:this,startedAt:Date.now(),start:t}),r),t)})}createOfficialDriverLifecycleExecutionGate(e,t){let n=createDeferredDispatch(),r=Object.freeze({kind:`driver-lifecycle`,dispatch:n.dispatch,complete:e=>(n.settleSkipped(),e.status===`failure`&&e.failure instanceof Error?Object.freeze({kind:`driver-lifecycle`,failure:e.failure}):void 0)});return Object.freeze({readFacts:()=>r,execute:r=>n.execute(n=>Object.freeze({driver:this,context:e,boundary:t,start:n}),r)})}buildStatement(e){switch(this.dialect){case`postgresql`:return e.toStatement(`$n`);case`sqlite`:case`mysql`:return e.toStatement(`?`);default:return e.toStatement()}}getBatchDiagnosticParameters(e){try{let t=Reflect.get(e,W);return Array.isArray(t)?t:this.getDiagnosticParameters(e.params??[],e.context)}catch{return this.getDiagnosticParameters(e.params??[],e.context)}}getDiagnosticParameters(e,t,n){return this.canDiscloseParameters(t)||n!==void 0&&n!==t&&this.canDiscloseParameters(n)?snapshotDiagnosticParameters(e):G}connectedClient(){if(!(this.getClient!==DriverInstrumentationBase.prototype.getClient||this.transactionPoisonError||this.isDisconnecting||this.closeRetryClient!==null))return this.client??void 0}async getClient(e={}){if(this.transactionPoisonError||this.isDisconnecting||this.closeRetryClient!==null)throw this.unavailableClientError(e);return this.client?this.client:await this.initializeClient(e)}unavailableClientError(e){return this.transactionPoisonError?new N(`Driver "${this.driverName}" is unavailable after transaction cleanup failed.`,{cause:this.transactionPoisonError,meta:{driver:this.driverName,model:e.model,operation:e.operation,correlationId:e.correlationId}}):this.connectionClosedError(this.isDisconnecting?`Database connection is closing`:`Database connection cleanup is incomplete`,e)}connectionClosedError(e,t){return new k(e,{code:v.CONNECTION_CLOSED,diagnostics:this.getErrorDisclosure(t),meta:{driver:this.driverName,model:t.model,operation:t.operation,correlationId:t.correlationId}})}async initializeClient(e){this.initPromise||=Promise.resolve().then(()=>this.initClient()).then(e=>(this.client=e,e));try{return await this.initPromise}catch(t){throw T(t,{driverName:this.driverName,model:e.model,operation:e.operation,correlationId:e.correlationId,callsite:R(e),diagnostics:this.getErrorDisclosure(e)})}}normalizeStatementFailure(e,t,n,r,i){return D(e,{driverName:this.driverName,dialect:this.dialect,model:r.model,operation:r.operation,correlationId:r.correlationId,callsite:R(r),query:t,params:n,diagnostics:this.getErrorDisclosure(r),forceContext:i})}async executeNormalizedStatement(e,t,n,r,i){try{return await r()}catch(r){throw this.normalizeStatementFailure(r,e,t,n,i)}}resolveExecutionContext(e,t){return z(e,this.boundContext,t)}canDiscloseParameters(e){let t=readOfficialCapability(e);return t!==void 0&&(t.diagnostics.includeParams===!0||t.wants(`parameters`))}getErrorDisclosure(e){return readOfficialCapability(e)?.diagnostics??y}};function readOfficialCapability(e){return ne(B(e))}const X=[`ReadUncommitted`,`ReadCommitted`,`RepeatableRead`,`Serializable`],methodForForm=e=>e===`batch`?`$transaction([...])`:`$transaction(callback)`;function invalidTransactionOptions(e,t){return new N(e,{code:v.INVALID_TRANSACTION_INPUT,meta:{driver:t.driverName,method:methodForForm(t.form)}})}function refuseTransactionOption(e,t,n){return new A(`Driver "${n.driverName}" cannot honor the "${e}" transaction option on ${methodForForm(n.form)}: ${t}`,{meta:{driver:n.driverName,method:methodForForm(n.form)}})}function transactionTimeoutError(e,t){return new N(`Transaction on driver "${t.driverName}" exceeded its timeout of ${e}ms and was rolled back.`,{code:v.TRANSACTION_TIMEOUT,meta:{driver:t.driverName,method:methodForForm(t.form)}})}function transactionMaxWaitError(e,t){return new N(`Transaction on driver "${t.driverName}" waited longer than maxWait (${e}ms) for a transaction slot and never started.`,{code:v.TRANSACTION_TIMEOUT,meta:{driver:t.driverName,method:methodForForm(t.form)}})}const isIsolationLevel=e=>X.includes(e);function readDurationOption(e,t,n){if(typeof e!=`number`||!Number.isFinite(e)||e<=0)throw invalidTransactionOptions(`Transaction option "${t}" must be a positive finite number of milliseconds.`,n);return e}function parseTransactionOptions(e,t){if(e===void 0)return;if(!n(e))throw invalidTransactionOptions(`Transaction options must be an object.`,t);let r=t.form===`batch`?[`isolationLevel`]:[`isolationLevel`,`timeout`,`maxWait`];for(let n of Reflect.ownKeys(e))if(!(typeof n==`string`&&r.includes(n)))throw t.form===`batch`&&(n===`timeout`||n===`maxWait`)?invalidTransactionOptions(`Transaction option "${n}" is not available on $transaction([...]): an array of operations has no interactive window to bound. Use the callback form.`,t):invalidTransactionOptions(`Unknown transaction option "${String(n)}". Supported options are ${r.map(e=>`"${e}"`).join(`, `)}.`,t);let i={};if(e.isolationLevel!==void 0){if(!isIsolationLevel(e.isolationLevel))throw invalidTransactionOptions(`Unknown isolation level ${JSON.stringify(e.isolationLevel)}. Supported levels are ${X.map(e=>`"${e}"`).join(`, `)}.`,t);i.isolationLevel=e.isolationLevel}return e.timeout!==void 0&&(i.timeout=readDurationOption(e.timeout,`timeout`,t)),e.maxWait!==void 0&&(i.maxWait=readDurationOption(e.maxWait,`maxWait`,t)),i}const re={ReadUncommitted:`READ UNCOMMITTED`,ReadCommitted:`READ COMMITTED`,RepeatableRead:`REPEATABLE READ`,Serializable:`SERIALIZABLE`};function isolationLevelStatement(e){return`SET TRANSACTION ISOLATION LEVEL ${re[e]}`}function resolveIsolationLevel(e,t,n){switch(t.isolationLevel){case`provider`:return{placement:`provider`};case`post-begin`:case`pre-begin`:return{placement:t.isolationLevel,statement:isolationLevelStatement(e)};case`serializable-only`:if(e===`Serializable`)return{placement:`serializable-only`};throw refuseTransactionOption(`isolationLevel`,`${e} is not available — ${t.isolationLevelReason??`this driver offers Serializable only`}.`,n);default:throw refuseTransactionOption(`isolationLevel`,t.isolationLevelReason??`this driver does not open a transaction that can be configured`,n)}}function resolveTransactionPlan(e,t,n){if(!e||e.isolationLevel===void 0&&e.timeout===void 0&&e.maxWait===void 0)return;let r=`unsupported`,i;if(e.isolationLevel!==void 0){let a=resolveIsolationLevel(e.isolationLevel,t,n);r=a.placement,i=a.statement}if(e.timeout!==void 0&&!t.timeout)throw refuseTransactionOption(`timeout`,t.timeoutReason??`this driver does not run an interactive callback that could be interrupted`,n);if(e.maxWait!==void 0&&t.maxWait===`unsupported`)throw refuseTransactionOption(`maxWait`,t.maxWaitReason??`this driver has no transaction-slot wait that VibORM can bound`,n);let a={};return r===`pre-begin`&&e.isolationLevel!==void 0&&(a.isolationLevel=e.isolationLevel),t.maxWait===`acquisition`&&e.maxWait!==void 0&&(a.maxWaitMs=e.maxWait),{...e.isolationLevel===void 0?{}:{isolationLevel:e.isolationLevel},...i===void 0?{}:{isolationStatement:i},isolationPlacement:r,...e.timeout===void 0?{}:{timeoutMs:e.timeout},...e.maxWait===void 0?{}:{maxWaitMs:e.maxWait},maxWaitMode:t.maxWait,...Object.keys(a).length===0?{}:{driverOptions:a}}}async function runWithTransactionTimeout(e,t,n,r=H){return U(e(),t,()=>transactionTimeoutError(t,n),void 0,r)}async function acquireWithMaxWait(e,t,n,r,i=H){let a=e();return n===void 0?a:U(a,n,()=>transactionMaxWaitError(n,r),e=>{try{t(e)}catch{}},i)}const Z=new WeakMap;let Q,$;function physicalConnectionQueue(e){let t=Z.get(e);return t||(t=new SavepointQueue,Z.set(e,t)),t}function isConnectionScope(e){let t=Q?.getStore();return t!==void 0&&t.queue===e&&t.active}function connectionQueueWait(e,t){let n=e??(Q===null?5e3:void 0);return n===void 0?void 0:{maxWaitMs:n,onMaxWaitExceeded:()=>transactionMaxWaitError(n,t)}}async function withConnectionScope(e,t){if($??=import(`node:async_hooks`).then(({AsyncLocalStorage:e})=>{Q=new e}).catch(()=>{Q=null}),await $,Q===null)return t();if(!Q)throw Error(`Connection scope failed to initialize`);let n={queue:e,active:!0};return Q.run(n,async()=>{try{return await t()}finally{n.active=!1}})}function prepareAtomicBatch(e,t,n,r){let i=[],a=e.map(e=>{let r=e.params,a=z(e.context,t,`executeBatch`),c=r?l(r,a):void 0;c&&Object.freeze(c);let u={sql:e.sql,...c?{params:c}:{},context:a};s(e)&&(u=o(u)),d(e,u,c??[]);let f=n(c??[],a);return i.push(f),Object.defineProperty(u,W,{configurable:!1,enumerable:!1,value:f,writable:!1}),Object.freeze(u)}),c=a.map((e,n)=>({context:e.context??t,params:i[n]??G,sql:e.sql})),u=r?i:G;return r&&Object.freeze(u),{queries:a,diagnosticParams:u,members:c}}function toTransactionOperationError(e){return e instanceof Error?e:new N(`Transaction operation failed`,{cause:Error(`A transaction operation rejected without an Error`)})}function normalizeTransactionLifecycleError(e,t){try{if(!(e instanceof AggregateError))return t(e);let n=e.cause;return e.errors[0]===n?x(t(n),e.errors.slice(1).map(e=>t(e))):t(e)}catch{return t(e)}}function withoutTimeout(e){if(!e)return e;let{timeout:t,...n}=e;return n}var DriverTransactionBase=class extends Y{runTransactionBody(e){return e()}assertBaseOperationAllowedDuringTransaction(e){if(isConnectionScope(this.connectionQueue))throw this.transactionBoundError(e)}transactionBoundError(e){return new N(`Driver "${this.driverName}" cannot use the originating client while its single connection is transaction-bound. Use the transaction client supplied to the callback.`,{meta:{driver:this.driverName,model:e.model,operation:e.operation,correlationId:e.correlationId,method:`$transaction(callback)`}})}async runConnectionTransactionLease(e){return withConnectionScope(this.connectionQueue,e)}resolveTransactionOptions(e,t){let n={driverName:this.driverName,form:t};return resolveTransactionPlan(parseTransactionOptions(e,n),this.transactionOptionSupport(),n)}assertTransactionOptionsSupported(e,t){this.resolveTransactionOptions(e,t)}readPostBeginIsolationStatement(e){if(e?.isolationPlacement===`post-begin`)return e.isolationStatement}_execute(e,t){return this.executeTypedStatement(e,t,this.executeNormalizedProvider)}async executeNormalizedProvider(e,t,n,r,i=!1){let a=i?await this.executeRaw(e,t,n,r):await this.execute(e,t,n,r);return c(a,{provider:this.driverName,operation:r.operation??(i?`executeRaw`:`execute`)}),a}async executeTypedStatement(e,t,n){let r=this.resolveExecutionContext(t,`execute`),i=this.hasTrustedObservers(r),a=i?void 0:this.applyTrustedStatementTransforms(e,r,`execute`);return this.dispatchStatement(r,i,t=>{try{return a??=this.applyTrustedStatementTransforms(e,r,`execute`),this.sendStatement(this.buildStatement(a),a.values,r,n,t)}catch(e){return Promise.reject(e)}})}dispatchStatement(e,t,n){let r=t?()=>this.observeTrustedStatement(e,n):n;return this.serializeTransactions&&!this.inTransaction?(this.assertBaseOperationAllowedDuringTransaction(e),this.connectionQueue.run(r,connectionQueueWait(void 0,{driverName:this.driverName,form:`callback`}))):r()}async sendStatement(e,t,n,r,i=q){let a=l(t,n),o=this.getDiagnosticParameters(a,n),s=this.connectedClient()??await this.getClient(n);return i.execute({context:n,forceErrorContext:!0,params:o,sql:e},()=>this.executeNormalizedStatement(e,o,n,()=>r.call(this,s,e,a,n),!0))}_prepare(e,t){let n=new F([...e.strings],[...e.values]),r={sql:this.buildStatement(n),params:[...n.values]};return a(r,n),r}async _executeRaw(e,t,n){let r=this.resolveExecutionContext(n,`executeRaw`);return this.dispatchStatement(r,this.hasTrustedObservers(r),n=>this.sendStatement(e,t??[],r,(e,t,n)=>this.executeNormalizedProvider(e,t,n,r,!0),n))}runProviderTransactionCore(e,t,n,r=J){let i=Symbol(`noCallbackFailure`),a=i,o=t?.timeoutMs===void 0?e:n=>runWithTransactionTimeout(()=>e(n),t.timeoutMs,{driverName:this.driverName,form:`callback`}),trackedCallback=async e=>{try{return await o(e)}catch(e){throw a=e,e}},s=this.readPostBeginIsolationStatement(t),providerCallback=async e=>(s&&await this.executeRaw(e,s,void 0,{...n,operation:`transaction`}),trackedCallback(e)),runTransaction=async()=>{let e=await this.getClient(n);try{return await this.transaction(e,providerCallback,n,t?.driverOptions)}catch(e){let normalizeTransactionFailure=e=>D(e,{driverName:this.driverName,dialect:this.dialect,model:n.model,operation:n.operation,correlationId:n.correlationId,diagnostics:this.getErrorDisclosure(n)});if(a!==i){if(e===a)throw e;let t=ee(e,a).map(normalizeTransactionFailure),n=x(a,t);throw this.transactionCleanupFailed(n),n}let t=normalizeTransactionLifecycleError(e,normalizeTransactionFailure);throw(this.inTransaction||e instanceof O||e instanceof AggregateError&&e.errors[0]===e.cause&&e.errors.length>1)&&this.transactionCleanupFailed(t),t}};return r.execute(runTransaction)}observeTransactionLifecycle(e,t,n){let r=e===`transaction`?{phase:`pending`}:void 0,i=r?V(t,{readyToCommit:()=>{r.phase=`ready`},committed:()=>{r.phase=`committed`}}):t;return this.observeTrustedDriverLifecycle(e,t,e,async e=>{let t=await n(i,e);return r&&(r.phase=`committed`),t},r===void 0?void 0:()=>r.phase===`pending`?void 0:{commitCertainty:r.phase===`committed`?`committed`:`may-have-committed`})}async _transaction(e,t,n){let r=this.resolveTransactionOptions(t,`callback`);if(!this.supportsTransactions)throw w(this.driverName);let i=this.resolveExecutionContext(n,`transaction`),a=this.serializeTransactions&&!this.inTransaction;a&&this.assertBaseOperationAllowedDuringTransaction(i);let o=connectionQueueWait(r?.maxWaitMode===`queue`?r.maxWaitMs:void 0,{driverName:this.driverName,form:`callback`}),executeTransaction=(t,n)=>{let run=()=>this.runProviderTransactionCore(e,r,t,n);return a?this.connectionQueue.enqueue(()=>this.runConnectionTransactionLease(run),o):run()};return this.hasTrustedObservers(i)?this.observeTransactionLifecycle(`transaction`,i,executeTransaction):executeTransaction(i)}async withTransaction(e,t,n){let r=this.resolveTransactionOptions(t,`callback`),i=this.resolveExecutionContext(n,`transaction`),a=r?.timeoutMs,o=a===void 0?t:withoutTimeout(t),s;return this._transaction(async t=>{s=this.createTransactionBoundDriver(t,i);let n=s,scopedBody=()=>this.runTransactionBody(()=>e(n)),runBody=()=>a===void 0?scopedBody():runWithTransactionTimeout(scopedBody,a,{driverName:this.driverName,form:`callback`});try{let e=await runBody();return s.closeTransactionScope(),await s.waitForActiveOperations(),s.assertTransactionCommittable(),e}catch(e){s.closeTransactionScope(e),await s.waitForActiveOperations();let t=s.getTransactionFailure();throw t&&t!==e?L(e,t):e}},o,i)}async executeBatch(e,t,n,r,i){let a=n??{operation:`executeBatch`},o=[];try{for(let[n,r]of t.entries()){if(!r)continue;let t=r.context?this.resolveExecutionContext(r.context,r.context.operation??`executeBatch`):a,i=r,c=this.getBatchDiagnosticParameters(r),normalizeFailure=e=>D(e,{driverName:this.driverName,dialect:this.dialect,model:t.model,operation:t.operation,correlationId:t.correlationId,statementIndex:n,query:i.sql,params:c,diagnostics:this.getErrorDisclosure(t),forceContext:!0});o.push(await new Promise((n,a)=>{let o,l,u=new Promise((e,t)=>{o=e,l=t}),d=this.observeTrustedStatement(t,(a=q)=>{i=this.materializeTrustedBatchQuery(r,t),c=this.getBatchDiagnosticParameters(i);let{sql:f,params:p}=i,m=s(i);return n({execute:async()=>{try{o(await a.execute({context:t,forceErrorContext:!0,params:c,sql:f},()=>this.executeNormalizedStatement(f,c,t,()=>m?this.executeRaw(e,f,p,t):this.execute(e,f,p??[],t),!0)))}catch(e){l(normalizeFailure(e))}return d},cancel:e=>(l(e),d)}),u});d.catch(a)}).catch(e=>{throw normalizeFailure(e)}))}let n=[];for(let e of o)n.push(await e.execute());return n}catch(e){throw await Promise.allSettled(o.map(t=>t.cancel(e))),e}}async _executeBatch(e,t,n,r){if(this.resolveTransactionOptions(t,`batch`),e.length===0)return[];if(!(this.supportsBatch||this.supportsTransactions))throw new N(`Driver "${this.driverName}" supports neither transactions nor atomic batch execution.`,{meta:{driver:this.driverName,method:`$transaction([...])`}});let i=this.resolveExecutionContext(n,`executeBatch`),a={provider:this.driverName,operation:i.operation??`executeBatch`};if(this.supportsBatch){if(r&&!this.supportsOrderedCommittedSegments)throw new N(`Driver '${this.driverName}' cannot acknowledge ordered committed segments.`);let executeNativeBatch=async(n=e,o=q)=>{let{queries:s,diagnosticParams:c,members:l}=prepareAtomicBatch(n,i,(e,t)=>this.getDiagnosticParameters(e,t,i),this.canDiscloseParameters(i)),u=s.map(e=>e.sql).join(`; `),d=await this.getClient(i),executeProvider=async()=>{try{let e=await this.executeBatch(d,s,i,r,t);return f(e,s.length,a),e}catch(e){let t=findUniqueExecutionContextIndex(e,s),n=t===void 0?void 0:s[t],r=n?.context??i;throw D(e,{driverName:this.driverName,dialect:this.dialect,model:r.model,operation:r.operation,correlationId:r.correlationId,statementIndex:n?t:void 0,query:n?n.sql:u,params:n?this.getBatchDiagnosticParameters(n):c,diagnostics:this.getErrorDisclosure(r),forceContext:!0})}};return o.execute({context:i,forceErrorContext:!1,members:l,params:c,sql:u},()=>this.executeNormalizedStatement(u,c,i,executeProvider,!1))},submitNativeBatch=()=>this.observeTrustedBatchStatements(e,i,executeNativeBatch);return this.serializeTransactions&&!this.inTransaction?(this.assertBaseOperationAllowedDuringTransaction(i),this.connectionQueue.enqueue(submitNativeBatch,connectionQueueWait(void 0,{driverName:this.driverName,form:`batch`}))):submitNativeBatch()}let{queries:o}=prepareAtomicBatch(e,i,(e,t)=>this.getDiagnosticParameters(e,t,i),this.canDiscloseParameters(i)),runSequentialBatch=async e=>{let t=await this.executeBatch(e,o,i);return f(t,o.length,a),t};return this.inTransaction?runSequentialBatch(await this.getClient(i)):this._transaction(runSequentialBatch,t,i)}transactionCleanupFailed(e){this.transactionPoisonError??=e}};function observePromiseRejection(e,t){return new ie(e,t)}var ie=class RejectionObservedPromise{[Symbol.toStringTag]=`Promise`;onRejectionObserved;promise;constructor(e,t){this.promise=e,this.onRejectionObserved=t}then(e,t){return t&&this.onRejectionObserved(),new RejectionObservedPromise(this.promise.then(e,t),this.onRejectionObserved)}catch(e){return e&&this.onRejectionObserved(),new RejectionObservedPromise(this.promise.catch(e),this.onRejectionObserved)}finally(e){return new RejectionObservedPromise(this.promise.finally(e),this.onRejectionObserved)}};const ae=Object.freeze({foreignKeys:`pragma`,reservedTablePrefixes:`none`,exclusion:`database-write-lock`});var Driver=class extends DriverTransactionBase{createTransactionBoundDriver(e,t){return new oe(this,e,t)}_connect(e){return this.runConnectionLifecycle(`connect`,e,(e,t)=>t.execute(async()=>{await this.getClient(e)}))}_disconnect(e){return this.runConnectionLifecycle(`disconnect`,e,async(e,t)=>{if(this.isDisconnecting)throw this.connectionClosedError(`Database connection is closing`,e);this.isDisconnecting=!0;let doDisconnect=async()=>{if(this.initPromise)try{await this.initPromise}catch{}let t=this.closeRetryClient??this.client;if(!t){this.transactionPoisonError=void 0;return}try{await this.closeClient(t)}catch(n){throw this.closeRetryClient=t,this.client===t&&(this.client=null),this.initPromise=null,T(n,{driverName:this.driverName,model:e.model,operation:e.operation,correlationId:e.correlationId,diagnostics:this.getErrorDisclosure(e)},`Database disconnection failed`)}},n=t.execute(doDisconnect);try{await n,this.client=null,this.initPromise=null,this.closeRetryClient=null,this.transactionPoisonError=void 0}finally{this.isDisconnecting=!1}})}async runConnectionLifecycle(e,t,n){let r=this.resolveExecutionContext(t,e),run=(e=J)=>n(r,e),i=this.serializeTransactions&&!this.inTransaction;return i&&this.assertBaseOperationAllowedDuringTransaction(r),this.hasTrustedObservers(r)?this.observeTrustedDriverLifecycle(`connection`,r,e,i?e=>this.connectionQueue.enqueue(()=>run(e)):run):i?this.connectionQueue.enqueue(run):run()}async disconnect(){return this._disconnect()}};function disposeDriver(){return this.disconnect()}r!==void 0&&Object.defineProperty(Driver.prototype,r,{configurable:!0,writable:!0,enumerable:!1,value:disposeDriver});var oe=class TransactionBoundDriver extends Driver{baseDriver;parentTransactionDriver;tx;scopeQueue=new SavepointQueue;activeOperations=new Set;nestedTransactionObservations=new Set;transactionClosed=!1;signalScopeClosed;scopeClosed;isSavepointActive=!1;hasAdmittedWithTransactionDispatch=!1;rollbackOnlyError;result;inTransaction=!0;supportsTransactions;supportsBatch;supportsOrderedCommittedSegments;maxBindParametersPerStatement;constructor(e,t,n){super(e.dialect,e.driverName,n,e.migrationNamespaceAttestation);let resolveClosed=()=>void 0;this.scopeClosed=new Promise(e=>{resolveClosed=e}),this.signalScopeClosed=resolveClosed,this.baseDriver=e,this.parentTransactionDriver=e instanceof TransactionBoundDriver?e:void 0,this.tx=t,defineImmutableDriverFact(this,`adapter`,e.adapter),this.result=e.result,this.supportsTransactions=e.supportsTransactions,this.supportsBatch=e.supportsBatch,this.supportsOrderedCommittedSegments=e.supportsOrderedCommittedSegments,this.maxBindParametersPerStatement=e.maxBindParametersPerStatement}async getClient(e){return this.tx}closeTransactionScope(...e){this.transactionClosed=!0,e.length>0&&this.signalScopeClosed(e[0]);for(let e of this.nestedTransactionObservations)e.failure&&!e.isRejectionObserved&&this.markCurrentScopeRollbackOnly(e.failure)}runTransactionBody(e){return Promise.race([e(),this.scopeClosed.then(e=>{throw e})])}async waitForActiveOperations(){for(;this.activeOperations.size>0;)await Promise.allSettled([...this.activeOperations])}getTransactionFailure(){return this.parentTransactionDriver?.getTransactionFailure()??this.rollbackOnlyError}assertTransactionCommittable(){if(this.parentTransactionDriver?.assertTransactionCommittable(),this.rollbackOnlyError)throw this.rollbackOnlyError}markCurrentScopeRollbackOnly(e){this.rollbackOnlyError??=e}markRootTransactionRollbackOnly(e){if(this.parentTransactionDriver){this.parentTransactionDriver.markRootTransactionRollbackOnly(e);return}this.rollbackOnlyError??=e}assertRollbackOnlyUsable(){let e=this.getTransactionFailure();if(e)throw L(E(e,new N(`Transaction for driver "${this.driverName}" is rollback-only after an earlier failure; no further statements can execute.`,{cause:e,meta:{driver:this.driverName,method:`$transaction`}})),e)}assertTransactionOpen(){if(this.parentTransactionDriver?.assertTransactionOpen(),this.assertRollbackOnlyUsable(),this.transactionClosed)throw new N(`Transaction for driver "${this.driverName}" is no longer active.`,{meta:{driver:this.driverName,method:`$transaction`}})}getActiveSavepointUseError(e){if(this.isSavepointActive)return new N(`Transaction scope for driver "${this.driverName}" cannot be used while its nested transaction is active. At every nesting level, use the transaction client supplied to that callback.`,{meta:{driver:this.driverName,method:e}})}enqueueScopeOperation(e){return this.scopeQueue.enqueue(async()=>{this.assertRollbackOnlyUsable();try{return await e()}catch(e){throw this.markCurrentScopeRollbackOnly(toTransactionOperationError(e)),e}})}trackTransactionOperation(e,t){let n=t?void 0:{isRejectionObserved:!1};n&&this.nestedTransactionObservations.add(n);let r=Promise.resolve().then(()=>(this.assertTransactionOpen(),e()));return this.activeOperations.add(r),r.then(()=>{this.activeOperations.delete(r)},e=>{this.activeOperations.delete(r);let t=toTransactionOperationError(e);if(n){n.failure=t,this.transactionClosed&&!n.isRejectionObserved&&this.markCurrentScopeRollbackOnly(t);return}this.markCurrentScopeRollbackOnly(t)}).catch(()=>void 0),n?observePromiseRejection(r,()=>{n.isRejectionObserved=!0}):r}scoped(e,t){let n=this.getActiveSavepointUseError(e);return n?Promise.reject(n):this.trackTransactionOperation(()=>this.enqueueScopeOperation(t),!0)}_execute(e,t){return this.scoped(`execute`,()=>super._execute(e,t))}_executeRaw(e,t,n){return this.scoped(`executeRaw`,()=>super._executeRaw(e,t,n))}transactionOptionSupport(){return{isolationLevel:`unsupported`,isolationLevelReason:`a nested transaction runs as a SAVEPOINT inside the outer transaction, whose isolation level is already fixed and cannot be changed mid-transaction — set it on the outermost $transaction`,timeout:!0,maxWait:`unsupported`,maxWaitReason:`a nested transaction reuses the outer transaction's connection, so there is no transaction slot to wait for`}}resolveNestedOptions(e,t){try{return this.resolveTransactionOptions(e,t)}catch(e){return toTransactionOperationError(e)}}_executeBatch(e,t,n,r){let i=this.resolveNestedOptions(t,`batch`);return i instanceof Error?Promise.reject(i):e.length===0?Promise.resolve([]):this.scoped(`$transaction([...])`,()=>super._executeBatch(e,t,n,r))}_transaction(e,t,n){let r=this.resolveNestedOptions(t,`callback`);if(r instanceof Error)return Promise.reject(r);let i=this.hasAdmittedWithTransactionDispatch;if(!i){let e=this.getActiveSavepointUseError(`$transaction(callback)`);if(e)return Promise.reject(e);try{this.assertTransactionOpen()}catch(e){return Promise.reject(e)}}let a=this.resolveExecutionContext(n,`transaction`),o=this.hasTrustedObservers(a),executeTransaction=(t=J)=>this.scopeQueue.enqueue(async()=>{this.assertRollbackOnlyUsable(),this.isSavepointActive=!0;try{return await this.runProviderTransactionCore(e,r,a,t)}finally{this.isSavepointActive=!1}}),s=o?()=>this.observeTransactionLifecycle(`savepoint`,a,(e,t)=>executeTransaction(t)):void 0;return i?s?s():executeTransaction():this.trackTransactionOperation(s??executeTransaction,!1)}withTransaction(e,t,n){let r=this.resolveNestedOptions(t,`callback`);if(r instanceof Error)return Promise.reject(r);let i=this.getActiveSavepointUseError(`$transaction(callback)`);return i?Promise.reject(i):this.trackTransactionOperation(()=>{this.hasAdmittedWithTransactionDispatch=!0;try{return super.withTransaction(e,t,n)}finally{this.hasAdmittedWithTransactionDispatch=!1}},!1)}initClient(){throw Error(`TransactionBoundDriver does not initialize clients`)}closeClient(){return Promise.resolve()}execute(e,t,n,r){return this.baseDriver.execute(e,t,n,r)}executeRaw(e,t,n,r){return this.baseDriver.executeRaw(e,t,n,r)}async transaction(e,t,n){return this.assertTransactionCommittable(),S(e=>this.baseDriver.executeRaw(this.tx,e,void 0,n??{}),()=>t(this.tx))}transactionCleanupFailed(e){this.markRootTransactionRollbackOnly(e)}async disconnect(){}};export{isolationLevelStatement as a,refuseUnknownDriverConfigKeys as c,resolveNamespaceOption as d,systemRootAsVerifyFull as f,acquireWithMaxWait as i,resolveMigrationNamespaceAttestationOption as l,ae as n,defineImmutableDriverFact as o,physicalConnectionQueue as r,refuseEmptyDatabaseUrl as s,Driver as t,resolveMigrationSessionAttestationOption as u};
2
+ //# sourceMappingURL=driver-Ddt147dK.mjs.map