gemi 0.237.3 → 0.239.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (206) hide show
  1. package/dist/ai/index.js +2 -2
  2. package/dist/ai/index.js.map +2 -2
  3. package/dist/ai/testing/index.js +3 -3
  4. package/dist/ai/testing/index.js.map +3 -3
  5. package/dist/ai/testing/scriptedProvider.d.ts +10 -4
  6. package/dist/ai/testing/scriptedProvider.d.ts.map +1 -1
  7. package/dist/app/index.js +1 -1
  8. package/dist/bun/plugin.js +1 -1
  9. package/dist/bun/preload.js +1 -1
  10. package/dist/{chunk-psdcmh65.js → chunk-0wa8ztk5.js} +8 -8
  11. package/dist/{chunk-psdcmh65.js.map → chunk-0wa8ztk5.js.map} +3 -3
  12. package/dist/{chunk-34a5b9xt.js → chunk-13eq76tw.js} +2 -2
  13. package/dist/{chunk-34a5b9xt.js.map → chunk-13eq76tw.js.map} +1 -1
  14. package/dist/{chunk-hk37x8mp.js → chunk-1kjyhseb.js} +1 -1
  15. package/dist/{chunk-s3fpkpdh.js → chunk-1wfwqgm5.js} +2 -2
  16. package/dist/{chunk-s3fpkpdh.js.map → chunk-1wfwqgm5.js.map} +1 -1
  17. package/dist/{chunk-8kp4rkd3.js → chunk-342ydn4n.js} +2 -2
  18. package/dist/{chunk-8kp4rkd3.js.map → chunk-342ydn4n.js.map} +1 -1
  19. package/dist/{chunk-ajyfp09w.js → chunk-387fpg2k.js} +2 -2
  20. package/dist/{chunk-ajyfp09w.js.map → chunk-387fpg2k.js.map} +1 -1
  21. package/dist/{chunk-xe76d4v6.js → chunk-3ady4k66.js} +2 -2
  22. package/dist/{chunk-4rs6w1gp.js.map → chunk-3ady4k66.js.map} +1 -1
  23. package/dist/{chunk-97t5t8jp.js → chunk-3crknzwp.js} +3 -3
  24. package/dist/{chunk-97t5t8jp.js.map → chunk-3crknzwp.js.map} +1 -1
  25. package/dist/{chunk-gbgwtaqq.js → chunk-3kgp6xka.js} +1 -1
  26. package/dist/{chunk-wj0q7tyn.js → chunk-3mq0wmq7.js} +3 -3
  27. package/dist/{chunk-wj0q7tyn.js.map → chunk-3mq0wmq7.js.map} +1 -1
  28. package/dist/{chunk-mhvg8nnb.js → chunk-3qmhe96e.js} +2 -2
  29. package/dist/{chunk-mhvg8nnb.js.map → chunk-3qmhe96e.js.map} +1 -1
  30. package/dist/{chunk-xm0fb17q.js → chunk-3rm4v7ht.js} +3 -3
  31. package/dist/{chunk-xm0fb17q.js.map → chunk-3rm4v7ht.js.map} +1 -1
  32. package/dist/{chunk-358krc4n.js → chunk-4mysb5ej.js} +2 -2
  33. package/dist/{chunk-358krc4n.js.map → chunk-4mysb5ej.js.map} +1 -1
  34. package/dist/{chunk-8adbpxpm.js → chunk-4sv5vkab.js} +2 -2
  35. package/dist/{chunk-8adbpxpm.js.map → chunk-4sv5vkab.js.map} +1 -1
  36. package/dist/{chunk-prvncxxf.js → chunk-4wj4bwvc.js} +3 -3
  37. package/dist/{chunk-prvncxxf.js.map → chunk-4wj4bwvc.js.map} +1 -1
  38. package/dist/{chunk-5na9khtz.js → chunk-51mz612v.js} +2 -2
  39. package/dist/{chunk-5na9khtz.js.map → chunk-51mz612v.js.map} +1 -1
  40. package/dist/{chunk-wt80ekv9.js → chunk-6gek696n.js} +92 -92
  41. package/dist/{chunk-wt80ekv9.js.map → chunk-6gek696n.js.map} +4 -4
  42. package/dist/{chunk-h1a4febx.js → chunk-7axcthef.js} +2 -2
  43. package/dist/{chunk-h1a4febx.js.map → chunk-7axcthef.js.map} +1 -1
  44. package/dist/{chunk-dh1wbntq.js → chunk-7fh7cfjh.js} +2 -2
  45. package/dist/{chunk-dh1wbntq.js.map → chunk-7fh7cfjh.js.map} +1 -1
  46. package/dist/{chunk-ea5fv4h9.js → chunk-7sxbq483.js} +2 -2
  47. package/dist/{chunk-ea5fv4h9.js.map → chunk-7sxbq483.js.map} +1 -1
  48. package/dist/{chunk-4wdc4q33.js → chunk-7ycjs0xn.js} +2 -2
  49. package/dist/{chunk-4wdc4q33.js.map → chunk-7ycjs0xn.js.map} +1 -1
  50. package/dist/{chunk-ygfwbh8p.js → chunk-8e14zcdc.js} +2 -2
  51. package/dist/{chunk-ygfwbh8p.js.map → chunk-8e14zcdc.js.map} +1 -1
  52. package/dist/{chunk-szyr67g7.js → chunk-8wvh099n.js} +2 -2
  53. package/dist/{chunk-szyr67g7.js.map → chunk-8wvh099n.js.map} +1 -1
  54. package/dist/{chunk-fcbtgekt.js → chunk-92zmwb33.js} +2 -2
  55. package/dist/{chunk-fcbtgekt.js.map → chunk-92zmwb33.js.map} +1 -1
  56. package/dist/{chunk-pe4f30nw.js → chunk-9fgyanab.js} +2 -2
  57. package/dist/{chunk-pe4f30nw.js.map → chunk-9fgyanab.js.map} +1 -1
  58. package/dist/{chunk-wskms8nf.js → chunk-a8q7ds6w.js} +1 -1
  59. package/dist/chunk-aczp96k5.js +13 -0
  60. package/dist/chunk-aczp96k5.js.map +16 -0
  61. package/dist/{chunk-7qhqqf0q.js → chunk-agpty0p6.js} +2 -2
  62. package/dist/{chunk-7qhqqf0q.js.map → chunk-agpty0p6.js.map} +1 -1
  63. package/dist/{chunk-nxap8bmy.js → chunk-bvgcv0jx.js} +2 -2
  64. package/dist/{chunk-nxap8bmy.js.map → chunk-bvgcv0jx.js.map} +1 -1
  65. package/dist/chunk-by0ydsqs.js +5 -0
  66. package/dist/{chunk-cwkf46bk.js.map → chunk-by0ydsqs.js.map} +1 -1
  67. package/dist/{chunk-4rs6w1gp.js → chunk-c7hbdsjv.js} +2 -2
  68. package/dist/{chunk-xe76d4v6.js.map → chunk-c7hbdsjv.js.map} +1 -1
  69. package/dist/chunk-ccymw1ed.js +9 -0
  70. package/dist/chunk-ccymw1ed.js.map +10 -0
  71. package/dist/{chunk-9wf36729.js → chunk-cjwjrk12.js} +1 -1
  72. package/dist/{chunk-ca1qwsjj.js → chunk-e4adgvd6.js} +2 -2
  73. package/dist/{chunk-ca1qwsjj.js.map → chunk-e4adgvd6.js.map} +1 -1
  74. package/dist/{chunk-xr8mcx1y.js → chunk-etj63p4p.js} +2 -2
  75. package/dist/{chunk-xr8mcx1y.js.map → chunk-etj63p4p.js.map} +1 -1
  76. package/dist/{chunk-engdyem1.js → chunk-fec4qnr3.js} +2 -2
  77. package/dist/{chunk-engdyem1.js.map → chunk-fec4qnr3.js.map} +1 -1
  78. package/dist/{chunk-2fw9pm64.js → chunk-feh44g4f.js} +2 -2
  79. package/dist/{chunk-2fw9pm64.js.map → chunk-feh44g4f.js.map} +1 -1
  80. package/dist/{chunk-kgpqz8te.js → chunk-ff8rtz9h.js} +2 -2
  81. package/dist/{chunk-kgpqz8te.js.map → chunk-ff8rtz9h.js.map} +1 -1
  82. package/dist/{chunk-bxby9c62.js → chunk-g9q39z7t.js} +2 -2
  83. package/dist/{chunk-bxby9c62.js.map → chunk-g9q39z7t.js.map} +1 -1
  84. package/dist/{chunk-692nx054.js → chunk-gs8fvb6a.js} +2 -2
  85. package/dist/{chunk-692nx054.js.map → chunk-gs8fvb6a.js.map} +1 -1
  86. package/dist/{chunk-ycwv9n7m.js → chunk-gxre6wnc.js} +1 -1
  87. package/dist/{chunk-pb7n7vaq.js → chunk-gykwq8py.js} +1 -1
  88. package/dist/{chunk-h2cvg5r5.js → chunk-j3zz8046.js} +2 -2
  89. package/dist/{chunk-h2cvg5r5.js.map → chunk-j3zz8046.js.map} +1 -1
  90. package/dist/{chunk-y73xy0zy.js → chunk-kabkxq5q.js} +2 -2
  91. package/dist/{chunk-y73xy0zy.js.map → chunk-kabkxq5q.js.map} +1 -1
  92. package/dist/{chunk-dt8bxq4c.js → chunk-kgbgj7v4.js} +2 -2
  93. package/dist/{chunk-dt8bxq4c.js.map → chunk-kgbgj7v4.js.map} +1 -1
  94. package/dist/{chunk-zz0k1na4.js → chunk-m0n0ddd2.js} +1 -1
  95. package/dist/{chunk-41bpne77.js → chunk-mmc5bbf4.js} +2 -2
  96. package/dist/{chunk-41bpne77.js.map → chunk-mmc5bbf4.js.map} +1 -1
  97. package/dist/{chunk-1etmnz40.js → chunk-p0dgpm5r.js} +2 -2
  98. package/dist/{chunk-1etmnz40.js.map → chunk-p0dgpm5r.js.map} +1 -1
  99. package/dist/{chunk-dnqmvmnp.js → chunk-pkew0k7c.js} +2 -2
  100. package/dist/{chunk-dnqmvmnp.js.map → chunk-pkew0k7c.js.map} +1 -1
  101. package/dist/{chunk-y89vn9da.js → chunk-q8pr18w6.js} +4 -4
  102. package/dist/{chunk-y89vn9da.js.map → chunk-q8pr18w6.js.map} +1 -1
  103. package/dist/{chunk-d2jafhaf.js → chunk-qb8pjdez.js} +4 -4
  104. package/dist/{chunk-d2jafhaf.js.map → chunk-qb8pjdez.js.map} +1 -1
  105. package/dist/{chunk-hgwtg5zp.js → chunk-qkfd84hx.js} +2 -2
  106. package/dist/{chunk-hgwtg5zp.js.map → chunk-qkfd84hx.js.map} +1 -1
  107. package/dist/{chunk-mykr2v6g.js → chunk-rc86ewq1.js} +3 -3
  108. package/dist/{chunk-mykr2v6g.js.map → chunk-rc86ewq1.js.map} +1 -1
  109. package/dist/{chunk-88c8ck33.js → chunk-re13gf4s.js} +3 -3
  110. package/dist/{chunk-88c8ck33.js.map → chunk-re13gf4s.js.map} +1 -1
  111. package/dist/{chunk-80kga3p1.js → chunk-rpwvwsq9.js} +1 -1
  112. package/dist/{chunk-9779ngzq.js → chunk-rreb2k19.js} +2 -2
  113. package/dist/{chunk-9779ngzq.js.map → chunk-rreb2k19.js.map} +1 -1
  114. package/dist/{chunk-7ytazpjd.js → chunk-samm4h7d.js} +1 -1
  115. package/dist/{chunk-cvg01wc0.js → chunk-sx2gadhs.js} +2 -2
  116. package/dist/{chunk-cvg01wc0.js.map → chunk-sx2gadhs.js.map} +1 -1
  117. package/dist/{chunk-vf9jtq9h.js → chunk-t495wyhh.js} +2 -2
  118. package/dist/{chunk-vf9jtq9h.js.map → chunk-t495wyhh.js.map} +1 -1
  119. package/dist/{chunk-f0bz1q3t.js → chunk-tvb68dqg.js} +1 -1
  120. package/dist/{chunk-4pjv77s5.js → chunk-vk1x3rsw.js} +2 -2
  121. package/dist/{chunk-4pjv77s5.js.map → chunk-vk1x3rsw.js.map} +1 -1
  122. package/dist/{chunk-mn5xxg4q.js → chunk-vq1q8mgm.js} +2 -2
  123. package/dist/{chunk-mn5xxg4q.js.map → chunk-vq1q8mgm.js.map} +1 -1
  124. package/dist/{chunk-49kkapvr.js → chunk-vqmy8jfr.js} +2 -2
  125. package/dist/{chunk-49kkapvr.js.map → chunk-vqmy8jfr.js.map} +1 -1
  126. package/dist/{chunk-wzng3k56.js → chunk-vvq18rrr.js} +2 -2
  127. package/dist/{chunk-wzng3k56.js.map → chunk-vvq18rrr.js.map} +1 -1
  128. package/dist/{chunk-vtf7tkef.js → chunk-wgb26e02.js} +2 -2
  129. package/dist/{chunk-vtf7tkef.js.map → chunk-wgb26e02.js.map} +1 -1
  130. package/dist/{chunk-g7exgg3k.js → chunk-wjjxqw9b.js} +2 -2
  131. package/dist/{chunk-g7exgg3k.js.map → chunk-wjjxqw9b.js.map} +1 -1
  132. package/dist/{chunk-q1grt110.js → chunk-wkw8afk0.js} +2 -2
  133. package/dist/{chunk-q1grt110.js.map → chunk-wkw8afk0.js.map} +1 -1
  134. package/dist/{chunk-kbz5s9wb.js → chunk-x68jra5n.js} +2 -2
  135. package/dist/{chunk-kbz5s9wb.js.map → chunk-x68jra5n.js.map} +1 -1
  136. package/dist/{chunk-p7ae0rnf.js → chunk-z0jf5kzx.js} +2 -2
  137. package/dist/{chunk-p7ae0rnf.js.map → chunk-z0jf5kzx.js.map} +1 -1
  138. package/dist/{chunk-cckfxk08.js → chunk-z6gwn4xf.js} +2 -2
  139. package/dist/{chunk-cckfxk08.js.map → chunk-z6gwn4xf.js.map} +1 -1
  140. package/dist/{chunk-j5r7vm8a.js → chunk-zsmwmg8x.js} +2 -2
  141. package/dist/{chunk-j5r7vm8a.js.map → chunk-zsmwmg8x.js.map} +1 -1
  142. package/dist/config/index.js +1 -1
  143. package/dist/console/run.js +2 -2
  144. package/dist/console/run.js.map +1 -1
  145. package/dist/container/index.js +2 -2
  146. package/dist/container/index.js.map +1 -1
  147. package/dist/database/Connection.d.ts +7 -0
  148. package/dist/database/Connection.d.ts.map +1 -1
  149. package/dist/database/config.d.ts +16 -0
  150. package/dist/database/config.d.ts.map +1 -1
  151. package/dist/database/index.js +2 -2
  152. package/dist/database/index.js.map +1 -1
  153. package/dist/database/sqliteClient.d.ts +42 -0
  154. package/dist/database/sqliteClient.d.ts.map +1 -0
  155. package/dist/database/sqliteQueue.d.ts +67 -0
  156. package/dist/database/sqliteQueue.d.ts.map +1 -0
  157. package/dist/email/index.js +2 -2
  158. package/dist/email/index.js.map +1 -1
  159. package/dist/facades/index.js +1 -1
  160. package/dist/foundation/index.js +2 -2
  161. package/dist/foundation/index.js.map +1 -1
  162. package/dist/http/index.js +1 -1
  163. package/dist/i18n/dictionaryRuntime.js +2 -2
  164. package/dist/i18n/dictionaryRuntime.js.map +1 -1
  165. package/dist/i18n/index.js +2 -2
  166. package/dist/i18n/index.js.map +1 -1
  167. package/dist/kernel/index.js +2 -2
  168. package/dist/kernel/index.js.map +1 -1
  169. package/dist/orm/context.d.ts +3 -61
  170. package/dist/orm/context.d.ts.map +1 -1
  171. package/dist/orm/index.js +2 -2
  172. package/dist/orm/index.js.map +1 -1
  173. package/dist/probe/index.js +2 -2
  174. package/dist/probe/index.js.map +1 -1
  175. package/dist/server/index.js +2 -2
  176. package/dist/server/index.js.map +1 -1
  177. package/dist/services/change-feed/DatabaseChangeFeedDriver.d.ts +0 -1
  178. package/dist/services/change-feed/DatabaseChangeFeedDriver.d.ts.map +1 -1
  179. package/dist/services/index.js +2 -2
  180. package/dist/services/index.js.map +1 -1
  181. package/dist/services/lock/DatabaseLockStore.d.ts +6 -1
  182. package/dist/services/lock/DatabaseLockStore.d.ts.map +1 -1
  183. package/dist/services/queue/DatabaseQueueDriver.d.ts +6 -1
  184. package/dist/services/queue/DatabaseQueueDriver.d.ts.map +1 -1
  185. package/dist/services/queue/work.js +2 -2
  186. package/dist/services/queue/work.js.map +1 -1
  187. package/dist/stats/route-table.js +1 -1
  188. package/dist/support/index.js +2 -2
  189. package/dist/support/index.js.map +1 -1
  190. package/dist/vitest/index.js +1 -1
  191. package/package.json +1 -1
  192. package/dist/chunk-2as2xfem.js +0 -5
  193. package/dist/chunk-2as2xfem.js.map +0 -14
  194. package/dist/chunk-cwkf46bk.js +0 -5
  195. package/dist/chunk-mxqrmjha.js +0 -13
  196. package/dist/chunk-mxqrmjha.js.map +0 -10
  197. /package/dist/{chunk-hk37x8mp.js.map → chunk-1kjyhseb.js.map} +0 -0
  198. /package/dist/{chunk-gbgwtaqq.js.map → chunk-3kgp6xka.js.map} +0 -0
  199. /package/dist/{chunk-wskms8nf.js.map → chunk-a8q7ds6w.js.map} +0 -0
  200. /package/dist/{chunk-9wf36729.js.map → chunk-cjwjrk12.js.map} +0 -0
  201. /package/dist/{chunk-ycwv9n7m.js.map → chunk-gxre6wnc.js.map} +0 -0
  202. /package/dist/{chunk-pb7n7vaq.js.map → chunk-gykwq8py.js.map} +0 -0
  203. /package/dist/{chunk-zz0k1na4.js.map → chunk-m0n0ddd2.js.map} +0 -0
  204. /package/dist/{chunk-80kga3p1.js.map → chunk-rpwvwsq9.js.map} +0 -0
  205. /package/dist/{chunk-7ytazpjd.js.map → chunk-samm4h7d.js.map} +0 -0
  206. /package/dist/{chunk-f0bz1q3t.js.map → chunk-tvb68dqg.js.map} +0 -0
@@ -1,5 +0,0 @@
1
- // @bun
2
- function E(z){return z}function f(){return{url:process.env.DATABASE_URL,dialect:void 0,options:void 0,slowTransactionThreshold:b,connections:void 0}}var b=2000;class Q extends Error{constructor(z){super(`Could not infer a database dialect from "${z}". Expected a URL starting with postgres://, postgresql://, mysql://, mariadb://, `+"sqlite://, or file: \u2014 or a SQLite path such as ./dev.db or :memory:.");this.name="UnknownDatabaseUrlError"}}class j extends Error{constructor(z){super(z===void 0||z==="default"?"No database URL configured. Set the DATABASE_URL environment variable, or set `url` in app/config/database.ts.":`The "${z}" database connection has no \`url\`. Set one under \`connections.${z}\` in app/config/database.ts.`);this.name="MissingDatabaseUrlError"}}var L={"postgres:":"postgres","postgresql:":"postgres","mysql:":"mysql","mariadb:":"mariadb","sqlite:":"sqlite","file:":"sqlite"},D=[".db",".sqlite",".sqlite3"];function F(z){let B=z.trim();if(B==="")throw new Q(z);if(B===":memory:")return"sqlite";let G=B.indexOf(":");if(G!==-1){let J=B.slice(0,G+1).toLowerCase(),K=L[J];if(K)return K}if(S(B))return"sqlite";throw new Q(z)}function S(z){if(z.startsWith("./")||z.startsWith("../")||z.startsWith("/"))return!0;let B=z.toLowerCase();return D.some((G)=>B.endsWith(G))}function p(z){return z==="sqlite"}function m(z){return z==="mysql"||z==="mariadb"}import{existsSync as g,readFileSync as y,realpathSync as I,statSync as U}from"fs";import{isAbsolute as w,join as H,resolve as q}from"path";var O=H("prisma","schema.prisma");class R extends Error{constructor(z,B,G){super(`"${z}" now resolves to ${B}, which is where Prisma migrates it. gemi used to open ${G} instead, and that file holds data \u2014 so `+`opening the resolved one would quietly leave it behind. gemi will not choose. Move ${G} onto ${B} if it is the database you want, or point DATABASE_URL at an absolute path to say so explicitly.`);this.name="AmbiguousSqlitePathError"}}function C(z){let B=z.trim(),G="",J=B;for(let K of["file://","file:","sqlite://","sqlite:"])if(B.slice(0,K.length).toLowerCase()===K){G=B.slice(0,K.length),J=B.slice(K.length);break}if(J===":memory:"||J.startsWith(":memory:?"))return null;return{prefix:G,file:J}}function _(z,B,G=process.cwd()){if(B!=="sqlite")return{url:z};let J=C(z);if(!J||J.file==="")return{url:z};if(w(J.file))return{url:z};let K=J.file.indexOf("?"),Z=K===-1?J.file:J.file.slice(0,K),$=K===-1?"":J.file.slice(K),X=H(G,"prisma");if(!T(G,z))return{url:z};let W=q(G,Z),Y=q(X,Z);if(W===Y)return{url:z};return{url:`${J.prefix}${Y}${$}`,moved:{from:W,to:Y}}}function T(z,B){let G=H(z,O);if(!g(G))return!1;let J;try{J=y(G,"utf8")}catch{return!1}let Z=J.replace(/^\s*\/\/.*$/gm,"").match(/datasource\s+\w+\s*\{([\s\S]*?)\}/);if(!Z)return!1;let $=Z[1];if(!/provider\s*=\s*["']sqlite["']/.test($))return!1;let X=$.match(/url\s*=\s*env\(\s*["']([^"']+)["']\s*\)/);if(X){let Y=process.env[X[1]];return typeof Y==="string"&&Y.trim()===B.trim()}let W=$.match(/url\s*=\s*["']([^"']+)["']/);return W?W[1].trim()===B.trim():!1}function k(z){try{if(I(z.from)===I(z.to))return null}catch{}try{let B=U(z.from);return B.isFile()&&B.size>0?z.from:null}catch{return null}}var{SQL:A}=globalThis.Bun;var V="default";class P extends Error{constructor(z,B){super(`No database connection named "${z}". Configured: ${B.map((G)=>`"${G}"`).join(", ")}. Declare it under \`connections\` in app/config/database.ts.`);this.name="UnknownConnectionError"}}class x extends Error{constructor(z){super(`"${z}" is the name of the connection declared by the top-level \`url\` and \`options\`, so it cannot also appear under \`connections\`. Rename it, or move its settings up to the top level.`);this.name="ReservedConnectionNameError"}}class N extends Error{open;requested;constructor(z,B){super(`A transaction is open on the "${z}" connection, and this statement names "${B}". A transaction cannot span two connections: the statement would run outside it and stay committed when the transaction rolls back. Move this query outside the transaction, or run the whole unit on one connection.`);this.open=z;this.requested=B;this.name="CrossConnectionTransactionError"}}class M{name;config;sql;dialect;url;ready;constructor(z,B={}){this.name=z;this.config=B;let G=B.url;if(!G)throw new j(z);this.dialect=B.dialect??F(G);let J=_(G,this.dialect);if(J.moved){let K=k(J.moved);if(K)throw new R(G,J.moved.to,K)}this.url=J.url,this.sql=B.options?new A(this.url,B.options):new A(this.url),this.ready=this.configure()}async configure(){if(this.dialect!=="sqlite")return;await this.sql.unsafe("pragma foreign_keys = ON")}get query(){return this.sql}async close(){this.ready.catch(()=>{}),await this.sql.close()}}class h{config;static token="database";name=V;pools=new Map;ready;constructor(z={}){this.config=z;let{connections:B={},...G}=z;this.pools.set(V,new M(V,G));try{this.build(B,G.slowTransactionThreshold)}catch(J){for(let K of this.pools.values())K.ready.catch(()=>{}),K.close().catch(()=>{});throw J}this.ready=Promise.all([...this.pools.values()].map((J)=>J.ready)).then(()=>{return})}build(z,B){for(let[G,J]of Object.entries(z)){if(G===V)throw new x(G);this.pools.set(G,new M(G,{slowTransactionThreshold:B,...J}))}}connection(z=V){if(z===V)return this;let B=this.pools.get(z);if(!B)throw new P(z,this.connectionNames);return B}get connectionNames(){return[...this.pools.keys()]}get sql(){return this.default.sql}get dialect(){return this.default.dialect}get url(){return this.default.url}get query(){return this.sql}async close(){this.ready.catch(()=>{}),await Promise.all([...this.pools.values()].map((z)=>z.close()))}get default(){return this.pools.get(V)}}
3
- export{E as Il,f as Jl,b as Kl,Q as Ll,j as Ml,F as Nl,p as Ol,m as Pl,R as Ql,V as Rl,P as Sl,x as Tl,N as Ul,M as Vl,h as Wl};
4
-
5
- //# debugId=5D03A4CD2C51C54764756E2164756E21
@@ -1,14 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../database/config.ts", "../database/dialect.ts", "../database/sqlitePath.ts", "../database/Connection.ts", "../database/DatabaseManager.ts"],
4
- "sourcesContent": [
5
- "import type { SQL } from \"bun\";\nimport type { Dialect } from \"./dialect\";\n\n// One connection: a URL, the dialect to compile for, and the pool behind it.\n//\n// Split out of `DatabaseConfig` when a second connection became configurable\n// (#327), so that a named connection is described by exactly the same fields\n// the default one is — rather than by a smaller, second-class shape that would\n// need widening the first time somebody's analytics pool needed a `dialect`\n// override or a threshold of its own.\nexport interface ConnectionConfig {\n // Connection string. Defaults to the `DATABASE_URL` environment variable.\n // The dialect is inferred from it — `postgres://`, `mysql://`, `mariadb://`,\n // `sqlite://`, `file:`, or a SQLite path like `./dev.db` or `:memory:`.\n url?: string;\n\n // Override the inferred dialect. Only needed when the URL doesn't carry a\n // recognisable protocol — a proxy or connection pooler fronting Postgres on a\n // custom scheme, say. Wrong values here produce SQL that fails at runtime\n // against a database that connected fine, so leave it unset unless inference\n // actually gets it wrong.\n dialect?: Dialect;\n\n // Options passed straight through to Bun's `SQL` client (pool size, timeouts,\n // TLS, ...). See https://bun.sh/docs/api/sql.\n options?: Record<string, unknown>;\n\n // How long a transaction may run, in milliseconds, before development warns\n // that it is still holding a pooled connection. `false` turns the warning off.\n //\n // A diagnostic, not a limit: nothing here cancels or shortens a transaction.\n // It only fires in development — the cost of a long transaction is paid by\n // unrelated queries blocking on connection acquisition, and that is a problem\n // worth catching while the callback is still in front of you.\n //\n // Raise it for a seed script or a data migration whose transactions are\n // legitimately long; `false` if the noise is not worth it at all. A value\n // that is not a positive finite number falls back to the 2s default rather\n // than disabling, so the warning cannot be lost to a typo — say `false` when\n // you mean off.\n //\n // Per connection, and this is the field most likely to differ between two of\n // them: a connection that exists *because* its queries are slow will warn on\n // every transaction it opens if it inherits the hot path's threshold, and a\n // warning that always fires is one nobody reads. A named connection that\n // does not set it inherits the top-level value.\n slowTransactionThreshold?: number | false;\n}\n\n// Config key: `database`.\n//\n// The top-level `url` / `options` / `dialect` describe the connection called\n// `\"default\"` — the one every query uses unless it says otherwise. `connections`\n// declares the others.\nexport interface DatabaseConfig extends ConnectionConfig {\n // Additional connections, keyed by the name `DB.connection(name)` and\n // `Model.on(name)` take.\n //\n // The case this exists for is two pools against **one** database with\n // opposite workloads — a hot path that must never block, and an analytics\n // path whose queries legitimately run for seconds:\n //\n // export default defineDatabaseConfig({\n // url: process.env.DATABASE_URL,\n // options: { max: 12 },\n //\n // connections: {\n // analytics: {\n // url: process.env.DATABASE_URL,\n // options: { max: 3, idleTimeout: 60, connectionTimeout: 45 },\n // slowTransactionThreshold: 60_000,\n // },\n // },\n // })\n //\n // A value that protects one of those is the wrong value for the other, which\n // is the entire reason they cannot be one pool with one setting. The same URL\n // twice is normal here and is not a mistake: what differs is the pool, not\n // the database.\n //\n // Two consequences worth knowing before declaring one, both of them\n // structural rather than incidental:\n //\n // - **A transaction cannot span two connections.** A statement that names one\n // while a transaction is open on another raises\n // `CrossConnectionTransactionError` rather than quietly running outside the\n // transaction.\n // - **Every connection is a real pool**, counted separately against whatever\n // connection cap the server or the pooler enforces. Two pools of 12 is 24\n // connections, not 12.\n connections?: Record<string, ConnectionConfig>;\n}\n\nexport function defineDatabaseConfig(config: DatabaseConfig): DatabaseConfig {\n return config;\n}\n\nexport function databaseConfigDefaults(): DatabaseConfig {\n return {\n url: process.env.DATABASE_URL,\n dialect: undefined,\n options: undefined,\n slowTransactionThreshold: SLOW_TRANSACTION_THRESHOLD,\n connections: undefined,\n };\n}\n\n// The default warning threshold, in milliseconds. Exported so the ORM can fall\n// back to the same number when a `DatabaseManager` was built without going\n// through `withDefaults` — a test constructing one directly, say — rather than\n// keeping a second copy of it that can drift.\nexport const SLOW_TRANSACTION_THRESHOLD = 2_000;\n\nexport type { SQL };\n",
6
- "// The SQL dialects Bun's `SQL` client can talk to. Bun infers the *connection*\n// from the URL protocol on its own, but it does not tell us which dialect it\n// picked — and gemi needs to know, because the SQL it generates differs per\n// dialect (`RETURNING` support, upsert syntax, autoincrement, boolean and\n// timestamp types). So we infer it a second time, here, for query generation.\nexport type Dialect = \"sqlite\" | \"postgres\" | \"mysql\" | \"mariadb\";\n\nexport class UnknownDatabaseUrlError extends Error {\n constructor(url: string) {\n super(\n `Could not infer a database dialect from \"${url}\". Expected a URL ` +\n `starting with postgres://, postgresql://, mysql://, mariadb://, ` +\n `sqlite://, or file: — or a SQLite path such as ./dev.db or :memory:.`,\n );\n this.name = \"UnknownDatabaseUrlError\";\n }\n}\n\nexport class MissingDatabaseUrlError extends Error {\n // The connection's name, when it is not the default one. A named connection\n // has no environment variable behind it and no top-level `url` to fall back\n // on, so the generic message would send whoever reads it to check\n // `DATABASE_URL`, which is set and is not what is missing.\n constructor(connection?: string) {\n super(\n connection === undefined || connection === \"default\"\n ? \"No database URL configured. Set the DATABASE_URL environment \" +\n \"variable, or set `url` in app/config/database.ts.\"\n : `The \"${connection}\" database connection has no \\`url\\`. Set one ` +\n `under \\`connections.${connection}\\` in app/config/database.ts.`,\n );\n this.name = \"MissingDatabaseUrlError\";\n }\n}\n\nconst PROTOCOLS: Record<string, Dialect> = {\n \"postgres:\": \"postgres\",\n \"postgresql:\": \"postgres\",\n \"mysql:\": \"mysql\",\n \"mariadb:\": \"mariadb\",\n \"sqlite:\": \"sqlite\",\n \"file:\": \"sqlite\",\n};\n\nconst SQLITE_FILE_EXTENSIONS = [\".db\", \".sqlite\", \".sqlite3\"];\n\n// Infer the dialect from a connection string. Accepts every form Bun's `SQL`\n// accepts, including the bare SQLite paths (`./dev.db`, `:memory:`) that have no\n// protocol at all.\n//\n// Note this deliberately does NOT default to postgres the way `new SQL(...)`\n// does. Guessing the dialect wrong means generating SQL that fails at runtime\n// against a database that connected fine, which is a far more confusing failure\n// than refusing to guess.\nexport function inferDialect(url: string): Dialect {\n const trimmed = url.trim();\n\n if (trimmed === \"\") {\n throw new UnknownDatabaseUrlError(url);\n }\n\n // `:memory:` is SQLite's in-memory database. It looks like a protocol to\n // `new URL()` but isn't one, so it has to be checked before parsing.\n if (trimmed === \":memory:\") {\n return \"sqlite\";\n }\n\n const separator = trimmed.indexOf(\":\");\n if (separator !== -1) {\n const protocol = trimmed.slice(0, separator + 1).toLowerCase();\n const dialect = PROTOCOLS[protocol];\n if (dialect) {\n return dialect;\n }\n }\n\n // No recognised protocol. Bun treats a bare path as a SQLite file, so we do\n // too — but only when it actually looks like one, rather than treating every\n // unrecognised string as SQLite.\n if (looksLikeSqlitePath(trimmed)) {\n return \"sqlite\";\n }\n\n throw new UnknownDatabaseUrlError(url);\n}\n\nfunction looksLikeSqlitePath(value: string): boolean {\n if (value.startsWith(\"./\") || value.startsWith(\"../\") || value.startsWith(\"/\")) {\n return true;\n }\n const lower = value.toLowerCase();\n return SQLITE_FILE_EXTENSIONS.some((extension) => lower.endsWith(extension));\n}\n\n// True when the dialect stores a SQLite database, i.e. a local file rather than\n// a networked server. Callers use this to decide whether `db:setup` should\n// create a file, and which DDL flavour to emit.\nexport function isSqlite(dialect: Dialect): boolean {\n return dialect === \"sqlite\";\n}\n\n// MariaDB is wire-compatible with MySQL and takes the same SQL in everything\n// gemi generates, so query builders collapse the two.\nexport function isMysqlFamily(dialect: Dialect): boolean {\n return dialect === \"mysql\" || dialect === \"mariadb\";\n}\n",
7
- "import { existsSync, readFileSync, realpathSync, statSync } from \"node:fs\";\nimport { isAbsolute, join, resolve } from \"node:path\";\n\nimport type { Dialect } from \"./dialect\";\n\n/**\n * Where a relative SQLite `DATABASE_URL` actually points.\n *\n * ## The disagreement\n *\n * `DATABASE_URL=file:./dev.db` is the template's default and Prisma's own\n * convention. Prisma resolves it **relative to the directory holding the schema\n * file**, so `prisma migrate dev` writes `prisma/dev.db`. Bun's `SQL` client\n * resolves it relative to the process working directory, so gemi opened\n * `./dev.db` — a different file, which SQLite then *created*, empty. Every\n * query failed with `no such table`, and the 0-byte file left behind looked\n * like a database rather than the symptom.\n *\n * The two had to agree and did not, which is the same class of bug as the\n * `foreign_keys` pragma in `Connection.configure`: development ran under rules\n * the migrations did not share. This resolves the path the way Prisma does, so\n * one relative URL means one file.\n *\n * ## What is left alone\n *\n * Everything that is not ambiguous. `:memory:`, an absolute path, and a\n * networked dialect all pass through untouched, and so does a relative path in\n * an app with no `prisma/schema.prisma` — there is no schema directory to be\n * relative *to*, so the working directory is the only answer available and\n * stays the answer it always was.\n */\n\n/** Prisma's default schema location, relative to the project root. */\nconst SCHEMA_PATH = join(\"prisma\", \"schema.prisma\");\n\n/**\n * The url moved, and the file it used to name holds data.\n *\n * Thrown rather than warned, and rather than choosing. The app was reading the\n * working-directory file until now and that file has rows in it; the resolved one\n * is where Prisma migrates. Which of them matters is not knowable from here — the\n * resolved file may not even exist yet — and the failure mode of guessing is\n * silent: the app runs, against an empty database or against the wrong half of\n * its own history.\n */\nexport class AmbiguousSqlitePathError extends Error {\n constructor(url: string, resolved: string, stranded: string) {\n super(\n `\"${url}\" now resolves to ${resolved}, which is where Prisma migrates it. ` +\n `gemi used to open ${stranded} instead, and that file holds data — so ` +\n `opening the resolved one would quietly leave it behind. gemi will not ` +\n `choose. Move ${stranded} onto ${resolved} if it is the database you ` +\n `want, or point DATABASE_URL at an absolute path to say so explicitly.`,\n );\n this.name = \"AmbiguousSqlitePathError\";\n }\n}\n\nexport type SqliteResolution = {\n /** The URL to hand to the client, in the form it arrived in. */\n url: string;\n /** Set when the path was rewritten: where it used to point, and where it\n * points now. `undefined` when nothing changed. */\n moved?: { from: string; to: string };\n};\n\n/**\n * Splits a SQLite URL into the prefix to put back and the file path itself.\n *\n * `null` for a URL with no file path to resolve — an in-memory database, or a\n * form this does not recognise, both of which are handed on untouched.\n */\nfunction splitSqliteUrl(url: string): { prefix: string; file: string } | null {\n const trimmed = url.trim();\n\n // The prefix is sliced off first, and `:memory:` tested after — the other way\n // round, only the three exact spellings written out longhand were recognised,\n // and `sqlite::memory:` and `file::memory:?cache=shared` (both of which Bun\n // opens in memory) were resolved as if `:memory:` were a file name. That\n // produced a real file called `:memory:` inside `prisma/`, silently, with\n // nothing stranded for the guard below to notice.\n //\n // The original casing is kept rather than the matched constant, so a URL is\n // handed back as it arrived.\n let prefix = \"\";\n let file = trimmed;\n for (const candidate of [\"file://\", \"file:\", \"sqlite://\", \"sqlite:\"]) {\n if (trimmed.slice(0, candidate.length).toLowerCase() === candidate) {\n prefix = trimmed.slice(0, candidate.length);\n file = trimmed.slice(candidate.length);\n break;\n }\n }\n\n // In memory, however it was spelled and whatever query string follows. Not a\n // path, and `resolve` would happily turn it into one.\n if (file === \":memory:\" || file.startsWith(\":memory:?\")) {\n return null;\n }\n\n return { prefix, file };\n}\n\n/**\n * The file a SQLite URL names, resolved the way Prisma resolves it.\n *\n * `cwd` is a parameter rather than read here so the tests can point it at a\n * fixture directory instead of the process's own.\n */\nexport function resolveSqliteUrl(\n url: string,\n dialect: Dialect,\n cwd: string = process.cwd(),\n): SqliteResolution {\n if (dialect !== \"sqlite\") {\n return { url };\n }\n\n const split = splitSqliteUrl(url);\n if (!split || split.file === \"\") {\n return { url };\n }\n\n // An absolute path says exactly what it means; there is nothing to resolve\n // and nothing the two tools could disagree about.\n //\n // Unobservable, and kept anyway: `path.resolve` ignores its base for an\n // absolute segment, so the `from === to` check below reaches the same answer\n // and no test can tell the two apart. This states the intent where a reader\n // looks for it, and saves a `statSync` on every connection that has one.\n if (isAbsolute(split.file)) {\n return { url };\n }\n\n // Query parameters — `?mode=ro`, Prisma's `?connection_limit=` — belong to\n // the URL, not to the file name.\n const query = split.file.indexOf(\"?\");\n const file = query === -1 ? split.file : split.file.slice(0, query);\n const suffix = query === -1 ? \"\" : split.file.slice(query);\n\n const schemaDirectory = join(cwd, \"prisma\");\n if (!prismaMigratesThisUrl(cwd, url)) {\n // Not the database Prisma migrates — no schema at all, a datasource that is\n // not SQLite, or a connection whose url is simply a different one. Nothing\n // else has an opinion about where this points, so it is left as it arrived.\n return { url };\n }\n\n const from = resolve(cwd, file);\n const to = resolve(schemaDirectory, file);\n if (from === to) {\n return { url };\n }\n\n return { url: `${split.prefix}${to}${suffix}`, moved: { from, to } };\n}\n\n/**\n * Whether THIS url is the one Prisma migrates.\n *\n * Not \"does a Prisma schema exist\", and not \"is its datasource SQLite\" — both\n * are questions about the project, and the answer was being applied to every\n * connection. A project has one Prisma datasource and may open any number of\n * SQLite connections through `connections`; a secondary one is not something\n * Prisma has ever seen, so repointing it into `prisma/` either produced an empty\n * database or an `AmbiguousSqlitePathError` whose message — \"the file Prisma\n * migrates\" — was false about that file.\n *\n * So the datasource's own url is read and compared. `url = env(\"DATABASE_URL\")`\n * resolves through the environment, a quoted literal is taken as written, and a\n * connection whose url is neither is left exactly as it arrived.\n *\n * Read with a regex rather than Prisma's parser: this needs two fields out of\n * one block, and the dependency would be a poor trade. Line comments are\n * stripped first, so a commented-out datasource cannot answer for the live one.\n * Anything unreadable answers no, which lands on the old behaviour.\n */\nfunction prismaMigratesThisUrl(cwd: string, url: string): boolean {\n const schema = join(cwd, SCHEMA_PATH);\n if (!existsSync(schema)) return false;\n let source: string;\n try {\n source = readFileSync(schema, \"utf8\");\n } catch {\n return false;\n }\n // `//` to end of line. Prisma has no block comments, and a `//` inside the\n // quoted url would be part of a protocol this function does not act on.\n const live = source.replace(/^\\s*\\/\\/.*$/gm, \"\");\n const datasource = live.match(/datasource\\s+\\w+\\s*\\{([\\s\\S]*?)\\}/);\n if (!datasource) return false;\n const block = datasource[1]!;\n if (!/provider\\s*=\\s*[\"']sqlite[\"']/.test(block)) return false;\n\n const fromEnv = block.match(/url\\s*=\\s*env\\(\\s*[\"']([^\"']+)[\"']\\s*\\)/);\n if (fromEnv) {\n const value = process.env[fromEnv[1]!];\n return typeof value === \"string\" && value.trim() === url.trim();\n }\n const literal = block.match(/url\\s*=\\s*[\"']([^\"']+)[\"']/);\n return literal ? literal[1]!.trim() === url.trim() : false;\n}\n\n/**\n * The database an app was opening before this resolution moved it, when that\n * file holds data.\n *\n * A 0-byte file is the artifact of the bug — SQLite creates an empty file for a\n * path that does not exist — so finding one is the expected case and says\n * nothing. A file with pages in it is the other thing entirely: two databases,\n * one URL, and no way to tell from here which one the app meant. Choosing\n * silently would be choosing somebody's data.\n */\nexport function strandedDatabase(moved: { from: string; to: string }): string | null {\n try {\n // The same file reached two ways is not two databases. `statSync` follows\n // symlinks, so an app that had already worked around this by symlinking the\n // old path onto the real database would otherwise be refused for finding\n // its own data where it put it.\n if (realpathSync(moved.from) === realpathSync(moved.to)) return null;\n } catch {\n // One of the two is not there, which is the ordinary case — fall through and\n // let the stat below decide.\n }\n try {\n const stats = statSync(moved.from);\n return stats.isFile() && stats.size > 0 ? moved.from : null;\n } catch {\n // Not there at all, which is the ordinary case for an app that has only\n // ever run migrations.\n return null;\n }\n}\n",
8
- "import { SQL } from \"bun\";\nimport type { ConnectionConfig } from \"./config\";\nimport { MissingDatabaseUrlError, inferDialect, type Dialect } from \"./dialect\";\nimport { AmbiguousSqlitePathError, resolveSqliteUrl, strandedDatabase } from \"./sqlitePath\";\n\n/**\n * The name of the connection an application gets without asking for one: the\n * `url` / `options` pair at the top level of `app/config/database.ts`.\n *\n * A constant rather than the string spelled at each site, because it is\n * compared in five places across three layers — the manager resolving a name,\n * the ORM deciding whether a query names a different pool than the open\n * transaction, and the facade — and a typo in any one of them reads as \"that\n * connection is not configured\" rather than as a typo.\n */\nexport const DEFAULT_CONNECTION = \"default\";\n\n/**\n * What every layer above `database/` is allowed to know about a connection.\n *\n * `DatabaseManager` implements this itself and *is* the default connection —\n * see the note on `DatabaseManager.connection`. So this interface is the one\n * shape the ORM and the `DB` facade read, whether they are looking at the\n * default pool or at a named one, and neither has to branch on which it got.\n */\nexport interface DatabaseConnection {\n /** `\"default\"`, or the key this connection was declared under. */\n readonly name: string;\n readonly url: string;\n readonly dialect: Dialect;\n readonly sql: SQL;\n readonly ready: Promise<void>;\n readonly config: ConnectionConfig;\n}\n\n/** A connection named in the config that the manager has no pool for. */\nexport class UnknownConnectionError extends Error {\n constructor(name: string, known: readonly string[]) {\n super(\n `No database connection named \"${name}\". Configured: ` +\n `${known.map((one) => `\"${one}\"`).join(\", \")}. Declare it under ` +\n `\\`connections\\` in app/config/database.ts.`,\n );\n this.name = \"UnknownConnectionError\";\n }\n}\n\n/**\n * A `connections` entry that would shadow the top-level `url`.\n *\n * Refused rather than merged, because the two spellings would be a silent\n * either/or: whichever the manager happened to build last would win, and the\n * losing half of the config would go on describing a pool nothing uses.\n */\nexport class ReservedConnectionNameError extends Error {\n constructor(name: string) {\n super(\n `\"${name}\" is the name of the connection declared by the top-level ` +\n `\\`url\\` and \\`options\\`, so it cannot also appear under ` +\n `\\`connections\\`. Rename it, or move its settings up to the top level.`,\n );\n this.name = \"ReservedConnectionNameError\";\n }\n}\n\n/**\n * A statement that named one connection while a transaction was open on\n * another.\n *\n * **The whole reason named connections refuse rather than route.** A\n * transaction lives on one reserved connection of one pool; there is no\n * mechanism by which a second pool's statement could join it, and no rollback\n * that could take it back. So the alternatives to this error are both worse\n * than an error:\n *\n * - Run it on the other pool anyway, *outside* the transaction. The caller\n * wrote `Model.transaction`, the block rolls back, and that one statement\n * stays committed. Half the work landed and nothing said so.\n * - Run it on the open handle, ignoring the name. Then the statement went to\n * the wrong database, which the ORM cannot even detect afterwards — the\n * tables are usually the same shape.\n *\n * There is no third answer at this layer; two-phase commit is not what a second\n * pool for analytics is asking for. So the failure is made loud and early, at\n * the call that would have straddled the two, and the fix is always the same\n * shape: move that query outside the transaction, or do the whole unit on one\n * connection.\n */\nexport class CrossConnectionTransactionError extends Error {\n constructor(\n /** The connection the open transaction belongs to. */\n public readonly open: string,\n /** The connection the refused statement named. */\n public readonly requested: string,\n ) {\n super(\n `A transaction is open on the \"${open}\" connection, and this statement ` +\n `names \"${requested}\". A transaction cannot span two connections: ` +\n `the statement would run outside it and stay committed when the ` +\n `transaction rolls back. Move this query outside the transaction, or ` +\n `run the whole unit on one connection.`,\n );\n this.name = \"CrossConnectionTransactionError\";\n }\n}\n\n/**\n * One pool: a URL, its dialect, and Bun's client for it.\n *\n * Extracted from `DatabaseManager` when a second connection became\n * configurable (#327). The manager kept the lifecycle — which names exist, how\n * they are resolved, closing them all — and this kept everything that is true\n * of a connection *one at a time*, so the two do not have to be written twice.\n *\n * Safe to build eagerly, like the manager it came from: Bun's client connects\n * on the first query, not at construction. A named connection an application\n * declares and never queries therefore costs an object.\n */\nexport class Connection implements DatabaseConnection {\n public readonly sql: SQL;\n public readonly dialect: Dialect;\n public readonly url: string;\n\n /**\n * Resolves once the connection has been configured, or rejects if it could\n * not be. Only SQLite has anything to do; elsewhere it is already resolved.\n *\n * Exposed so a caller that needs the guarantee can wait for it. Nothing has\n * to: SQLite queues statements on one connection in the order they were\n * issued, so the pragma below is ahead of anything a caller sends after the\n * constructor returns. That ordering is asserted in `DatabaseManager.test.ts`\n * rather than assumed, because it is the load-bearing half.\n */\n public readonly ready: Promise<void>;\n\n constructor(\n public readonly name: string,\n public readonly config: ConnectionConfig = {},\n ) {\n const url = config.url;\n if (!url) {\n throw new MissingDatabaseUrlError(name);\n }\n\n // An explicit `dialect` wins, for URLs whose protocol we can't read (a\n // pooler on a custom scheme). Otherwise infer, which throws rather than\n // guessing — see the note in dialect.ts.\n this.dialect = config.dialect ?? inferDialect(url);\n\n // Before the client is built, because this decides which file the client\n // opens — and SQLite creates whatever it is pointed at, so getting it\n // wrong leaves a convincing empty database rather than an error. See\n // `sqlitePath.ts` for why gemi and Prisma disagreed about it.\n const resolved = resolveSqliteUrl(url, this.dialect);\n if (resolved.moved) {\n const stranded = strandedDatabase(resolved.moved);\n if (stranded) {\n throw new AmbiguousSqlitePathError(url, resolved.moved.to, stranded);\n }\n }\n\n this.url = resolved.url;\n this.sql = config.options\n ? new SQL(this.url, config.options as any)\n : new SQL(this.url);\n this.ready = this.configure();\n }\n\n /**\n * `pragma foreign_keys = ON`, which SQLite leaves **off** by default — and so\n * does Bun's driver, which reports `0` on a fresh connection.\n *\n * Without it SQLite enforces nothing at all. Not \"cascades do not fire\":\n * nothing. An insert naming a parent that does not exist is accepted, a\n * dangling reference survives the parent's deletion, and `ON DELETE RESTRICT`\n * does not restrict — while the migrations declare all three. Postgres\n * enforces them always, and Prisma turns the pragma on for every SQLite\n * connection it opens, so leaving it off meant development and production\n * disagreed about whether the schema's constraints were real.\n *\n * It is also why this is more than a dialect gap. The differential harness\n * compares gemi against Prisma on one database per dialect; with the pragma\n * off on one side, the two were being asked to agree while running under\n * different integrity rules, so an entire class of divergence was invisible\n * to the instrument rather than merely untested.\n *\n * **Per connection, not per database**, which is what makes this a live\n * assumption rather than a one-line fix: Bun serves SQLite from a single\n * connection today, so setting it once holds for every later statement. If\n * that ever becomes a pool, one statement's worth of enforcement would move\n * to whichever connection happened to serve it. `DatabaseManager.test.ts`\n * pins both halves — the value, and that it is the same across concurrent\n * queries — so the day it changes is a failing test rather than a silent\n * regression.\n *\n * That per-connection wording is now literal in a second sense: a named\n * SQLite connection is a *different* Bun client, so it needs the pragma of\n * its own. Running it from this constructor is what makes that automatic —\n * the alternative, doing it once for the default connection, was correct\n * exactly while there was only one.\n *\n * Issued outside any transaction. SQLite documents the pragma as a no-op\n * inside one, so a lazy \"set it on first use\" would be correct exactly until\n * the first use happened to be a transaction.\n */\n private async configure(): Promise<void> {\n if (this.dialect !== \"sqlite\") return;\n await this.sql.unsafe(\"pragma foreign_keys = ON\");\n }\n\n // Escape hatch matching Bun's own API, so `connection.query` reads like `sql`\n // does in Bun's docs: connection.query`select * from users where id = ${id}`\n get query(): SQL {\n return this.sql;\n }\n\n async close(): Promise<void> {\n // A close that races the constructor's `pragma` leaves that statement to\n // settle against a client that is going away, and it settles as a rejection\n // — `ERR_SQLITE_CONNECTION_CLOSED`, from a promise nobody is holding, which\n // arrives as an unhandled rejection naming neither the close nor the\n // pragma. The caller asked for this connection to go away, so that\n // rejection is expected rather than something to surface. Marked handled\n // here rather than suppressed globally, and only on the way out.\n this.ready.catch(() => {});\n await this.sql.close();\n }\n}\n",
9
- "import type { SQL } from \"bun\";\nimport type { ConnectionConfig, DatabaseConfig } from \"./config\";\nimport {\n Connection,\n DEFAULT_CONNECTION,\n ReservedConnectionNameError,\n UnknownConnectionError,\n type DatabaseConnection,\n} from \"./Connection\";\nimport type { Dialect } from \"./dialect\";\n\n// Wraps Bun's `SQL` client. Bun ships one client that speaks SQLite, Postgres,\n// MySQL and MariaDB, so gemi does not need a driver per database — it needs to\n// know *which* one is in use, which is what `dialect` carries.\n//\n// Safe to build eagerly: Bun's client connects on the first query, not at\n// construction. (`RedisManager` used to be cited here as the parallel case. As\n// of #403 it builds its client in a memoizing getter instead — not because\n// eager construction was unsafe, but because naming Bun's `RedisClient` at\n// module scope is what made `gemi/services` unloadable off Bun. `Connection`\n// still imports `SQL` as a value for the same reason, which is the remaining\n// half of #396.) It is still bound as a lazy singleton,\n// so an app that never touches the database never resolves it and never has to\n// have DATABASE_URL set.\n//\n// Since #327 it holds *connections*, plural: the top-level `url` and `options`\n// build the one called `\"default\"`, and each key under `connections` builds\n// another. What it does not do is decide which one a query uses — that is the\n// ORM's ambient scope and the `DB` facade, because the choice is per query\n// rather than per application. See `connection` below.\nexport class DatabaseManager implements DatabaseConnection {\n static token = \"database\";\n\n /**\n * This object *is* the default connection, so it answers to the name.\n *\n * Not a formality: `connection(\"default\")` returns `this` rather than the\n * `Connection` in the map, which is what keeps every existing reader —\n * `DB.sql`, `db.dialect`, and the test harnesses that wrap the manager in a\n * Proxy to count statements — looking at the same object the ORM executes\n * through. A second object for the default pool would have quietly bypassed\n * all of them while every test still passed.\n */\n public readonly name = DEFAULT_CONNECTION;\n\n /**\n * Every pool this manager owns, keyed by name and including the default one.\n *\n * Private because the map is the manager's bookkeeping — `connection()` is\n * the way in, and it is the only path that knows the default is `this`.\n */\n private readonly pools = new Map<string, Connection>();\n\n /**\n * Resolves once **every** connection has been configured, or rejects if one\n * could not be. Only SQLite has anything to do; elsewhere it is already\n * resolved.\n *\n * All of them rather than the default alone, because the thing a caller waits\n * on this for — SQLite's `pragma foreign_keys` — is per client, so a second\n * SQLite connection has its own and a caller awaiting one manager-level\n * promise means all of them.\n */\n public readonly ready: Promise<void>;\n\n constructor(public config: DatabaseConfig = {}) {\n const { connections = {}, ...primary } = config;\n\n // The default first, so a `MissingDatabaseUrlError` from a missing\n // `DATABASE_URL` still comes out of construction the way it always has,\n // rather than after a named connection has already opened a client.\n this.pools.set(\n DEFAULT_CONNECTION,\n new Connection(DEFAULT_CONNECTION, primary),\n );\n\n // A connection that is built before the one whose config is wrong is still\n // a live client with an open handle, and on the throwing path nothing else\n // will ever hold it: the manager never becomes a value, so nobody can call\n // `close`. Left alone, the pragma this constructor issues for a SQLite\n // connection settles against a client being torn down and surfaces as an\n // unhandled rejection with no configuration error anywhere near it.\n try {\n this.build(connections, primary.slowTransactionThreshold);\n } catch (error) {\n for (const pool of this.pools.values()) {\n // The in-flight configuration first: it is what rejects when the client\n // under it goes away, and this is the only place that can say the\n // rejection was expected.\n pool.ready.catch(() => {});\n pool.close().catch(() => {});\n }\n throw error;\n }\n\n // Built once here rather than derived per read, so that a connection whose\n // configuration rejects produces one unhandled rejection at most instead of\n // a fresh one per access.\n this.ready = Promise.all(\n [...this.pools.values()].map((pool) => pool.ready),\n ).then(() => undefined);\n }\n\n private build(\n connections: Record<string, ConnectionConfig>,\n slowTransactionThreshold: number | false | undefined,\n ): void {\n for (const [name, connection] of Object.entries(connections)) {\n if (name === DEFAULT_CONNECTION)\n throw new ReservedConnectionNameError(name);\n\n this.pools.set(\n name,\n new Connection(name, {\n // The threshold is the one setting a named connection is likely to\n // want *unchanged*: it is a development diagnostic about holding a\n // pooled connection, and that concern does not stop applying because\n // the pool has a name. `url`, `options` and `dialect` are deliberately\n // not inherited — a connection that borrowed the default's URL by\n // omission would be a second pool onto the same database created by a\n // typo in a key.\n slowTransactionThreshold,\n ...connection,\n }),\n );\n }\n }\n\n /**\n * The connection called `name`, or the default one when called with nothing.\n *\n * Throws rather than falling back to the default for an unknown name, and\n * that is the important half. A fallback would make `Model.on(\"analitycs\")`\n * run on the hot path — the exact pool the caller was trying to stay off —\n * and the only symptom would be the incident it was meant to prevent,\n * arriving weeks later with nothing pointing back at the typo.\n */\n connection(name: string = DEFAULT_CONNECTION): DatabaseConnection {\n // `this`, not `pools.get(DEFAULT_CONNECTION)` — see `name` above.\n if (name === DEFAULT_CONNECTION) return this;\n\n const found = this.pools.get(name);\n if (!found) throw new UnknownConnectionError(name, this.connectionNames);\n return found;\n }\n\n /** Every configured name, default first. For error messages and diagnostics. */\n get connectionNames(): string[] {\n return [...this.pools.keys()];\n }\n\n /**\n * The default connection's client. Unchanged in meaning: an application that\n * never names a connection sees exactly what it saw before #327.\n */\n get sql(): SQL {\n return this.default.sql;\n }\n\n get dialect(): Dialect {\n return this.default.dialect;\n }\n\n get url(): string {\n return this.default.url;\n }\n\n // Escape hatch matching Bun's own API, so `db.query` reads like `sql` does in\n // Bun's docs: db.query`select * from users where id = ${id}`\n get query(): SQL {\n return this.sql;\n }\n\n /** Closes every connection, not only the default one. */\n async close(): Promise<void> {\n // The aggregate promise needs the same treatment each connection's own\n // `ready` gets in `Connection.close` — it is derived from them, so a\n // rejection there arrives here as a second, separately unhandled one.\n this.ready.catch(() => {});\n await Promise.all([...this.pools.values()].map((pool) => pool.close()));\n }\n\n private get default(): Connection {\n return this.pools.get(DEFAULT_CONNECTION)!;\n }\n}\n"
10
- ],
11
- "mappings": ";AA6FO,SAAS,CAAoB,CAAC,EAAwC,CAC3E,OAAO,EAGF,SAAS,CAAsB,EAAmB,CACvD,MAAO,CACL,IAAK,QAAQ,IAAI,aACjB,QAAS,OACT,QAAS,OACT,yBAA0B,EAC1B,YAAa,MACf,EAOK,IAAM,EAA6B,KCxGnC,MAAM,UAAgC,KAAM,CACjD,WAAW,CAAC,EAAa,CACvB,MACE,4CAA4C,sFAE1C,2EACJ,EACA,KAAK,KAAO,0BAEhB,CAEO,MAAM,UAAgC,KAAM,CAKjD,WAAW,CAAC,EAAqB,CAC/B,MACE,IAAe,QAAa,IAAe,UACvC,iHAEA,QAAQ,sEACiB,gCAC/B,EACA,KAAK,KAAO,0BAEhB,CAEA,IAAM,EAAqC,CACzC,YAAa,WACb,cAAe,WACf,SAAU,QACV,WAAY,UACZ,UAAW,SACX,QAAS,QACX,EAEM,EAAyB,CAAC,MAAO,UAAW,UAAU,EAUrD,SAAS,CAAY,CAAC,EAAsB,CACjD,IAAM,EAAU,EAAI,KAAK,EAEzB,GAAI,IAAY,GACd,MAAM,IAAI,EAAwB,CAAG,EAKvC,GAAI,IAAY,WACd,MAAO,SAGT,IAAM,EAAY,EAAQ,QAAQ,GAAG,EACrC,GAAI,IAAc,GAAI,CACpB,IAAM,EAAW,EAAQ,MAAM,EAAG,EAAY,CAAC,EAAE,YAAY,EACvD,EAAU,EAAU,GAC1B,GAAI,EACF,OAAO,EAOX,GAAI,EAAoB,CAAO,EAC7B,MAAO,SAGT,MAAM,IAAI,EAAwB,CAAG,EAGvC,SAAS,CAAmB,CAAC,EAAwB,CACnD,GAAI,EAAM,WA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MAAM,MAAM,IAAM,EAAE,EACzB,MAAM,QAAQ,IAAI,CAAC,GAAG,KAAK,MAAM,OAAO,CAAC,EAAE,IAAI,CAAC,IAAS,EAAK,MAAM,CAAC,CAAC,KAG5D,QAAO,EAAe,CAChC,OAAO,KAAK,MAAM,IAAI,CAAkB,EAE5C",
12
- "debugId": "5D03A4CD2C51C54764756E2164756E21",
13
- "names": []
14
- }
@@ -1,5 +0,0 @@
1
- // @bun
2
- import{Xe as o}from"./chunk-g7exgg3k.js";import{Ye as i}from"./chunk-bhycdjcv.js";import{kl as t}from"./chunk-6wv3k8ap.js";import{qm as r}from"./chunk-kbz5s9wb.js";class n extends i{register(){this.app.singleton(r,()=>new r(t(o(),this.app.config.get("translation",{}))))}}
3
- export{n as pb};
4
-
5
- //# debugId=94B0236723BFD40064756E2164756E21
@@ -1,13 +0,0 @@
1
- // @bun
2
- import{Kl as W,Rl as H,Ul as L}from"./chunk-2as2xfem.js";import{AsyncLocalStorage as A}from"async_hooks";var R=new A;function G(){let z=R.getStore();if(z?.tx===void 0||z.afterCommit===void 0)return z;if(!_.has(z.afterCommit))return z;return{...z,tx:void 0,depth:0,afterCommit:void 0,commitDependsOn:void 0,statementFailed:void 0,appliedSettings:void 0}}function c(){return G()?.tx}function v(){return G()?.connection??H}function l(z,B){let J=G();if(v()===z)return B();return O(z),R.run({...J,depth:J?.depth??0,connection:z===H?void 0:z},B)}function O(z){let B=G();if(B?.tx===void 0)return;let J=B.connection??H;if(J===z)return;throw new L(J,z)}function T(z){let B=R.getStore();if(B?.tx===void 0||B.afterCommit===void 0)return!1;let J=y.get(B.afterCommit);if(J==="committed")return!1;if(J==="rolled_back")return!0;return B.afterCommit.push(z),!0}var _=new WeakSet,y=new WeakMap;function i(z){if(T(z))return Promise.resolve();let B=(J)=>{console.error("An after-commit callback threw. No transaction was open, so it ran immediately.",J)};try{return Promise.resolve(z()).catch(B)}catch(J){return B(J),Promise.resolve()}}function a(z){let B=G();if(B?.tx!==void 0&&B.tx===z&&B.statementFailed)B.statementFailed.value=!0}function s(z){let B=G();if(B?.tx===void 0||B.commitDependsOn===void 0)return!1;return B.commitDependsOn.push(z),!0}class b extends Error{constructor(z){super(`A statement this transaction depended on failed after being issued on it, so the transaction rolled back instead of committing: ${z instanceof Error?z.message:String(z)}`,{cause:z});this.name="TransactionDependencyError"}}async function h(z,B){if(z.length===B)return;let K=(await Promise.allSettled(z.slice(B))).find((V)=>V.status==="rejected");if(K)throw new b(K.reason)}function n(){let z=G();return z?.tx===void 0?null:z.depth}function t(){return G()?.system===!0}function o(z){let B=G();return R.run({...B,depth:B?.depth??0,system:!0},z)}function r(z){return G()?.trashed?.get(z)}function e(z,B,J){let K=G(),V=new Map(K?.trashed);return V.set(z,B),R.run({...K,depth:K?.depth??0,trashed:V},J)}function zz(){return G()?.actor}function Bz(z,B){let J=G();return R.run({...J,depth:J?.depth??0,system:!1,actor:{user:z??null}},B)}function x(z){if(Bun.env.NODE_ENV!=="development")return null;if(z===!1)return null;if(z===void 0)return W;if(!Number.isFinite(z)||z<=0)return W;return z}function C(z){let B=x(z);if(B===null)return()=>{};let J=Error("transaction opened here"),K=setTimeout(()=>{let V=J.stack?.split(`
3
- `).slice(1).join(`
4
- `)??"";console.warn(`[gemi] A database transaction has not settled after ${B}ms. It `+"reserves a pooled connection until it does \u2014 check for network or "+`filesystem I/O inside the callback, and move it outside the transaction if you find any.
5
- ${V}
6
- (development only; set database.slowTransactionThreshold to change the threshold, or false to switch this off)`)},B);return K.unref?.(),()=>clearTimeout(K)}async function S(z,B){if(z.length===0)return;await R.run({...B,tx:void 0,afterCommit:void 0,commitDependsOn:void 0,depth:B?.depth??0},async()=>{for(let J of z)try{await J()}catch(K){console.error("An after-commit callback threw. The transaction it was waiting on had already committed and stays committed, and the callbacks after it still ran.",K)}})}function Jz(z,B,J){let K=G(),V=J?.connection??H;if(O(V),K?.tx){let P=K.afterCommit,Y=P?.length??0,$=K.commitDependsOn,X=$?.length??0;return K.tx.savepoint((j)=>{let M=j;return R.run({...K,tx:M,depth:K.depth+1},async()=>{let Z=await B(M);if($)await h($,X);return Z})}).catch((j)=>{if(P)P.length=Y;if($)$.length=X;throw j})}if(J?.dialect==="sqlite")return g(z,(P)=>w(z,B,J,K,V,P),J);return w(z,B,J,K,V)}var U=new WeakMap;class E extends Error{constructor(){super("A SQLite transaction started from inside an open transaction on the same connection, outside its scope (a raw `begin`, or an in-process call that left the transaction's scope while the transaction waits on it). SQLite runs one transaction per connection, so it would wait for the transaction that waits on it. Run it after the commit (`afterCommit`), or inside the transaction.");this.name="TransactionQueueDeadlockError"}}var Q=new WeakMap,D=new A,k=5000;function g(z,B,J={}){let K=D.getStore(),V={},P,Y=new Promise((X)=>{P=()=>{if(Q.get(z)===V)Q.delete(z);X()}}),$=U.get(z)??Promise.resolve();return U.set(z,Y),new Promise((X,j)=>{let M=!1,Z=x(J.slowTransactionThreshold)===null?void 0:Error("transaction queued here"),q=setTimeout(()=>{let F=Q.get(z);if(F&&K?.has(F)){M=!0,j(new E);return}if(Z)f(Z)},k);q.unref?.(),$.then(()=>{if(clearTimeout(q),M){P();return}Q.set(z,V);let F=D.run(new Set([...K??[],V]),()=>B(P));F.then(P,P),F.then(X,j)})})}function f(z){let B=z.stack?.split(`
7
- `).slice(1).join(`
8
- `)??"";console.warn(`[gemi] A SQLite transaction has waited ${k}ms for the one open on its connection (SQLite runs one at a time per connection). Look for a long transaction, or one that waits on work started outside it.
9
- ${B}
10
- (development only; database.slowTransactionThreshold: false switches it off)`)}function w(z,B,J,K,V,P){let Y=C(J?.slowTransactionThreshold),$=P?[P]:[],X=[],j=new Map,M={value:!1};try{return z.begin((Z)=>R.run({...K,tx:Z,depth:0,connection:V===H?void 0:V,afterCommit:$,commitDependsOn:X,appliedSettings:j,statementFailed:M},async()=>{if(!J?.deferSettings)await I(Z,K?.settings,j);try{let q=await B(Z);if(await h(X,0),M.value)await Z.unsafe("select 1");return q}finally{_.add($)}})).finally(Y).then(async(Z)=>{return y.set($,"committed"),await S($,K),Z},(Z)=>{throw y.set($,"rolled_back"),Z})}catch(Z){throw Y(),Z}}var m=/^[A-Za-z_][A-Za-z0-9_$]*(\.[A-Za-z_][A-Za-z0-9_$]*)+$/;class N extends Error{setting;outer;inner;constructor(z,B,J){super(`DB.withSettings: "${z}" is already "${B}" in an enclosing withSettings block, and a nested block can't change it to "${J}". Open a separate block outside the first one.`);this.setting=z;this.outer=B;this.inner=J;this.name="SessionSettingConflictError"}}function Kz(){let z=G()?.settings;return z&&Object.keys(z).length>0?z:void 0}async function I(z,B,J){if(!B)return[];let K=Object.entries(B).filter(([P,Y])=>J.get(P)!==Y);if(K.length===0)return[];let V=K.map((P,Y)=>`set_config($${Y*2+1}, $${Y*2+2}, true)`);await z.unsafe(`select ${V.join(", ")}`,K.flatMap(([P,Y])=>[P,Y]));for(let[P,Y]of K)J.set(P,Y);return K.map(([P])=>P)}async function Pz(){let z=G();if(z?.tx&&z.appliedSettings)await I(z.tx,z.settings,z.appliedSettings)}async function Vz(z,B){let J=G(),K=J?.settings??{},V={...K};for(let[X,j]of Object.entries(z)){if(!m.test(X))throw Error(`DB.withSettings: "${X}" is not a custom setting name. Use a prefix and a dot, like "app.tenant_id".`);let M=j===null?"":String(j);if(Object.hasOwn(K,X)&&K[X]!==M)throw new N(X,K[X],M);V[X]=M}let P={...J,depth:J?.depth??0,settings:V},Y=J?.tx,$=J?.appliedSettings;if(!Y||!$)return R.run(P,B);return R.run(P,async()=>{let X=await I(Y,V,$),j=async()=>{if(X.length===0)return;let Z=X.map((q,F)=>`set_config($${F+1}, '', true)`);await Y.unsafe(`select ${Z.join(", ")}`,X);for(let q of X)$.delete(q)},M;try{M=await B()}catch(Z){throw await j().catch(()=>{}),Z}return await j(),M})}
11
- export{R as ll,c as ml,v as nl,l as ol,O as pl,T as ql,i as rl,a as sl,s as tl,b as ul,n as vl,t as wl,o as xl,r as yl,e as zl,zz as Al,Bz as Bl,Jz as Cl,g as Dl,N as El,Kz as Fl,Pz as Gl,Vz as Hl};
12
-
13
- //# debugId=80489B2923262AF164756E2164756E21
@@ -1,10 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../orm/context.ts"],
4
- "sourcesContent": [
5
- "import type { SQL, TransactionSQL } from \"bun\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { SLOW_TRANSACTION_THRESHOLD } from \"../database/config\";\nimport {\n CrossConnectionTransactionError,\n DEFAULT_CONNECTION,\n} from \"../database/Connection\";\n\n/**\n * The ambient transaction: the ORM's own `AsyncLocalStorage`, holding nothing\n * but the open handle and how deep the nesting is.\n *\n * One store per scope with one owner, which is the pattern the framework\n * already follows — `kernel/context.ts` holds the Application,\n * `http/requestContext.ts` the request and its user. The reasoning for\n * not folding this into the kernel's is written up beside it, and the short\n * version is that a transaction scope has to *nest inside* an Application scope\n * without replacing it, and `foundation/app.ts` must keep reading exactly one\n * shape out of the kernel store or resolving a service becomes a transaction\n * concern.\n *\n * What makes an ALS the right home rather than a field somewhere: two concurrent\n * requests each in their own transaction must never see each other's handle.\n * Anything reachable from the Application — which is one object shared by every\n * in-flight request — fails that by construction, and fails it as silently\n * written data, not as an error. \"two concurrent transactions never see each\n * other's handle\" in `context.test.ts` is the test that would catch it.\n */\nexport interface OrmScope {\n /**\n * Bun's transaction handle. Every ORM statement in scope runs on it, which\n * means they all run on one reserved connection — so nothing here may issue\n * two statements concurrently. `Model.$exec` already runs its nested writes\n * and its relation reads sequentially, for exactly this reason.\n */\n tx?: TransactionSQL;\n /** 0 for the outermost transaction, 1+ for each savepoint inside it. */\n depth: number;\n /**\n * Which named connection this subtree's queries run on, and — when `tx` is\n * set — which connection the open transaction belongs to.\n *\n * Ambient rather than an argument threaded through `$exec`, for the same\n * reason the handle above is: a relation read resolves its target through the\n * registry and calls that class's `$exec`, so an argument would have to be\n * carried by every intermediate that has no interest in it, and the one that\n * forgot would silently read a nested `include` off the *other* pool. There\n * is no error that shape produces; there are just rows from the wrong place.\n *\n * `undefined` means the default connection. Kept as absent-rather-than-\n * `\"default\"` so that entering a scope on the default connection is\n * indistinguishable from not entering one, which is what makes the\n * cross-connection check below cost a comparison of two `undefined`s on every\n * application that never declares a second connection.\n */\n connection?: string;\n /**\n * Whether policies are suspended for this scope. Set only by\n * `Model.asSystem`, and never by anything ambient — the whole point is that\n * unscoped access is a decision visible at the call site, not the accidental\n * result of a missing user.\n */\n system?: boolean;\n /**\n * The user policies should scope to, when there is no request to read one\n * from. Set only by `Model.asUser`.\n *\n * A sentinel wrapper rather than the bare value, so that \"a scope was entered\n * with `null`\" stays distinguishable from \"no scope was entered\" — the two\n * mean different things under deny-by-default.\n */\n actor?: { user: unknown };\n /**\n * Work that must not happen unless this transaction commits — an event whose\n * `static afterCommit` is set, today, and nothing else.\n *\n * **Created by the outermost `withTransaction` and never by a savepoint.** A\n * savepoint's scope is a spread of its parent's (`{ ...current, tx: nested }`),\n * so the array arrives here already shared by reference with the transaction\n * that opened it — which is the behaviour wanted rather than a leak. A\n * dispatch made inside a savepoint that commits, in a transaction that then\n * rolls back, must not run: rolling back the outermost transaction discards\n * the list whole, savepoint entries included, because nothing ever drains it.\n *\n * The inverse — a savepoint that rolls back under a transaction that commits\n * — is the case sharing gets wrong on its own, and `withTransaction`'s\n * savepoint branch is where it is put right.\n *\n * Absent, rather than an empty array, on every scope that is not a\n * transaction: `runAsSystem`, `runAsUser` and `runOnConnection` spread\n * whatever they are given, so \"there is a list here\" and \"there is an open\n * transaction here\" have to stay the same question. `deferUntilCommit`\n * answers `false` when either half is missing and the caller runs the work\n * now, which is what keeps a hand-built scope carrying a `tx` — the shape\n * tests write — from swallowing a dispatch into a list nothing drains.\n */\n afterCommit?: AfterCommitCallback[];\n /**\n * Statements written on `tx` that the commit must wait for and must not\n * outlive — today, a job row the database queue driver wrote on the\n * transaction (#563), and nothing else. See `commitDependsOn`.\n *\n * Created and shared exactly as `afterCommit` is, and truncated with it\n * when a savepoint rolls back.\n */\n commitDependsOn?: Promise<unknown>[];\n /**\n * Set when a statement the ORM or `DB` ran on `tx` failed. Shared by the\n * outermost transaction and its savepoints, like `afterCommit`.\n *\n * On Postgres a failed statement aborts the transaction, and a caller that\n * catches the error and returns normally used to get a resolved\n * `Model.transaction` whose `COMMIT` had quietly been a rollback: nothing\n * written, and the after-commit work ran anyway. Bun 1.4.3 and later reject\n * that `COMMIT` with `ERR_POSTGRES_COMMIT_ROLLED_BACK`; earlier versions\n * resolve. So when this is set, `withTransaction` asks the transaction one\n * `select 1` before it commits, which fails on an aborted transaction on\n * every Bun version, and costs nothing on the path where nothing failed.\n */\n statementFailed?: { value: boolean };\n /**\n * Models whose soft-delete scope (`static $softDeletes`) is lifted or\n * inverted for this async subtree, by name — set only by\n * `Model.withTrashed(fn)` / `Model.onlyTrashed(fn)`.\n *\n * Keyed by model name rather than class because a nested relation read\n * resolves its target through the registry by name, and the block has to\n * reach those reads too. A fresh map per block, never mutated, so an inner\n * block cannot leak its entry back into the enclosing one.\n */\n trashed?: ReadonlyMap<string, TrashedMode>;\n /**\n * Postgres session settings for this subtree (#1158), set by\n * `DB.withSettings`: applied with `set_config(name, value, true)` at the\n * start of every transaction opened here, and of the implicit transaction a\n * single ORM call or `DB.query` gets when none is open. A fresh object per\n * scope, never mutated.\n */\n settings?: Readonly<Record<string, string>>;\n /**\n * What has been applied on `tx` so far, by name. Created by the outermost\n * `withTransaction` and shared by reference with its savepoints, so a\n * `withSettings` block entered inside the transaction applies only what is\n * new and resets it on the way out.\n */\n appliedSettings?: Map<string, string>;\n}\n\n/**\n * How a soft-deleted model's trashed rows are treated: `\"with\"` includes them,\n * `\"only\"` reads nothing else. Absent means the default — they are hidden.\n */\nexport type TrashedMode = \"with\" | \"only\";\n\n/**\n * Work deferred to a transaction's commit.\n *\n * Awaited when it is drained, and its rejection is caught there: a callback is\n * a side effect that the transaction is not waiting on and cannot be told\n * about, so the only thing left to do with a failure is report it.\n *\n * Not exported: a caller passes a lambda and never names this, and an export\n * nothing outside this file uses is what `orm/architecture.test.ts` is pointed\n * at. The declaration emit carries it along regardless, so `OrmScope` stays\n * readable from a `.d.ts`.\n */\ntype AfterCommitCallback = () => void | Promise<void>;\n\n/**\n * One ambient scope for the ORM, not one per feature.\n *\n * Transactions (iteration 5) and system access (iteration 6) are both\n * \"something is true for this async subtree and every query in it\", so they\n * share a store rather than minting a second `AsyncLocalStorage` each. The\n * inventory note in `kernel/context.ts` sets the bar for adding one; two\n * booleans-worth of ORM state does not clear it.\n */\nexport const ormContext = new AsyncLocalStorage<OrmScope>();\n\n/**\n * The ambient scope, without its transaction once that transaction has\n * finished (#1376).\n *\n * Work a transaction starts and doesn't wait for (a `setTimeout`, an\n * un-awaited call, an emitter callback) inherits its scope, handle included.\n * Run after the commit or rollback, that work would otherwise take a\n * savepoint on a finished transaction, or write on its handle. Without the\n * transaction it is outside one, as it is: its `transaction()` opens one of\n * its own, and its statements run on the pool. While the transaction is\n * still open it stays inside it (nested calls the transaction awaits look\n * the same). `deferUntilCommit` reads the raw scope: it goes by how the\n * transaction ended.\n *\n * \"Finished\" starts when the transaction's callback is done with it, before\n * `COMMIT` or `ROLLBACK` is sent: during that round-trip the handle takes\n * statements outside any transaction.\n */\nfunction liveScope(): OrmScope | undefined {\n const store = ormContext.getStore();\n if (store?.tx === undefined || store.afterCommit === undefined) return store;\n if (!finishedLists.has(store.afterCommit)) return store;\n return {\n ...store,\n tx: undefined,\n depth: 0,\n afterCommit: undefined,\n commitDependsOn: undefined,\n statementFailed: undefined,\n appliedSettings: undefined,\n };\n}\n\n/**\n * The open transaction, or `undefined` outside one. This is what `Model.$exec`\n * consults to decide which connection a statement runs on.\n *\n * Exported as the escape hatch for code that genuinely needs the handle — a raw\n * query that must join the surrounding transaction, say. **Do not store what it\n * returns.** Bun's handle stays callable after its `begin` resolves: queries on\n * it then run on the pooled connection, outside any transaction, and succeed.\n * Verified against both dialects, and it is the reason `Model.transaction`'s\n * callback takes no argument.\n */\nexport function currentTransaction(): TransactionSQL | undefined {\n return liveScope()?.tx;\n}\n\n/**\n * The connection every query in this scope runs on unless it names another.\n *\n * `\"default\"` outside any scope, so callers get a name rather than a\n * `string | undefined` to normalise themselves — the store keeps it absent,\n * which is not the same distinction and is nobody else's business.\n */\nexport function currentConnectionName(): string {\n return liveScope()?.connection ?? DEFAULT_CONNECTION;\n}\n\n/**\n * Run `fn` with `name` as the ambient connection.\n *\n * Merged into the current scope rather than replacing it, exactly as\n * `runAsSystem` and `runAsUser` are: naming a connection must not drop an open\n * transaction handle or re-enable policies underneath it.\n *\n * Deliberately absent from `orm/index.ts`, so it is not part of what an\n * application can reach — `Model.on(name)` and `DB.connection(name)` are the\n * two doors, and both funnel through here so that a nested relation read,\n * which resolves its own class out of the registry and calls its `$exec`,\n * inherits the connection without anything having to pass it along.\n */\nexport function runOnConnection<T>(\n name: string,\n fn: () => Promise<T>,\n): Promise<T> {\n const current = liveScope();\n if (currentConnectionName() === name) return fn();\n\n // ENTERING A CONNECTION IS WHERE THE CROSS-CONNECTION CHECK BELONGS, not at\n // each door — and it has to be *here*, before the scope is entered, because\n // entering it is what makes the check impossible afterwards.\n //\n // The scope carries `tx` and `connection` together, so overwriting the name\n // while an open handle stays in place produces a store that says \"a\n // transaction on analytics\" while holding the *default* connection's handle.\n // Every check downstream then agrees with itself and the statement runs on\n // the wrong connection's transaction. `Model.save` found this: it routes to\n // the row's own connection, so it is the one caller that switches connections\n // with a transaction already open.\n assertConnectionUsable(name);\n\n return ormContext.run(\n {\n ...current,\n depth: current?.depth ?? 0,\n connection: name === DEFAULT_CONNECTION ? undefined : name,\n },\n fn,\n );\n}\n\n/**\n * Refuse a statement that names one connection while a transaction is open on\n * another.\n *\n * The check `withTransaction`'s single-connection note asked for, and the\n * reasoning for refusing rather than routing is on\n * `CrossConnectionTransactionError`. Both doors call it — `Model.$exec` for\n * every model operation, `DB` for a raw fragment — because either one alone\n * leaves the other free to straddle the two connections, and a raw `DB.execute`\n * escaping a transaction is the more damaging of the two.\n *\n * Only ever fires on a query that *names* a connection: an unqualified one\n * resolves to the ambient name, which is the transaction's own.\n */\nexport function assertConnectionUsable(name: string): void {\n const store = liveScope();\n if (store?.tx === undefined) return;\n\n const open = store.connection ?? DEFAULT_CONNECTION;\n if (open === name) return;\n\n throw new CrossConnectionTransactionError(open, name);\n}\n\n/**\n * Hold `callback` until the open transaction commits, and say whether that\n * happened.\n *\n * `false` means there was nothing to wait for — no transaction is open, or the\n * scope was entered by hand rather than by `withTransaction` — and the caller\n * must run the work itself, now. That return value is the whole contract: a\n * caller that ignores it turns \"no transaction here\" into a side effect queued\n * on a list nothing will ever drain, which is a dispatch that silently never\n * happens.\n *\n * `true` means the callback is on the outermost scope's list and will run after\n * `begin` resolves, outside the transaction, whatever the caller does next. It\n * will not run at all if the transaction rolls back, or if a savepoint it was\n * registered inside rolls back — both of which are the point.\n *\n * Nothing here is ordered against anything but the other deferred callbacks:\n * they run in registration order, one at a time, after the commit round-trip.\n */\nexport function deferUntilCommit(callback: AfterCommitCallback): boolean {\n // The raw scope: a settled transaction's list says what to do with it.\n const store = ormContext.getStore();\n if (store?.tx === undefined || store.afterCommit === undefined) return false;\n\n // Async work started inside a transaction and not awaited by it — a sync\n // listener still awaiting, an un-awaited emit — can reach here after the\n // transaction settled, through a scope that still carries its handle and its\n // list. Pushing then would queue onto a list already drained (or discarded),\n // and the work would silently never run. A committed list answers \"run it\n // now\"; a rolled-back one keeps the promise that nothing runs: the callback\n // may announce the transaction's own writes (#875). During COMMIT the\n // outcome isn't known yet, so it is queued and runs if the commit does.\n // Detached work that opened a transaction of its own (#1376) is on that\n // one's list instead.\n const settled = settledLists.get(store.afterCommit);\n if (settled === \"committed\") return false;\n if (settled === \"rolled_back\") return true;\n\n store.afterCommit.push(callback);\n return true;\n}\n\n/**\n * The after-commit lists of outermost transactions whose callback is done\n * (committing, rolled back or settled): what `liveScope` drops.\n */\nconst finishedLists = new WeakSet<AfterCommitCallback[]>();\n\n/**\n * How each outermost transaction's after-commit list ended, once it has. Keyed\n * by the list itself, which every savepoint and every lingering async scope of\n * that transaction shares by reference.\n */\nconst settledLists = new WeakMap<AfterCommitCallback[], \"committed\" | \"rolled_back\">();\n\n/**\n * Run `callback` once the open transaction commits, or now when none is open.\n * Never when the transaction rolls back, nor when a savepoint it was\n * registered inside rolls back.\n *\n * The application-facing form of `deferUntilCommit`, exported from `gemi/orm`\n * (#786). The difference is the `false` branch: `deferUntilCommit` hands the\n * \"no transaction\" case back to the caller, who must remember to run the work\n * itself, and this runs it. A caller that wants a side effect only once its\n * writes are durable — waking a long-poll, notifying another process — has\n * nothing left to get wrong.\n *\n * Inside a transaction the callback joins the same list `static afterCommit`\n * events use, so it is drained after `begin` resolves, outside the\n * transaction, in registration order with them.\n *\n * The returned promise resolves once the callback has run (no transaction) or\n * been queued (inside one). It never rejects: a callback that throws is\n * reported on stderr, as a deferred one is at the drain, so a caller that does\n * not await — the usual case — cannot leave an unhandled rejection behind, and\n * the two branches fail the same way. A sync callback outside a transaction\n * runs before this returns.\n */\nexport function afterCommit(\n callback: () => void | Promise<void>,\n): Promise<void> {\n if (deferUntilCommit(callback)) return Promise.resolve();\n\n const report = (error: unknown) => {\n console.error(\n `An after-commit callback threw. No transaction was open, so it ran ` +\n `immediately.`,\n error,\n );\n };\n try {\n return Promise.resolve(callback()).catch(report);\n } catch (error) {\n report(error);\n return Promise.resolve();\n }\n}\n\n/**\n * Record that a statement run on `handle` failed, when `handle` is the open\n * transaction's. See `OrmScope.statementFailed`. @internal\n */\nexport function noteFailedStatement(handle: unknown): void {\n const store = liveScope();\n if (store?.tx !== undefined && store.tx === handle && store.statementFailed) {\n store.statementFailed.value = true;\n }\n}\n\n/**\n * Make the open transaction's commit depend on `write`, a statement issued on\n * its handle: the transaction does not commit until `write` settles, and\n * rolls back — rejecting with `TransactionDependencyError` — if it rejected.\n *\n * For a write the caller may not await. A queued listener's dispatch never is\n * (`EventManager` pushes it and moves on), and on Postgres a statement that\n * fails aborts the whole transaction: every statement after it is refused and\n * Bun's `COMMIT` quietly becomes a rollback. Without this, the callback's\n * promise resolved, `begin` resolved, and the rows the caller wrote were gone\n * with nothing to say so. MySQL does not abort on a failed statement, and is\n * failed here anyway, so that a joined write means the same thing on both:\n * it commits with the transaction or the transaction does not commit.\n *\n * `false` when there is no transaction to depend on, as for\n * `deferUntilCommit`.\n */\nexport function commitDependsOn(write: Promise<unknown>): boolean {\n const store = liveScope();\n if (store?.tx === undefined || store.commitDependsOn === undefined) {\n return false;\n }\n store.commitDependsOn.push(write);\n return true;\n}\n\n/**\n * A write the transaction's commit depended on failed, so the transaction —\n * or the savepoint the write was made in — rolled back. `cause` is the write's\n * own error.\n */\nexport class TransactionDependencyError extends Error {\n constructor(cause: unknown) {\n super(\n `A statement this transaction depended on failed after being issued on ` +\n `it, so the transaction rolled back instead of committing: ` +\n `${cause instanceof Error ? cause.message : String(cause)}`,\n { cause },\n );\n this.name = \"TransactionDependencyError\";\n }\n}\n\n/**\n * Wait for the writes registered from `mark` on, and throw if one failed.\n *\n * Called at the end of a transaction's or savepoint's callback, *inside*\n * `begin`/`savepoint`, so a throw is what makes Bun roll back rather than\n * commit — after `begin` has resolved it is too late to do anything but\n * report. Every write is settled before throwing, so none is still running on\n * the handle when the rollback is issued.\n */\nasync function awaitDependencies(\n writes: Promise<unknown>[],\n mark: number,\n): Promise<void> {\n if (writes.length === mark) return;\n const settled = await Promise.allSettled(writes.slice(mark));\n const failed = settled.find(\n (outcome): outcome is PromiseRejectedResult => outcome.status === \"rejected\",\n );\n if (failed) throw new TransactionDependencyError(failed.reason);\n}\n\n/** How deeply nested the current transaction is; `null` outside one. */\nexport function transactionDepth(): number | null {\n const store = liveScope();\n return store?.tx === undefined ? null : store.depth;\n}\n\n/** Whether policies are suspended for the current async scope. */\nexport function isSystemScope(): boolean {\n return liveScope()?.system === true;\n}\n\n/**\n * Run `fn` with policies suspended.\n *\n * The escape hatch the deny-by-default rule needs to be usable: a cron tick, a\n * queue worker or a seed script has no user, and under deny-by-default every\n * policied model would refuse it. This makes that intent explicit *at the call\n * site*, which is the property that matters — unscoped access must never be\n * what happens when a user simply fails to turn up.\n *\n * It nests inside a transaction and a transaction nests inside it: the scope is\n * merged rather than replaced, so `asSystem` does not silently drop an open\n * handle.\n */\nexport function runAsSystem<T>(fn: () => Promise<T>): Promise<T> {\n const current = liveScope();\n return ormContext.run({ ...current, depth: current?.depth ?? 0, system: true }, fn);\n}\n\n/**\n * How `model`'s trashed rows are treated in this async scope, or `undefined`\n * for the default (hidden). See `OrmScope.trashed`.\n */\nexport function trashedMode(model: string): TrashedMode | undefined {\n return liveScope()?.trashed?.get(model);\n}\n\n/**\n * Run `fn` with `model`'s soft-delete scope lifted (`\"with\"`) or inverted\n * (`\"only\"`). Merged into the current scope like `runAsSystem`, so it keeps an\n * open transaction, the system flag and the actor — and every other policy.\n */\nexport function runWithTrashed<T>(\n model: string,\n mode: TrashedMode,\n fn: () => Promise<T>,\n): Promise<T> {\n const current = liveScope();\n const trashed = new Map(current?.trashed);\n trashed.set(model, mode);\n return ormContext.run(\n { ...current, depth: current?.depth ?? 0, trashed },\n fn,\n );\n}\n\n/** The explicitly-set actor, or `undefined` when none was. */\nexport function currentActor(): { user: unknown } | undefined {\n return liveScope()?.actor;\n}\n\n/**\n * Run `fn` with policies scoped to `user`, for code with no request to read one\n * from.\n *\n * The counterpart to `runAsSystem`, and the reason that one is not the only\n * escape hatch. A queue worker processing \"send the invoice for organisation 7\"\n * genuinely acts *as somebody*; giving it `asSystem` would suspend policies\n * entirely and leave it hand-scoping every query — which is precisely the\n * unscoped-by-accident failure the deny-by-default rule exists to prevent. The\n * narrow tool should be the easy one.\n *\n * It is also what makes policies testable without reaching into\n * `RequestContext`'s internals.\n *\n * Takes precedence over the request store, so a job that says who it is acting\n * as is not quietly overridden by an ambient request that happens to enclose it.\n *\n * It also **clears `system`**, which is the more surprising half. Acting as a\n * user is strictly narrower than acting as the system, so naming one inside an\n * `asSystem` block has to narrow back — and the spread would otherwise carry\n * `system: true` forward, leaving `$exec` to skip policies entirely while\n * `currentUser()` cheerfully returned the actor. Silently unscoped, from the\n * realistic shape: a worker enters `asSystem` to read its job queue, then\n * narrows to the job's owner for the work itself. The reverse nesting —\n * `asSystem` inside `asUser` — suspends policies, which is what it should do.\n */\nexport function runAsUser<T>(user: unknown, fn: () => Promise<T>): Promise<T> {\n const current = liveScope();\n return ormContext.run(\n {\n ...current,\n depth: current?.depth ?? 0,\n system: false,\n actor: { user: user ?? null },\n },\n fn,\n );\n}\n\n/**\n * The warning threshold in milliseconds, or `null` when the warning is off.\n *\n * `configured` is `database.slowTransactionThreshold` — see `DatabaseConfig`.\n * It arrives as a value rather than being read from here so that this file\n * keeps knowing nothing about the container: `withTransaction` is reachable\n * with a bare pool, and its tests use one.\n *\n * Exported for its own tests. The behaviour worth pinning is the fallback —\n * that a malformed threshold lands on the default rather than disabling — and\n * that cannot be observed through `withTransaction`: \"no warning fired\" is what\n * a disabled warning looks like too, so a behavioural test of it passes just as\n * happily when the fallback is gone. Asserting the number directly is the only\n * form of that test that can fail.\n */\nexport function slowTransactionThreshold(\n configured?: number | false,\n): number | null {\n // Read per call, never cached at module scope. `scripts/build.ts` rewrites\n // `process.env.NODE_ENV` to `Bun.env.NODE_ENV` precisely so mode stays a\n // runtime question in the built framework; caching it here would undo that.\n if (process.env.NODE_ENV !== \"development\") return null;\n\n // The one way to switch it off, and it has to be spelled. Everything else\n // falls back, so the warning is never lost to a mistyped value — only to an\n // explicit `false`.\n if (configured === false) return null;\n\n if (configured === undefined) return SLOW_TRANSACTION_THRESHOLD;\n if (!Number.isFinite(configured) || configured <= 0) {\n return SLOW_TRANSACTION_THRESHOLD;\n }\n return configured;\n}\n\n/**\n * Warn, in development only, about a transaction that has been open too long.\n *\n * The risk is structural rather than occasional: an open transaction holds one\n * reserved connection for as long as its callback runs, and nothing about\n * `Model.transaction(async () => { ... })` stops that callback from awaiting a\n * `fetch`, an S3 upload or a slow queue push. Under concurrency that drains the\n * pool, and the symptom — every unrelated query in the process blocking on\n * connection acquisition — names neither the callback nor the I/O in it.\n *\n * A timer rather than measuring elapsed time on the way out, for one reason:\n * the worst case is the transaction that *never* settles (a hung request, a\n * lock wait, a deadlock). After-the-fact measurement is silent for exactly that\n * case; a timer fires while it is still open and still holding the connection.\n *\n * The `Error` is constructed up front and read only if the timer fires — V8\n * formats `.stack` lazily on first access, so an ordinary fast transaction pays\n * for an object allocation and nothing else.\n *\n * The clock starts at the `begin` call, not at the moment a connection is\n * acquired, and stops when `begin` settles rather than when the callback\n * returns — so it spans the pool wait and the commit round-trip as well as the\n * callback. That is deliberate: all three are time this transaction is in\n * flight, and a warning that only covered the callback would stay silent for a\n * transaction stuck waiting on an exhausted pool, which is the exact situation\n * a long transaction elsewhere creates. Hence \"not settled\" rather than \"open\n * for\" — the message must not claim a connection was held for the whole span.\n */\nfunction watchForSlowTransaction(configured?: number | false): () => void {\n const threshold = slowTransactionThreshold(configured);\n if (threshold === null) return () => {};\n\n const site = new Error(\"transaction opened here\");\n\n const timer = setTimeout(() => {\n const stack = site.stack?.split(\"\\n\").slice(1).join(\"\\n\") ?? \"\";\n console.warn(\n `[gemi] A database transaction has not settled after ${threshold}ms. It ` +\n `reserves a pooled connection until it does — check for network or ` +\n `filesystem I/O inside the callback, and move it outside the ` +\n `transaction if you find any.\\n${stack}\\n` +\n `(development only; set database.slowTransactionThreshold to change ` +\n `the threshold, or false to switch this off)`,\n );\n }, threshold);\n\n // Otherwise the warning timer is itself a reason the process stays alive,\n // which would turn a diagnostic into a hang in short-lived commands and\n // scripts.\n timer.unref?.();\n\n return () => clearTimeout(timer);\n}\n\n/**\n * Runs what a committed transaction deferred, outside the transaction it was\n * deferred by.\n *\n * `outside` is the scope that was ambient before `begin` — an `asSystem` block,\n * a named connection, or nothing at all — and re-entering it explicitly is the\n * guarantee rather than a tidy-up. The alternative is relying on where a `.then`\n * happens to have captured its context, and the failure that produces is the\n * one the whole feature is about: a listener that runs \"after commit\" while\n * still holding the closed transaction's handle joins nothing, because Bun's\n * handle stays callable and simply runs on the pool. So the scope is rebuilt\n * with `tx` and the drained list cleared, and a listener that opens its own\n * transaction gets a real one.\n *\n * Errors are caught per callback and the next one still runs, for the reason\n * the event subsystem catches per listener: these are independent side effects\n * whose order came from a filesystem walk. And the transaction is not failed by\n * one — it committed, the database kept the rows, and reporting a rejection to\n * the caller would have it roll back or retry work that is already durable.\n * stderr is all that is left, and it is enough: the caller has no decision to\n * make here.\n *\n * The transaction's own promise does not resolve until this has finished, which\n * is the one thing about `afterCommit` that a caller can feel. Deliberate: the\n * alternative is a floating promise whose rejection nobody sees and whose work\n * a short-lived process — a command, a seed — exits out from under.\n */\nasync function drainAfterCommit(\n callbacks: AfterCommitCallback[],\n outside: OrmScope | undefined,\n): Promise<void> {\n if (callbacks.length === 0) return;\n\n await ormContext.run(\n {\n ...outside,\n tx: undefined,\n afterCommit: undefined,\n commitDependsOn: undefined,\n depth: outside?.depth ?? 0,\n },\n async () => {\n for (const callback of callbacks) {\n try {\n await callback();\n } catch (error) {\n console.error(\n `An after-commit callback threw. The transaction it was waiting ` +\n `on had already committed and stays committed, and the ` +\n `callbacks after it still ran.`,\n error,\n );\n }\n }\n },\n );\n}\n\n/**\n * Run `fn` inside a transaction, entering the ambient scope for its whole async\n * subtree.\n *\n * The single implementation behind both `Model.transaction` and\n * `DB.transaction`, so the two cannot become transaction systems that ignore\n * each other: a `Model.create` inside a `DB.transaction` joins it, and a raw\n * `DB.sql` inside a `Model.transaction` can join it through\n * `currentTransaction()`.\n *\n * Nesting becomes a savepoint. Not a preference — Bun refuses the alternative\n * outright (`cannot call begin inside a transaction use savepoint() instead`),\n * and a savepoint is the semantics worth having anyway: an inner failure rolls\n * back to it and leaves the outer transaction usable, which a caller that\n * catches can rely on. Verified on SQLite and Postgres.\n *\n * Note Bun hands the savepoint callback the *same* handle object as the outer\n * transaction (`sp === tx`), so the depth counter is the only thing that\n * actually changes on the way in. The callback's argument is still what gets\n * stored, so this keeps working if that ever stops being true. The cast is\n * because Bun types a savepoint handle as plain `SQL` — without `savepoint` on\n * it — while the runtime object does carry the method, which is what makes\n * three levels of nesting work.\n *\n * Anything `deferUntilCommit` queued is drained once `begin` resolves, outside\n * the transaction and only on the outermost call — a savepoint has committed\n * nothing durable, so draining there would run work that a later rollback of\n * the enclosing transaction was meant to have prevented. See `drainAfterCommit`\n * for what that costs the caller.\n *\n * In development, an outermost transaction that stays open past\n * `options.slowTransactionThreshold` (2s by default, `false` to disable) warns\n * — see `watchForSlowTransaction`. Nothing here *prevents* a long transaction;\n * the warning exists because the cost of one is paid by unrelated queries\n * elsewhere in the process, which makes it hard to trace back.\n *\n * The threshold is passed in rather than read from `app(DatabaseManager)` here.\n * Every caller already holds the manager — it is where `pool` came from — and\n * taking it as an argument keeps this file free of the container, so a bare\n * `SQL` is still enough to call it. Its tests rely on that.\n *\n * `options.connection` is the name `pool` belongs to, and follows the same rule\n * for the same reason: the pool cannot be asked what it is called. Passing it\n * is what lets a nested `withTransaction` tell \"the same connection, so take a\n * savepoint\" from \"a different one, so refuse\" — omitting it means the default\n * connection, which is what a two-argument call always meant.\n *\n * The return type is asserted rather than inferred for one reason worth\n * knowing: Bun's `begin` unwraps a callback that resolves to an *array of\n * promises*, awaiting each. So `Model.transaction(async () => [a, b])` where\n * `a` and `b` are promises resolves to their values, not to the promises. That\n * is Bun's behaviour and is left alone; it is only surprising if unmentioned.\n */\nexport function withTransaction<T>(\n pool: SQL,\n fn: (tx: TransactionSQL) => Promise<T>,\n options?: {\n slowTransactionThreshold?: number | false;\n connection?: string;\n /**\n * Leave the scope's `settings` (#1158) to `fn`, which applies them with\n * `applyTransactionSettings()` after statements that have to come first\n * (`SET TRANSACTION READ ONLY`).\n */\n deferSettings?: boolean;\n /**\n * The connection's dialect. On `\"sqlite\"` an outermost transaction\n * queues behind the one already open on the same pool (#1362); see\n * `queuedOnSqlite`.\n */\n dialect?: string;\n },\n): Promise<T> {\n const current = liveScope();\n\n // THE SINGLE-CONNECTION ASSUMPTION, WHICH IS NOW CHECKED RATHER THAN PINNED.\n //\n // The savepoint branch below ignores `pool` entirely. That was correct while\n // there was one `DatabaseManager` and one `SQL` — the ambient handle and\n // whatever pool the caller passed were necessarily the same database — and\n // the note that stood here said what would happen when a second connection\n // became configurable (#327): a `DB.transaction` on B inside a\n // `Model.transaction` on A would savepoint on **A** and hand the callback A's\n // handle, so statements landed in the wrong database with no error at all.\n //\n // So the name is compared before the branch is taken, and a mismatch raises.\n // Refusing is the whole answer rather than half of one — there is no way to\n // make one transaction span two pools, and the alternatives are covered on\n // `CrossConnectionTransactionError`.\n //\n // A caller that passes no `connection` is treated as naming the default,\n // which is what `withTransaction(pool, fn)` meant before this argument\n // existed.\n const name = options?.connection ?? DEFAULT_CONNECTION;\n assertConnectionUsable(name);\n\n // `current?.tx` rather than `current`: since iteration 6 a scope can exist\n // with no open transaction — `Model.asSystem` enters one — and a savepoint\n // needs an actual handle, not merely a store.\n if (current?.tx) {\n // WHERE THE SHARED AFTER-COMMIT LIST IS PUT RIGHT.\n //\n // The savepoint's scope is a spread of this one, so it appends to the\n // transaction's list rather than to a list of its own — which is what makes\n // \"the outer transaction rolled back, so nothing runs\" free. The case that\n // is not free is this one: the savepoint rolls back and the transaction\n // goes on to commit. Its entries have to go, or a dispatch made inside a\n // block the database threw away runs anyway, which is the same wrong answer\n // as before with an extra step.\n //\n // A mark on the way in and a truncate on the way out, rather than tagging\n // each entry with its depth and dropping everything at or below the failing\n // one. Depth cannot tell two *siblings* apart: a savepoint that committed\n // and one that rolled back both left entries at the same depth, adjacent in\n // the list, and dropping by depth would discard the committed sibling's\n // work as well. The index is exact because the ORM issues one statement at\n // a time on a transaction handle — see `OrmScope.tx` — so nothing appends\n // between the mark and the failure but this savepoint's own subtree.\n const deferred = current.afterCommit;\n const mark = deferred?.length ?? 0;\n // The same mark for the writes the commit depends on. The savepoint waits\n // for its own before it releases, so one that failed rolls back only the\n // savepoint — which a caller that catches can survive, exactly as it\n // survives a statement that threw inside it — and is then forgotten\n // rather than failing the transaction a second time.\n const dependencies = current.commitDependsOn;\n const dependencyMark = dependencies?.length ?? 0;\n\n return current.tx\n .savepoint((sp) => {\n const nested = sp as TransactionSQL;\n return ormContext.run(\n { ...current, tx: nested, depth: current.depth + 1 },\n async () => {\n const result = await fn(nested);\n if (dependencies) {\n await awaitDependencies(dependencies, dependencyMark);\n }\n return result;\n },\n );\n })\n .catch((error: unknown) => {\n if (deferred) deferred.length = mark;\n if (dependencies) dependencies.length = dependencyMark;\n throw error;\n }) as Promise<T>;\n }\n\n if (options?.dialect === \"sqlite\") {\n return queuedOnSqlite(pool, (release) => openTransaction(pool, fn, options, current, name, release), options);\n }\n return openTransaction(pool, fn, options, current, name);\n}\n\n/**\n * The transactions waiting on each SQLite pool, as the promise the last one\n * queued settles (#1362). Bun's SQLite client runs every statement on one\n * connection, where a second `BEGIN` while a transaction is open fails with\n * \"cannot start a transaction within a transaction\". SQLite allows one writer\n * at a time anyway, so queueing changes the order, not the throughput.\n */\nconst sqliteQueues = new WeakMap<SQL, Promise<void>>();\n\n/**\n * A transaction on a SQLite pool waited, in the queue, for one it is itself\n * inside (#1362). It would wait forever: the open transaction can't commit\n * until this one, which it is waiting on, has run.\n *\n * Thrown, rather than hung, when a transaction that isn't nested through the\n * ORM's scope starts from inside an open one on the same connection, and is\n * still waiting on it 5 seconds later: a raw\n * `sql.begin` (a store's), or code that deliberately left the transaction's\n * ORM scope while still awaited by it (an in-process API call or channel\n * message, `ormContext.exit`). Run that work after the commit\n * (`afterCommit`), or inside the transaction, where it becomes a savepoint.\n */\nexport class TransactionQueueDeadlockError extends Error {\n constructor() {\n super(\n \"A SQLite transaction started from inside an open transaction on the same connection, \" +\n \"outside its scope (a raw `begin`, or an in-process call that left the transaction's scope \" +\n \"while the transaction waits on it). SQLite runs one transaction per connection, so it \" +\n \"would wait for the transaction that waits on it. Run it after the commit (`afterCommit`), \" +\n \"or inside the transaction.\",\n );\n this.name = \"TransactionQueueDeadlockError\";\n }\n}\n\n/** The transaction each SQLite pool's queue is running now: its token. */\nconst queueHolders = new WeakMap<SQL, object>();\n\n/**\n * The queued transactions the current async context is inside of. An ORM\n * scope exit (`ormContext.exit`) doesn't leave this one, which is the point:\n * code that left the ORM scope on purpose is still awaited by the\n * transaction around it.\n */\nconst insideQueued = new AsyncLocalStorage<ReadonlySet<object>>();\n\n/** How long a transaction waits in the queue before development warns. */\nconst QUEUE_WAIT_WARNING_MS = 5_000;\n\n/**\n * `begin` once the transactions queued on `pool` before it have let it go\n * (#1362). Exported for the stores that open their own transactions on an\n * app connection, so every transaction on the pool takes the same turns.\n *\n * `release` lets the next one go. The ORM calls it first thing after COMMIT,\n * before the after-commit callbacks: `begin` resolves only after those have\n * run, and one that opened a transaction would otherwise wait on the very\n * transaction that waits on it. Settling lets it go too, so a caller that\n * ignores `release` (a raw `sql.begin`, whose commit is its settle) holds the\n * queue until its promise settles, including any work it does after its own\n * commit. `begin` must not queue on the same pool again from inside (it\n * would wait for itself; see below).\n *\n * Savepoints never come here: they run inside the open transaction.\n *\n * A transaction queued from inside the one holding the pool (its async\n * context says so) is only a suspected deadlock: async context is inherited\n * by work the transaction never waits for too (a `setTimeout`, an un-awaited\n * call), which just waits its turn. So it queues like any other, and is\n * rejected with `TransactionQueueDeadlockError` only if, after 5 seconds, it\n * is still waiting on a transaction it is inside. In development any\n * transaction still waiting then warns (`slowTransactionThreshold: false`\n * turns the warning off).\n */\nexport function queuedOnSqlite<T>(\n pool: SQL,\n begin: (release: () => void) => Promise<T>,\n options: { slowTransactionThreshold?: number | false } = {},\n): Promise<T> {\n const inside = insideQueued.getStore();\n const token = {};\n let release!: () => void;\n const released = new Promise<void>((resolve) => {\n release = () => {\n if (queueHolders.get(pool) === token) queueHolders.delete(pool);\n resolve();\n };\n });\n const previous = sqliteQueues.get(pool) ?? Promise.resolve();\n sqliteQueues.set(pool, released);\n\n return new Promise<T>((resolve, reject) => {\n let abandoned = false;\n // Only where it can be shown: a stack per transaction is not free.\n const site =\n slowTransactionThreshold(options.slowTransactionThreshold) === null\n ? undefined\n : new Error(\"transaction queued here\");\n const timer = setTimeout(() => {\n // Still waiting. On a transaction it is inside: it can never get its\n // turn, so it fails, and lets the queue go when its turn would come.\n const holder = queueHolders.get(pool);\n if (holder && inside?.has(holder)) {\n abandoned = true;\n reject(new TransactionQueueDeadlockError());\n return;\n }\n if (site) warnQueueWait(site);\n }, QUEUE_WAIT_WARNING_MS);\n timer.unref?.();\n\n void previous.then(() => {\n clearTimeout(timer);\n if (abandoned) {\n release();\n return;\n }\n queueHolders.set(pool, token);\n const result = insideQueued.run(new Set([...(inside ?? []), token]), () => begin(release));\n result.then(release, release);\n result.then(resolve, reject);\n });\n });\n}\n\n/** Development's warning for a transaction still waiting in the queue. */\nfunction warnQueueWait(site: Error): void {\n const stack = site.stack?.split(\"\\n\").slice(1).join(\"\\n\") ?? \"\";\n console.warn(\n `[gemi] A SQLite transaction has waited ${QUEUE_WAIT_WARNING_MS}ms for the one open on its ` +\n `connection (SQLite runs one at a time per connection). Look for a long transaction, or ` +\n `one that waits on work started outside it.\\n${stack}\\n` +\n `(development only; database.slowTransactionThreshold: false switches it off)`,\n );\n}\n\n/** The outermost half of `withTransaction`: `BEGIN` on `pool`, `fn`, `COMMIT`, then the after-commit list. */\nfunction openTransaction<T>(\n pool: SQL,\n fn: (tx: TransactionSQL) => Promise<T>,\n options: { slowTransactionThreshold?: number | false; deferSettings?: boolean } | undefined,\n current: OrmScope | undefined,\n name: string,\n release?: () => void,\n): Promise<T> {\n // Only the outermost scope is watched. A savepoint reserves no connection of\n // its own — its lifetime is bounded by the transaction it sits in, which is\n // already being timed — so warning per depth would report one slow block as\n // several warnings and point at the innermost frame rather than the one\n // holding the connection.\n const stopWatching = watchForSlowTransaction(\n options?.slowTransactionThreshold,\n );\n\n // Built out here rather than inside the `begin` callback, because the drain\n // below needs it *after* that callback's scope is gone, and reading it off\n // the store then is exactly what is no longer possible.\n // A queued SQLite transaction lets the next one go first thing after its\n // commit, before the app's callbacks (`queuedOnSqlite`).\n const deferred: AfterCommitCallback[] = release ? [release] : [];\n const dependencies: Promise<unknown>[] = [];\n const applied = new Map<string, string>();\n const statementFailed = { value: false };\n\n // The `try` covers a *synchronous* throw from `begin` — a closed pool, say.\n // `.finally` alone would not: it is only attached once `begin` has returned a\n // promise, so a synchronous throw escapes with the timer still armed and\n // eventually warns about a transaction that never opened. `unref` keeps that\n // from holding the process, which makes it cosmetic rather than a leak, but\n // it is the same gap the `.finally` below exists to close.\n try {\n // Spread rather than replace: a `Model.transaction` inside a\n // `Model.asSystem` must not silently re-enable policies for its subtree.\n //\n // The connection goes into the scope alongside the handle, and the pair is\n // what makes the check at the top of this function possible: \"which\n // connection is this transaction on\" has to be answerable from the store,\n // because the handle itself does not say. It is also what makes an\n // unqualified query inside `DB.connection(\"analytics\").transaction(...)`\n // *join* the transaction instead of being refused by it — the query\n // inherits the name rather than defaulting to the hot path.\n return (\n pool\n .begin((tx) =>\n ormContext.run(\n {\n ...current,\n tx,\n depth: 0,\n connection: name === DEFAULT_CONNECTION ? undefined : name,\n // A fresh list per outermost transaction, assigned rather than\n // left to the spread. `current` holds no list today — the drain\n // clears the field before it runs anything — and assigning is\n // what keeps that from being load-bearing: a transaction opened\n // by a callback during a drain gets its own list either way,\n // rather than appending to the array it is being run out of.\n afterCommit: deferred,\n commitDependsOn: dependencies,\n appliedSettings: applied,\n statementFailed,\n },\n async () => {\n if (!options?.deferSettings) {\n await applySettings(tx, current?.settings, applied);\n }\n try {\n const result = await fn(tx);\n await awaitDependencies(dependencies, 0);\n // Throws \"current transaction is aborted\" when a failed statement\n // was swallowed on Postgres, so `begin` rolls back and rejects\n // instead of resolving over a `COMMIT` that rolled back.\n if (statementFailed.value) await tx.unsafe(\"select 1\");\n return result;\n } finally {\n // Done with it, before Bun sends COMMIT or ROLLBACK: work\n // that runs from now on is outside it (#1376).\n finishedLists.add(deferred);\n }\n },\n ),\n )\n // `finally` and not a `then`/`catch` pair: the connection is released on\n // rollback exactly as it is on commit, so a throwing callback must clear\n // the timer too or every failed transaction leaves a warning armed\n // against a connection that has already gone back to the pool.\n //\n // Before the drain, so that a slow after-commit listener is not\n // reported as a transaction that will not settle. The connection went\n // back to the pool at the commit; the warning is about holding it.\n .finally(stopWatching)\n // Only here, on the fulfilled path. A rejected `begin` rolled back, so\n // the scope and everything queued on it are discarded unread — which is\n // the whole of what `afterCommit` promises.\n .then(\n async (result) => {\n settledLists.set(deferred, \"committed\");\n await drainAfterCommit(deferred, current);\n return result;\n },\n (error: unknown) => {\n settledLists.set(deferred, \"rolled_back\");\n throw error;\n },\n ) as Promise<T>\n );\n } catch (error) {\n stopWatching();\n throw error;\n }\n}\n\n// --- session settings (#1158) ---------------------------------------------\n\n/** A custom Postgres setting's name: at least two dot-separated parts. */\nconst SETTING_NAME = /^[A-Za-z_][A-Za-z0-9_$]*(\\.[A-Za-z_][A-Za-z0-9_$]*)+$/;\n\n/** The value a setting can be given. `null` sets it to the empty string. */\nexport type SessionSettingValue = string | number | boolean | bigint | null;\n\n/**\n * A `withSettings` block tried to give a setting another value than the\n * block around it gave it (#1158). Refused rather than applied, because a\n * nested change would outlive the inner block: `SET LOCAL` survives\n * `RELEASE SAVEPOINT`, so the rest of the outer block would run as the inner\n * tenant.\n */\nexport class SessionSettingConflictError extends Error {\n constructor(\n readonly setting: string,\n readonly outer: string,\n readonly inner: string,\n ) {\n super(\n `DB.withSettings: \"${setting}\" is already \"${outer}\" in an enclosing withSettings block, and a nested block can't change it to \"${inner}\". Open a separate block outside the first one.`,\n );\n this.name = \"SessionSettingConflictError\";\n }\n}\n\n/** The settings of the ambient scope, or `undefined` when there are none. */\nexport function currentSettings(): Readonly<Record<string, string>> | undefined {\n const settings = liveScope()?.settings;\n return settings && Object.keys(settings).length > 0 ? settings : undefined;\n}\n\n/**\n * `set_config(name, value, true)` on `tx` for every setting not applied yet,\n * in one statement.\n */\nasync function applySettings(\n tx: TransactionSQL,\n settings: Readonly<Record<string, string>> | undefined,\n applied: Map<string, string>,\n): Promise<string[]> {\n if (!settings) return [];\n const pending = Object.entries(settings).filter(([name, value]) => applied.get(name) !== value);\n if (pending.length === 0) return [];\n const calls = pending.map((_, at) => `set_config($${at * 2 + 1}, $${at * 2 + 2}, true)`);\n await tx.unsafe(\n `select ${calls.join(\", \")}`,\n pending.flatMap(([name, value]) => [name, value]),\n );\n for (const [name, value] of pending) applied.set(name, value);\n return pending.map(([name]) => name);\n}\n\n/**\n * Apply the ambient scope's settings on the open transaction, for a caller\n * that opened it with `deferSettings` (`DB.readOnly`). @internal\n */\nexport async function applyTransactionSettings(): Promise<void> {\n const store = liveScope();\n if (store?.tx && store.appliedSettings) {\n await applySettings(store.tx, store.settings, store.appliedSettings);\n }\n}\n\n/**\n * Runs `fn` with Postgres session settings (#1158): every transaction opened\n * inside starts with `set_config(name, value, true)` for each, and so does the\n * implicit transaction a single ORM call or `DB.query` outside a transaction\n * is given. Inside an open transaction they are applied at once, and the ones\n * this block added are reset to `''` when it returns.\n *\n * Blocks nest: an inner block adds settings, and giving one the outer block\n * set another value throws `SessionSettingConflictError`.\n */\nexport async function runWithSettings<T>(\n settings: Record<string, SessionSettingValue>,\n fn: () => Promise<T>,\n): Promise<T> {\n const current = liveScope();\n const outer = current?.settings ?? {};\n const merged: Record<string, string> = { ...outer };\n for (const [name, raw] of Object.entries(settings)) {\n if (!SETTING_NAME.test(name)) {\n throw new Error(\n `DB.withSettings: \"${name}\" is not a custom setting name. Use a prefix and a dot, like \"app.tenant_id\".`,\n );\n }\n const value = raw === null ? \"\" : String(raw);\n if (Object.hasOwn(outer, name) && outer[name] !== value) {\n throw new SessionSettingConflictError(name, outer[name]!, value);\n }\n merged[name] = value;\n }\n const scope: OrmScope = { ...current, depth: current?.depth ?? 0, settings: merged };\n\n const tx = current?.tx;\n const applied = current?.appliedSettings;\n if (!tx || !applied) return ormContext.run(scope, fn);\n\n return ormContext.run(scope, async () => {\n const added = await applySettings(tx, merged, applied);\n const reset = async () => {\n if (added.length === 0) return;\n const calls = added.map((_, at) => `set_config($${at + 1}, '', true)`);\n await tx.unsafe(`select ${calls.join(\", \")}`, added);\n for (const name of added) applied.delete(name);\n };\n let result: T;\n try {\n result = await fn();\n } catch (error) {\n // The transaction may already be failing (an aborted transaction\n // refuses every statement): the rollback resets them anyway, and the\n // caller sees the original error.\n await reset().catch(() => {});\n throw error;\n }\n await reset();\n return result;\n });\n}\n"
6
- ],
7
- "mappings": ";yDACA,4BAAS,oBAgLF,IAAM,EAAa,IAAI,EAoB9B,SAAS,CAAS,EAAyB,CACzC,IAAM,EAAQ,EAAW,SAAS,EAClC,GAAI,GAAO,KAAO,QAAa,EAAM,cAAgB,OAAW,OAAO,EACvE,GAAI,CAAC,EAAc,IAAI,EAAM,WAAW,EAAG,OAAO,EAClD,MAAO,IACF,EACH,GAAI,OACJ,MAAO,EACP,YAAa,OACb,gBAAiB,OACjB,gBAAiB,OACjB,gBAAiB,MACnB,EAcK,SAAS,CAAkB,EAA+B,CAC/D,OAAO,EAAU,GAAG,GAUf,SAAS,CAAqB,EAAW,CAC9C,OAAO,EAAU,GAAG,YAAc,EAgB7B,SAAS,CAAkB,CAChC,EACA,EACY,CACZ,IAAM,EAAU,EAAU,EAC1B,GAAI,EAAsB,IAAM,EAAM,OAAO,EAAG,EAehD,OAFA,EAAuB,CAAI,EAEpB,EAAW,IAChB,IACK,EACH,MAAO,GAAS,OAAS,EACzB,WAAY,IAAS,EAAqB,OAAY,CACxD,EACA,CACF,EAiBK,SAAS,CAAsB,CAAC,EAAoB,CACzD,IAAM,EAAQ,EAAU,EACxB,GAAI,GAAO,KAAO,OAAW,OAE7B,IAAM,EAAO,EAAM,YAAc,EACjC,GAAI,IAAS,EAAM,OAEnB,MAAM,IAAI,EAAgC,EAAM,CAAI,EAsB/C,SAAS,CAAgB,CAAC,EAAwC,CAEvE,IAAM,EAAQ,EAAW,SAAS,EAClC,GAAI,GAAO,KAAO,QAAa,EAAM,cAAgB,OAAW,MAAO,GAYvE,IAAM,EAAU,EAAa,IAAI,EAAM,WAAW,EAClD,GA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