gemi 0.80.0 → 0.81.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 (192) hide show
  1. package/dist/ai/Agent.d.ts +83 -2
  2. package/dist/ai/Agent.d.ts.map +1 -1
  3. package/dist/ai/AgentProvider.d.ts +10 -1
  4. package/dist/ai/AgentProvider.d.ts.map +1 -1
  5. package/dist/ai/index.d.ts +2 -2
  6. package/dist/ai/index.d.ts.map +1 -1
  7. package/dist/ai/index.js +9 -9
  8. package/dist/ai/index.js.map +7 -7
  9. package/dist/ai/providers/call.d.ts.map +1 -1
  10. package/dist/ai/providers/errors.d.ts +12 -0
  11. package/dist/ai/providers/errors.d.ts.map +1 -1
  12. package/dist/ai/store/stubAgentRun.d.ts +2 -2
  13. package/dist/ai/store/stubAgentRun.d.ts.map +1 -1
  14. package/dist/app/index.js +1 -1
  15. package/dist/broadcasting/index.js +1 -1
  16. package/dist/bun/plugin.js +1 -1
  17. package/dist/bun/preload.js +1 -1
  18. package/dist/{chunk-axxbkm30.js → chunk-03xrgp1m.js} +2 -2
  19. package/dist/{chunk-axxbkm30.js.map → chunk-03xrgp1m.js.map} +1 -1
  20. package/dist/{chunk-jcq0tbdv.js → chunk-06p4zq4m.js} +2 -2
  21. package/dist/{chunk-jcq0tbdv.js.map → chunk-06p4zq4m.js.map} +1 -1
  22. package/dist/{chunk-0472aphj.js → chunk-0zr926cf.js} +2 -2
  23. package/dist/{chunk-0472aphj.js.map → chunk-0zr926cf.js.map} +1 -1
  24. package/dist/{chunk-q0nqypca.js → chunk-1dgab0qn.js} +2 -2
  25. package/dist/{chunk-q0nqypca.js.map → chunk-1dgab0qn.js.map} +1 -1
  26. package/dist/{chunk-yernnzqs.js → chunk-1k783c44.js} +2 -2
  27. package/dist/{chunk-yernnzqs.js.map → chunk-1k783c44.js.map} +1 -1
  28. package/dist/{chunk-yedycsnk.js → chunk-2c89p8pf.js} +2 -2
  29. package/dist/{chunk-yedycsnk.js.map → chunk-2c89p8pf.js.map} +1 -1
  30. package/dist/{chunk-ss7ymqfm.js → chunk-2frgq249.js} +2 -2
  31. package/dist/{chunk-ss7ymqfm.js.map → chunk-2frgq249.js.map} +1 -1
  32. package/dist/{chunk-0pqsp84p.js → chunk-2gprnzc3.js} +2 -2
  33. package/dist/{chunk-0pqsp84p.js.map → chunk-2gprnzc3.js.map} +1 -1
  34. package/dist/{chunk-34s3tfgk.js → chunk-2y9haf48.js} +3 -3
  35. package/dist/{chunk-34s3tfgk.js.map → chunk-2y9haf48.js.map} +1 -1
  36. package/dist/{chunk-qjgfrsw7.js → chunk-3h1pd6ec.js} +2 -2
  37. package/dist/{chunk-qjgfrsw7.js.map → chunk-3h1pd6ec.js.map} +1 -1
  38. package/dist/{chunk-qgvg10ad.js → chunk-5krm6p9w.js} +3 -3
  39. package/dist/{chunk-qgvg10ad.js.map → chunk-5krm6p9w.js.map} +1 -1
  40. package/dist/{chunk-fmhkn266.js → chunk-6c0s1mb7.js} +2 -2
  41. package/dist/{chunk-fmhkn266.js.map → chunk-6c0s1mb7.js.map} +1 -1
  42. package/dist/{chunk-zzh52t0y.js → chunk-6eprvf4s.js} +2 -2
  43. package/dist/{chunk-zzh52t0y.js.map → chunk-6eprvf4s.js.map} +1 -1
  44. package/dist/{chunk-27pnn95c.js → chunk-6sd7an1r.js} +2 -2
  45. package/dist/{chunk-27pnn95c.js.map → chunk-6sd7an1r.js.map} +1 -1
  46. package/dist/{chunk-n03frt02.js → chunk-7dk4b1fn.js} +2 -2
  47. package/dist/{chunk-n03frt02.js.map → chunk-7dk4b1fn.js.map} +1 -1
  48. package/dist/{chunk-443yr2km.js → chunk-7y6gpg08.js} +3 -3
  49. package/dist/{chunk-443yr2km.js.map → chunk-7y6gpg08.js.map} +1 -1
  50. package/dist/chunk-817dxq6w.js +7 -0
  51. package/dist/{chunk-4h7z32zp.js.map → chunk-817dxq6w.js.map} +10 -7
  52. package/dist/{chunk-yaz93haz.js → chunk-8vnb3hfz.js} +2 -2
  53. package/dist/{chunk-yaz93haz.js.map → chunk-8vnb3hfz.js.map} +1 -1
  54. package/dist/{chunk-sqvw7rv2.js → chunk-9146818v.js} +3 -3
  55. package/dist/{chunk-sqvw7rv2.js.map → chunk-9146818v.js.map} +1 -1
  56. package/dist/{chunk-eekg7k6d.js → chunk-9z5g1rf6.js} +1 -1
  57. package/dist/{chunk-1ap69pez.js → chunk-a3mgkrb2.js} +1 -1
  58. package/dist/{chunk-tpdsfr2k.js → chunk-actjm3wr.js} +2 -2
  59. package/dist/{chunk-tpdsfr2k.js.map → chunk-actjm3wr.js.map} +1 -1
  60. package/dist/{chunk-tnt0ybj9.js → chunk-aecx542w.js} +2 -2
  61. package/dist/{chunk-tnt0ybj9.js.map → chunk-aecx542w.js.map} +1 -1
  62. package/dist/{chunk-s7hv9qgp.js → chunk-bwwjkdts.js} +2 -2
  63. package/dist/{chunk-s7hv9qgp.js.map → chunk-bwwjkdts.js.map} +1 -1
  64. package/dist/{chunk-dmdmt3gw.js → chunk-d07y2ddw.js} +2 -2
  65. package/dist/{chunk-dmdmt3gw.js.map → chunk-d07y2ddw.js.map} +1 -1
  66. package/dist/{chunk-7yhsy039.js → chunk-d2esms7y.js} +2 -2
  67. package/dist/{chunk-7yhsy039.js.map → chunk-d2esms7y.js.map} +1 -1
  68. package/dist/{chunk-sbqy6r29.js → chunk-d2tpgkg2.js} +1 -1
  69. package/dist/{chunk-6h5gvcs8.js → chunk-dk0kdrkm.js} +2 -2
  70. package/dist/{chunk-6h5gvcs8.js.map → chunk-dk0kdrkm.js.map} +1 -1
  71. package/dist/{chunk-0vkd0v3b.js → chunk-edhafzvs.js} +2 -2
  72. package/dist/{chunk-0vkd0v3b.js.map → chunk-edhafzvs.js.map} +1 -1
  73. package/dist/{chunk-3hfwbp2m.js → chunk-egw90hq5.js} +2 -2
  74. package/dist/{chunk-3hfwbp2m.js.map → chunk-egw90hq5.js.map} +1 -1
  75. package/dist/{chunk-sp4wwg7s.js → chunk-f46ntdj3.js} +3 -3
  76. package/dist/{chunk-sp4wwg7s.js.map → chunk-f46ntdj3.js.map} +1 -1
  77. package/dist/{chunk-rv9k5bqn.js → chunk-f9mwxne0.js} +2 -2
  78. package/dist/{chunk-rv9k5bqn.js.map → chunk-f9mwxne0.js.map} +1 -1
  79. package/dist/{chunk-0da5t7vs.js → chunk-fffph77x.js} +2 -2
  80. package/dist/{chunk-0da5t7vs.js.map → chunk-fffph77x.js.map} +1 -1
  81. package/dist/{chunk-e97kq9tn.js → chunk-fpy7m803.js} +2 -2
  82. package/dist/{chunk-e97kq9tn.js.map → chunk-fpy7m803.js.map} +1 -1
  83. package/dist/{chunk-mmhf39tr.js → chunk-fya5147b.js} +2 -2
  84. package/dist/{chunk-mmhf39tr.js.map → chunk-fya5147b.js.map} +1 -1
  85. package/dist/{chunk-ezae18wm.js → chunk-gppm9gkg.js} +2 -2
  86. package/dist/{chunk-ezae18wm.js.map → chunk-gppm9gkg.js.map} +1 -1
  87. package/dist/{chunk-rkx6qhwg.js → chunk-gzx3rskd.js} +4 -4
  88. package/dist/{chunk-rkx6qhwg.js.map → chunk-gzx3rskd.js.map} +1 -1
  89. package/dist/{chunk-b941c34r.js → chunk-hfxx52vr.js} +2 -2
  90. package/dist/{chunk-b941c34r.js.map → chunk-hfxx52vr.js.map} +1 -1
  91. package/dist/{chunk-j1w19cec.js → chunk-mc1xsz8j.js} +3 -3
  92. package/dist/{chunk-j1w19cec.js.map → chunk-mc1xsz8j.js.map} +1 -1
  93. package/dist/{chunk-q623tx9p.js → chunk-mmq47yh3.js} +2 -2
  94. package/dist/{chunk-q623tx9p.js.map → chunk-mmq47yh3.js.map} +1 -1
  95. package/dist/{chunk-989rzqd6.js → chunk-mwrh96hx.js} +3 -3
  96. package/dist/{chunk-989rzqd6.js.map → chunk-mwrh96hx.js.map} +1 -1
  97. package/dist/chunk-nc82trtm.js +5 -0
  98. package/dist/{chunk-cr9f0s09.js.map → chunk-nc82trtm.js.map} +1 -1
  99. package/dist/{chunk-sww4kgk4.js → chunk-nq2hm5xm.js} +2 -2
  100. package/dist/{chunk-sww4kgk4.js.map → chunk-nq2hm5xm.js.map} +1 -1
  101. package/dist/{chunk-dgqqv3pb.js → chunk-q7ngq6c5.js} +2 -2
  102. package/dist/{chunk-dgqqv3pb.js.map → chunk-q7ngq6c5.js.map} +1 -1
  103. package/dist/chunk-rs0xmd64.js +17 -0
  104. package/dist/{chunk-azebyh90.js.map → chunk-rs0xmd64.js.map} +3 -5
  105. package/dist/{chunk-1qwkhbc4.js → chunk-s7rhttvd.js} +2 -2
  106. package/dist/{chunk-1qwkhbc4.js.map → chunk-s7rhttvd.js.map} +1 -1
  107. package/dist/{chunk-njh95es7.js → chunk-sexaj89x.js} +2 -2
  108. package/dist/{chunk-njh95es7.js.map → chunk-sexaj89x.js.map} +1 -1
  109. package/dist/{chunk-j8nbjpkg.js → chunk-t2htq1v0.js} +2 -2
  110. package/dist/{chunk-j8nbjpkg.js.map → chunk-t2htq1v0.js.map} +1 -1
  111. package/dist/{chunk-fms4fcd1.js → chunk-t6yzarvt.js} +2 -2
  112. package/dist/{chunk-fms4fcd1.js.map → chunk-t6yzarvt.js.map} +1 -1
  113. package/dist/{chunk-xzp2ptj5.js → chunk-v0j7spj5.js} +2 -2
  114. package/dist/{chunk-fd0n8sav.js.map → chunk-v0j7spj5.js.map} +1 -1
  115. package/dist/{chunk-hjbe3jn2.js → chunk-v6nhcpsb.js} +2 -2
  116. package/dist/{chunk-hjbe3jn2.js.map → chunk-v6nhcpsb.js.map} +1 -1
  117. package/dist/{chunk-zjg31baf.js → chunk-v8s1dmc2.js} +2 -2
  118. package/dist/{chunk-zjg31baf.js.map → chunk-v8s1dmc2.js.map} +1 -1
  119. package/dist/{chunk-gzs2y282.js → chunk-vax2fp2k.js} +2 -2
  120. package/dist/{chunk-gzs2y282.js.map → chunk-vax2fp2k.js.map} +1 -1
  121. package/dist/{chunk-zkty5j42.js → chunk-vngyybzh.js} +2 -2
  122. package/dist/{chunk-zkty5j42.js.map → chunk-vngyybzh.js.map} +1 -1
  123. package/dist/{chunk-bdfdjnht.js → chunk-vqexqkfk.js} +3 -3
  124. package/dist/{chunk-bdfdjnht.js.map → chunk-vqexqkfk.js.map} +1 -1
  125. package/dist/{chunk-fvn78g6k.js → chunk-vxxk4syx.js} +2 -2
  126. package/dist/{chunk-fvn78g6k.js.map → chunk-vxxk4syx.js.map} +1 -1
  127. package/dist/{chunk-1712rv0r.js → chunk-wmbpdjvs.js} +2 -2
  128. package/dist/{chunk-1712rv0r.js.map → chunk-wmbpdjvs.js.map} +1 -1
  129. package/dist/{chunk-5ddn8mfj.js → chunk-y7gfg6tj.js} +2 -2
  130. package/dist/{chunk-5ddn8mfj.js.map → chunk-y7gfg6tj.js.map} +1 -1
  131. package/dist/{chunk-cg469vsg.js → chunk-z9x8fx21.js} +2 -2
  132. package/dist/{chunk-cg469vsg.js.map → chunk-z9x8fx21.js.map} +1 -1
  133. package/dist/{chunk-m2bmwre5.js → chunk-zbpgt20r.js} +2 -2
  134. package/dist/{chunk-m2bmwre5.js.map → chunk-zbpgt20r.js.map} +1 -1
  135. package/dist/{chunk-jvyj4hxd.js → chunk-zdg024wf.js} +2 -2
  136. package/dist/{chunk-jvyj4hxd.js.map → chunk-zdg024wf.js.map} +1 -1
  137. package/dist/{chunk-fd0n8sav.js → chunk-zv7417j0.js} +2 -2
  138. package/dist/{chunk-xzp2ptj5.js.map → chunk-zv7417j0.js.map} +1 -1
  139. package/dist/config/index.js +1 -1
  140. package/dist/console/run.js +2 -2
  141. package/dist/console/run.js.map +1 -1
  142. package/dist/container/index.js +2 -2
  143. package/dist/container/index.js.map +1 -1
  144. package/dist/database/index.js +2 -2
  145. package/dist/database/index.js.map +1 -1
  146. package/dist/email/index.js +2 -2
  147. package/dist/email/index.js.map +1 -1
  148. package/dist/facades/Storage.d.ts +8 -2
  149. package/dist/facades/Storage.d.ts.map +1 -1
  150. package/dist/facades/index.js +2 -2
  151. package/dist/facades/index.js.map +1 -1
  152. package/dist/foundation/index.js +2 -2
  153. package/dist/foundation/index.js.map +1 -1
  154. package/dist/http/index.js +2 -2
  155. package/dist/http/index.js.map +1 -1
  156. package/dist/i18n/dictionaryRuntime.js +2 -2
  157. package/dist/i18n/dictionaryRuntime.js.map +1 -1
  158. package/dist/i18n/index.js +2 -2
  159. package/dist/i18n/index.js.map +1 -1
  160. package/dist/kernel/index.js +2 -2
  161. package/dist/kernel/index.js.map +1 -1
  162. package/dist/orm/index.js +2 -2
  163. package/dist/orm/index.js.map +1 -1
  164. package/dist/server/index.js +2 -2
  165. package/dist/server/index.js.map +1 -1
  166. package/dist/services/file-storage/drivers/AzureBlobDriver.d.ts +7 -3
  167. package/dist/services/file-storage/drivers/AzureBlobDriver.d.ts.map +1 -1
  168. package/dist/services/file-storage/drivers/FileStorageDriver.d.ts +2 -2
  169. package/dist/services/file-storage/drivers/FileStorageDriver.d.ts.map +1 -1
  170. package/dist/services/file-storage/drivers/FileSystemDriver.d.ts +2 -2
  171. package/dist/services/file-storage/drivers/FileSystemDriver.d.ts.map +1 -1
  172. package/dist/services/file-storage/drivers/S3Driver.d.ts +2 -2
  173. package/dist/services/file-storage/drivers/S3Driver.d.ts.map +1 -1
  174. package/dist/services/file-storage/drivers/abortableBody.d.ts +16 -0
  175. package/dist/services/file-storage/drivers/abortableBody.d.ts.map +1 -0
  176. package/dist/services/file-storage/drivers/types.d.ts +10 -1
  177. package/dist/services/file-storage/drivers/types.d.ts.map +1 -1
  178. package/dist/services/index.d.ts +1 -1
  179. package/dist/services/index.d.ts.map +1 -1
  180. package/dist/services/index.js +8 -8
  181. package/dist/services/index.js.map +4 -4
  182. package/dist/services/queue/work.js +2 -2
  183. package/dist/services/queue/work.js.map +1 -1
  184. package/dist/support/index.js +2 -2
  185. package/dist/support/index.js.map +1 -1
  186. package/package.json +1 -1
  187. package/dist/chunk-4h7z32zp.js +0 -5
  188. package/dist/chunk-azebyh90.js +0 -19
  189. package/dist/chunk-cr9f0s09.js +0 -5
  190. /package/dist/{chunk-eekg7k6d.js.map → chunk-9z5g1rf6.js.map} +0 -0
  191. /package/dist/{chunk-1ap69pez.js.map → chunk-a3mgkrb2.js.map} +0 -0
  192. /package/dist/{chunk-sbqy6r29.js.map → chunk-d2tpgkg2.js.map} +0 -0
@@ -0,0 +1,7 @@
1
+ // @bun
2
+ import{vf as W}from"./chunk-vax2fp2k.js";import{rg as i}from"./chunk-mwrh96hx.js";import{Eg as j}from"./chunk-8vnb3hfz.js";import{Lg as XH}from"./chunk-v0j7spj5.js";class k{static kind="controller";constructor(){}}class l extends k{}function A(H){let R=new Map;if(!H)return R;for(let K of H.split(";")){let T=K.indexOf("=");if(T===-1)continue;let J=K.slice(0,T).trim();if(!J)continue;R.set(J,K.slice(T+1).trim())}return R}function PH(H){return A(H.headers.get("cookie"))}function P(H){if(!/^\d+$/.test(H))return null;let R=Number(H);return Number.isSafeInteger(R)?R:null}function c(H){if(!H)return null;let R=H.trim();if(!/^bytes=/i.test(R))return null;let T=R.slice(6).split(",").map((Z)=>Z.trim()).filter((Z)=>Z!=="");if(T.length!==1)return null;let J=T[0],G=J.indexOf("-");if(G===-1)return null;let O=J.slice(0,G),X=J.slice(G+1);if(O===""){let Z=P(X);if(Z===null)return null;return{kind:"suffix",suffixLength:Z}}let Q=P(O);if(Q===null)return null;if(X==="")return{kind:"offset",start:Q,end:null};let Y=P(X);if(Y===null||Y<Q)return null;return{kind:"offset",start:Q,end:Y}}function b(H,R){if(!Number.isFinite(R)||R<=0)return null;let K,T;if(H.kind==="suffix"){if(H.suffixLength<=0)return null;K=Math.max(0,R-H.suffixLength),T=R-1}else{if(H.start>=R)return null;if(K=H.start,T=H.end===null?R-1:Math.min(H.end,R-1),T<K)return null}return{start:K,end:T,length:T-K+1}}function LH(H){if(H.kind==="suffix")return`bytes=-${H.suffixLength}`;return H.end===null?`bytes=${H.start}-`:`bytes=${H.start}-${H.end}`}function jH(H){if(!H)return null;let R=/^bytes\s+(\d+)-(\d+)\/(\d+)$/i.exec(H.trim());if(!R)return null;let K=P(R[1]),T=P(R[2]),J=P(R[3]);if(K===null||T===null||J===null||T<K)return null;return{start:K,end:T,total:J}}function MH(H,R,K){return`bytes ${H}-${R}/${K}`}function f(H){return`bytes */${H}`}var xH="GEMI_REQUEST_BREAKER_ERROR";class $ extends Error{kind="GEMI_REQUEST_BREAKER_ERROR";payload={api:{},view:{}}}class B extends ${errors={};constructor(H){super("Validation error");this.name="ValidationError",this.errors=H,this.payload={api:{status:400,data:{error:{kind:"validation_error",messages:H}},headers:{"Content-Type":"application/json"}},view:{status:400}}}}function r(H){let[R,K]=H.match(/\d+|\D+/g)??[];if(!R||!K)return 0;let T=Number.parseInt(R);switch(K){case"B":return T;case"KB":return T*1024;case"MB":return T*1024*1024;case"GB":return T*1024*1024*1024;case"TB":return T*1024*1024*1024*1024;default:return 0}}function a(H){switch(H){case"image":return"image";case"png":return"image/png";case"jpg":return"image/jpeg";case"jpeg":return"image/jpeg";case"ttf":return"font/ttf";case"excel":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case"csv":return"text/csv";case"word":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"pdf":return"application/pdf";case"json":return"application/json";default:return H}}function g(H){if(typeof H==="string"||Array.isArray(H))return H.length;return}function F(H){return typeof H==="number"&&!Number.isNaN(H)}var e=["required","string","boolean","number","email","password","min","max","gte","lte","file","fileType","fileSize"];class D extends Error{name="InvalidValidationRuleError"}function x(H,R){let K=R===void 0||R.trim()===""?Number.NaN:Number(R);if(Number.isNaN(K))throw new D(`Validation rule "${H}:${R??""}" needs a number, e.g. "${H}:3"`);return K}function v(H){let[R,K]=H.split(":");switch(R){case"required":return(T)=>{if(T instanceof Blob)return T.size>0;if(T===null||T===void 0)return!1;if(typeof T==="string"||Array.isArray(T))return T.length>0;return!0};case"string":return(T)=>typeof T==="string";case"boolean":return(T)=>typeof T==="boolean";case"number":return(T)=>F(T);case"password":return(T)=>{return typeof T==="string"&&/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9]).{8,}$/.test(T)};case"min":{let T=x(R,K);return(J)=>{let G=g(J);return G!==void 0&&G>=T}}case"max":{let T=x(R,K);return(J)=>{let G=g(J);return G!==void 0&&G<=T}}case"gte":{let T=x(R,K);return(J)=>F(J)&&J>=T}case"lte":{let T=x(R,K);return(J)=>F(J)&&J<=T}case"email":return(T)=>{return typeof T==="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(T)};case"file":return(T)=>{return T instanceof Blob};case"fileType":{if(!K)throw new D('Validation rule "fileType" needs a type, e.g. "fileType:png" or "fileType:image"');let T=a(K);return(J)=>J instanceof Blob&&J.type.startsWith(T)}case"fileSize":{let T=r(K??"");if(T===0&&!/^0+(B|KB|MB|GB|TB)$/.test(K??""))throw new D(`Validation rule "fileSize:${K??""}" needs a whole size in B, KB, MB, GB or TB, e.g. "fileSize:5MB"`);return(J)=>J instanceof Blob&&J.size<=T}default:throw new D(`Unknown validation rule "${H}". Known rules: ${e.join(", ")}`)}}var N=new WeakMap;function VH(H,R){N.set(H,{clientAddress:R})}function h(H){return N.has(H)}function SH(H){return N.get(H)?.clientAddress}var m=new WeakMap;function _H(H,R){m.set(H,R)}function d(H){return m.get(H)??null}var V=new WeakMap;function EH(H,R){let K=V.get(H)??[];if(!K.includes(R))V.set(H,[...K,R])}function IH(H){return V.get(H)??[]}class C{data;constructor(H){this.data=H}get(H){return this.data[H]}has(H){return this.data[H]!==void 0}toJSON(){return this.data}}class HH{kind;rawRequest;headers;cookies;search;schema={};routePath;params;domain;constructor(H,R,K,T){if(!H){let Q=W.getStore().req;this.params=Q.params,this.rawRequest=Q.rawRequest,this.kind=Q.kind,this.routePath=Q.routePath,this.domain=Q.domain??null}else this.params=R,this.rawRequest=H,this.routePath=T,this.kind=K??"api",this.domain=d(H);this.headers=this.rawRequest.headers;let J=A(this.rawRequest.headers.get("Cookie")),G=new URL(this.rawRequest.url),O=new Map;for(let[Q,Y]of G.searchParams)if(O.has(Q)){let Z=O.get(Q);if(Array.isArray(Z))Z.push(Y),O.set(Q,Z);else O.set(Q,[Z,Y])}else O.set(Q,Y);let X=Object.fromEntries(O.entries());this.search=new C(X),this.cookies=J}locale(){return W.getStore().locale}ctx(){return W.getStore()}isModelOriginated(){return h(this.rawRequest)}range(){return c(this.rawRequest.headers.get("Range"))}refine(H){return{}}async parseBody(){let H=new C({});if(this.rawRequest.headers.get("Content-Type")==="application/json"){let R=await this.rawRequest.json();H=new C(R)}if(this.rawRequest.headers.get("Content-Type")==="application/x-www-form-urlencoded"){let R=await this.rawRequest.formData();H=new C(R)}if(this.rawRequest.headers.get("Content-Type")?.startsWith("multipart/form-data")){let R=await this.rawRequest.formData(),K=new Map;for(let[T,J]of R.entries())if(K.has(T)){let G=K.get(T);if(Array.isArray(G))G.push(J),K.set(T,G);else K.set(T,[G,J])}else K.set(T,J);H=new C(Object.fromEntries(K.entries()))}return H}validateInput(H){let R={},K=Object.entries(this.schema).map(([T,J])=>({key:T,rules:Object.entries(J).map(([G,O])=>({rule:G,message:O,check:typeof O==="function"?null:this.ruleFor(T,G)}))}));for(let{key:T,rules:J}of K){let G=H.get(T),O=J.some(({rule:Y})=>Y==="required"),X=G===void 0||G===null||G==="",Q=[];for(let{rule:Y,message:Z,check:t}of J){let M=Z,z=!1;if(typeof Z==="function")M=Z(G),z=typeof M>"u";else z=t(G);if(z)continue;if(X&&!O)continue;if(Y==="required"){Q.splice(0,Q.length,String(M));break}Q.push(String(M))}if(Q.length>0)R[T]=Q}for(let[T,J]of Object.entries(this.refine(H.toJSON())??{})){if(!R[T])R[T]=[];R[T]=[...R[T]??[],J]}if(Object.keys(R).length>0)throw new B(R);return H}ruleFor(H,R){try{return v(R)}catch(K){if(K instanceof D)throw new D(`${this.constructor.name}.schema.${H}: ${K.message}`);throw K}}async input(){return this.validateInput(await this.parseBody())}async safeInput(){let H=await this.parseBody();try{return this.validateInput(H),{isValid:!0,errors:{},input:H}}catch(R){if(!(R instanceof B))throw R;return{isValid:!1,errors:R.errors,input:H}}}}class RH extends ${error;constructor(H="Not authorized"){super(H);this.name="AuthorizationError",this.error=H,this.payload={api:{status:401,data:{error:this.error}},view:{}}}}class p extends ${static apiStatus=403;error;constructor(H="Insufficient permissions"){super(H);this.name="InsufficientPermissionsError",this.error=H,this.payload={api:{status:p.apiStatus,data:{error:this.error}},view:{status:403}}}}class S extends ${total;constructor(H){super("Range not satisfiable");this.total=H;this.name="RangeNotSatisfiableError",this.payload={api:{status:416,data:{error:{message:"Range not satisfiable"}},headers:{"Content-Range":f(H),"Accept-Ranges":"bytes","Cache-Control":"no-store"}},view:{}}}}class U extends ${fileName;constructor(H){super("File not found");this.fileName=H;this.name="FileNotFoundError",this.payload={api:{status:404,data:{error:{message:"Not found"}},headers:{"Cache-Control":"no-store"}},view:{}}}}class TH extends ${constructor(H={}){super("Authentication error");this.name="AuthenticationError";let R=H.redirectTo??"/auth/sign-in";this.payload={api:{status:401,data:{error:"Authentication error"}},viewData:{status:200,data:{},headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate"},directive:{kind:"Redirect",path:R}},view:{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:R}}}}}class L{static getFacadeAccessor(){throw Error(`Facade [${this.name}] does not implement getFacadeAccessor().`)}static getFacadeRoot(){return i(this.getFacadeAccessor())}}class w{async delete(H){throw Error(`${this.constructor.name} does not implement delete(). Override it to remove objects from this backend.`)}async read(H){let R=typeof H==="string"?{name:H}:H,K=await this.fetch({name:R.name,bucket:R.bucket});if(!K.ok)throw new U(R.name);let T=K.headers.get("Content-Type")??"application/octet-stream",J=K.headers.get("ETag")??void 0,G=K.headers.get("Last-Modified"),O=G?new Date(G):void 0;if(R.range){let Y=await K.blob();return{body:Y,start:0,end:Y.size-1,total:Y.size,partial:!1,type:T,etag:J,lastModified:O,name:R.name}}let X=Number(K.headers.get("Content-Length")),Q=Number.isFinite(X)?X:0;return{body:K.body,start:0,end:Q-1,total:Q,partial:!1,type:T,etag:J,lastModified:O,name:R.name}}async size(H){let R=typeof H==="string"?H:H.name,K=typeof H==="string"?void 0:H.bucket,T=await this.fetch({name:R,bucket:K});if(!T.ok)throw new U(R);let J=Number(T.headers.get("Content-Length"));if(Number.isFinite(J))return await T.body?.cancel(),J;return(await T.blob()).size}}function u(H,R){if(!R)return H;let K=H.getReader(),T=!1,J,G=()=>{if(T=!0,J)R.removeEventListener("abort",J)};return new ReadableStream({start(O){if(J=()=>{if(T)return;G(),O.error(R.reason),K.cancel(R.reason).catch(()=>{})},R.aborted)J();else R.addEventListener("abort",J,{once:!0})},async pull(O){let X;try{X=await K.read()}catch(Q){if(T)return;G(),O.error(Q);return}if(T)return;if(X.done){G(),O.close();return}O.enqueue(X.value)},cancel(O){return G(),K.cancel(O)}},{highWaterMark:0})}import{readdir as KH,unlink as JH}from"fs/promises";import{isAbsolute as GH,relative as OH,resolve as n,sep as QH}from"path";class _ extends w{configured;constructor(H){super();this.configured=H}get folderPath(){return this.configured??`${j()}/storage`}async put(H,{signal:R}={}){R?.throwIfAborted();let K,T;if(H instanceof Blob)K=H,T=`${Bun.randomUUIDv7()}.${H.type.split("/")[1].split(";")[0]}`;else K=H.body,T=H.name;let J=K instanceof Buffer?K:K instanceof Blob||K instanceof File?Buffer.from(await K.arrayBuffer()):"",G=`${this.folderPath}/${T}`;return R?.throwIfAborted(),await Bun.write(G,J),T}async fetch(H,{signal:R}={}){R?.throwIfAborted();let K=process.env.BUCKET_NAME,T;if(typeof H==="string")T=H;else K=H.bucket??K,T=H.name;if(!T)throw Error("Object name has to be specified");let J=`${this.folderPath}/${T}`,G=Bun.file(J),O=u(Bun.file(J).stream(),R),X=new Date(G.lastModified).toUTCString();return new Response(O,{headers:{"Content-Type":G.type,"Content-Length":String(G.size),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":X}})}async read(H){let R=typeof H==="string"?{name:H}:H,{name:K,range:T=null}=R;if(!K)throw Error("Object name has to be specified");let J=Bun.file(`${this.folderPath}/${K}`);if(!await J.exists())throw new U(K);let G=J.size,O=T?b(T,G):null;if(T&&!O)throw new S(G);let X=O?.start??0,Q=O?O.end:G-1;return{body:O?J.slice(X,Q+1):J,start:X,end:Q,total:G,partial:Boolean(O),type:J.type||"application/octet-stream",lastModified:new Date(J.lastModified),name:K}}async size(H){let R=typeof H==="string"?H:H.name,K=Bun.file(`${this.folderPath}/${R}`);if(!await K.exists())throw new U(R);return K.size}async delete(H){let R=typeof H==="string"?H:H.name;if(!R)throw Error("Object name has to be specified");let K=n(this.folderPath),T=n(K,R),J=OH(K,T);if(!J||J===".."||J.startsWith(`..${QH}`)||GH(J))throw Error(`Refusing to delete "${R}": it is outside the storage folder`);try{await JH(T)}catch(G){if(G?.code==="ENOENT")return;throw G}}async list(){return await KH(this.folderPath)}}function JR(H){return H}function o(){return{driver:new _}}class E{static token="filesystem";driver;constructor(H={}){this.driver=H.driver??o().driver}}import{Buffer as YH}from"buffer";async function s(H){try{return(await import("sharp")).default}catch(R){throw Error(`${H} requires the 'sharp' package. Install it with \`bun add sharp\`.`,{cause:R})}}class ZH extends L{static getFacadeAccessor(){return E}static async put(H,R={}){return this.getFacadeRoot().driver.put(H,R)}static async metadata(H){let R=YH.from(await H.arrayBuffer()),K=await s("Storage.metadata()");try{return await K(R).metadata()}catch{return{}}}static async fetch(H,R={}){return R.signal?.throwIfAborted(),this.getFacadeRoot().driver.fetch(H,R)}static async read(H,R={}){let K=typeof H==="string"?{name:H}:{...H},T="range"in R?R.range??null:K.range!==void 0?K.range:W.getStore()?.rangeRequest??null;return this.getFacadeRoot().driver.read({...K,range:T})}static list(H){return this.getFacadeRoot().driver.list(H)}static async delete(H){return this.getFacadeRoot().driver.delete(H)}}import{mkdir as I,readdir as $H,access as DH}from"fs/promises";async function y(H){try{return await DH(H),!0}catch{return!1}}class q{config;static token="log";writer;isReady=!1;flushTimeout;fileSize=0;writerSize=0;isCreatingFile=!1;bootPromise=null;currentLogFilePath;get logsDirPath(){return`${j()}/storage/logs`}constructor(H){this.config=H}boot(){if(!this.bootPromise)this.bootPromise=this.createStorage().catch((H)=>{console.error("Log storage unavailable, file logging disabled",H)}).then(()=>{this.isReady=!0});return this.bootPromise}async createStorage(){let H=`${j()}/storage`;if(!await y(H))await I(H);if(!await y(this.logsDirPath))await I(this.logsDirPath);await this.newLogFile()}async newLogFile(){if(!await y(this.logsDirPath))await I(this.logsDirPath);if(this.isCreatingFile=!0,this.currentLogFilePath){this.writer.flush(),this.writer.end(),this.writer=null;let K=new File([await Bun.file(this.currentLogFilePath).arrayBuffer()],this.currentLogFilePath.split("/").pop(),{type:"text/plain"});this.config.onLogFileClosed(K),this.fileSize=0,this.writerSize=0}let R=(await $H(this.logsDirPath)).sort().reverse()[0];if(R){let K=Bun.file(`${this.logsDirPath}/${R}`);if(K.size<this.config.maxFileSize)this.currentLogFilePath=`${this.logsDirPath}/${R}`,this.writer=K.writer(),this.writer.write(await K.text()),this.writer.write(`
3
+ `),this.writer.flush(),this.fileSize=K.size}if(!this.writer){let K=`${new Date(Date.now()).toISOString()}.log`.replaceAll(":","-");this.currentLogFilePath=`${this.logsDirPath}/${K}`;let T=Bun.file(`${this.logsDirPath}/${K}`);this.writer=T.writer(),this.fileSize=0,this.writerSize=0}this.isCreatingFile=!1}async log(H,R,K={}){if(!this.isReady)await this.boot();let T=W.getStore(),J={};if(T)J={url:T.req.rawRequest.url,method:T.req.rawRequest.method,headers:T.req.rawRequest.headers,body:T.req.rawRequest.body};let G={timestamp:new Date(Date.now()).toISOString(),env:Bun.env.NODE_ENV,level:H,message:R,metadata:{...J,...K}},O="";try{O=JSON.stringify(G)}catch(X){console.log("Error parsing log object",X)}try{let X=this.config.onLogCreated(G);if(X instanceof Promise)X.catch((Q)=>console.error("Error in onLogCreated",Q))}catch(X){console.error("Error in onLogCreated",X)}if(!this.writer)return;this.writerSize+=O.length,this.fileSize+=O.length;try{this.writer.write(O),this.writer.write(`
4
+ `),this.tryFlush()}catch(X){console.error("Error writing log",X)}}async tryFlush(){if(this.fileSize>this.config.maxFileSize){if(!this.isCreatingFile)await this.newLogFile()}if(this.writerSize>this.config.maxFileSize/2)await this.writer.flush(),this.writerSize=0,await this.newLogFile();else clearTimeout(this.flushTimeout),this.flushTimeout=setTimeout(async()=>{await this.writer.flush(),this.writerSize=0},100)}}class WH extends L{static getFacadeAccessor(){return q}static debug(H,R){this.getFacadeRoot().log("debug",H,R)}static info(H,R){this.getFacadeRoot().log("info",H,R)}static notice(H,R){this.getFacadeRoot().log("notice",H,R)}static warning(H,R){this.getFacadeRoot().log("warning",H,R)}static error(H,R){this.getFacadeRoot().log("error",H,R)}static critical(H,R){this.getFacadeRoot().log("critical",H,R)}static alert(H,R){this.getFacadeRoot().log("alert",H,R)}static emergency(H,R){this.getFacadeRoot().log("emergency",H,R)}}
5
+ export{k as Ke,l as Le,A as Me,PH as Ne,VH as Oe,SH as Pe,c as Qe,b as Re,LH as Se,jH as Te,MH as Ue,f as Ve,_H as We,d as Xe,EH as Ye,IH as Ze,xH as _e,$ as $e,B as af,D as bf,HH as cf,RH as df,p as ef,S as ff,U as gf,TH as hf,L as if,s as jf,w as kf,u as lf,_ as mf,JR as nf,o as of,E as pf,ZH as qf,q as rf,WH as sf};
6
+
7
+ //# debugId=C06EF1FC40EB69B364756E2164756E21
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../http/Controller.ts", "../http/getCookies.ts", "../http/range.ts", "../http/Error.ts", "../http/Router.ts", "../http/validate.ts", "../http/modelOriginated.ts", "../http/requestDomain.ts", "../http/HttpRequest.ts", "../http/errors.ts", "../facades/Facade.ts", "../services/file-storage/drivers/FileStorageDriver.ts", "../services/file-storage/drivers/FileSystemDriver.ts", "../services/file-storage/config.ts", "../services/file-storage/FilesystemManager.ts", "../facades/Storage.ts", "../support/sharp.ts"],
3
+ "sources": ["../http/Controller.ts", "../http/getCookies.ts", "../http/range.ts", "../http/Error.ts", "../http/Router.ts", "../http/validate.ts", "../http/modelOriginated.ts", "../http/requestDomain.ts", "../http/HttpRequest.ts", "../http/errors.ts", "../facades/Facade.ts", "../services/file-storage/drivers/FileStorageDriver.ts", "../services/file-storage/drivers/abortableBody.ts", "../services/file-storage/drivers/FileSystemDriver.ts", "../services/file-storage/config.ts", "../services/file-storage/FilesystemManager.ts", "../facades/Storage.ts", "../support/sharp.ts", "../services/logging/LogManager.ts", "../facades/Log.ts"],
4
4
  "sourcesContent": [
5
5
  "import type { HttpRequest } from \"./HttpRequest\";\n\nexport class Controller {\n static kind = \"controller\" as const;\n\n constructor() {}\n}\n\ntype PromiseOrData<T> = T | Promise<T>;\n\nexport abstract class ResourceController extends Controller {\n abstract store(req: HttpRequest<any, any>): PromiseOrData<any>;\n abstract update(req: HttpRequest<any, any>): PromiseOrData<any>;\n abstract delete(req: HttpRequest<any, any>): PromiseOrData<any>;\n abstract list(req: HttpRequest<any, any>): PromiseOrData<any>;\n abstract show(req: HttpRequest<any, any>): PromiseOrData<any>;\n}\n\nexport type ControllerMethods<\n T extends new () => Controller | ResourceController,\n> = {\n [K in keyof InstanceType<T>]: InstanceType<T>[K] extends Function ? K : never;\n}[keyof InstanceType<T>];\n",
6
6
  "/**\n * Parses a `Cookie` request header into name -> value.\n *\n * Splits each pair on its *first* `=`: base64 padding and JWTs put `=` inside\n * the value, and splitting on every one would cut them off. A segment with no\n * `=` or an empty name is skipped rather than thrown on, since browsers and\n * proxies do send `flag;`-style pairs and the client may not control them.\n * A repeated name keeps its last value.\n *\n * Values are not percent-decoded: server-written cookies (`createCookie`) are\n * unencoded, so decoding here would change any value that happens to contain\n * a `%`. A cookie the browser writes may be encoded — `useLocale` encodes\n * `i18n-locale` — and its reader decodes it if it needs to.\n */\nexport function parseCookieHeader(header: string | null | undefined): Map<string, string> {\n const cookies = new Map<string, string>();\n if (!header) {\n return cookies;\n }\n for (const pair of header.split(\";\")) {\n const eq = pair.indexOf(\"=\");\n if (eq === -1) continue;\n const name = pair.slice(0, eq).trim();\n if (!name) continue;\n cookies.set(name, pair.slice(eq + 1).trim());\n }\n return cookies;\n}\n\nexport function getCookies(req: Request): Map<string, string> {\n return parseCookieHeader(req.headers.get(\"cookie\"));\n}\n",
@@ -13,14 +13,17 @@
13
13
  "import { parseCookieHeader } from \"./getCookies\";\nimport { isModelOriginated } from \"./modelOriginated\";\nimport { parseRangeHeader } from \"./range\";\nimport { RequestContext } from \"./requestContext\";\nimport { requestDomain } from \"./requestDomain\";\nimport { ValidationError } from \"./Router\";\nimport { InvalidValidationRuleError, validate } from \"./validate\";\nimport type { ResolvedDomain } from \"../services/router/DomainResolver\";\n\nclass Input<T> {\n constructor(private data: T) {}\n\n public get<K extends keyof T>(key: K): T[K] {\n return this.data[key];\n }\n\n public has(key: keyof T) {\n return this.data[key] !== undefined;\n }\n\n public toJSON(): T {\n return this.data;\n }\n}\n\ntype StringType = \"string\";\ntype NumberType = \"number\";\ntype BooleanType = \"boolean\";\ntype MinLengthType = `min:${number}`;\ntype MaxLengthType = `max:${number}`;\n/** Magnitude, for numbers — see `validate`'s `min` case for why these are not\n * the same rule wearing different names. */\ntype GreaterOrEqualType = `gte:${number}`;\ntype LessOrEqualType = `lte:${number}`;\ntype RequiredType = \"required\";\ntype FileType = \"file\";\n// Backticks, not quotes. These two were written with double quotes, which makes\n// them the *literal text* `fileType:${string}` rather than a template literal\n// type — so `fileType:image/png`, the only way anyone would ever write the rule,\n// did not typecheck, while the runtime handled it perfectly well.\ntype FileTypeType = `fileType:${string}`;\ntype FileSizeType = `fileSize:${string}`;\ntype EmailType = \"email\";\ntype PasswordType = \"password\";\n/** One entry per rule in `validate`'s `RULES`; `validate.test-d.ts` holds them\n * to each other, so an offered rule cannot go unimplemented again (#609). */\nexport type SchemaKey =\n | StringType\n | NumberType\n | BooleanType\n | MinLengthType\n | MaxLengthType\n | GreaterOrEqualType\n | LessOrEqualType\n | RequiredType\n | FileType\n | FileTypeType\n | FileSizeType\n | EmailType\n | PasswordType;\n\nexport type Schema<T extends Body> = Record<keyof T, Partial<Record<SchemaKey, string>>>;\n\nexport type Body = Record<string, any>;\nexport type HttpRequestKind = \"view\" | \"api\";\n\nexport class HttpRequest<T extends Body = Record<string, never>, Params = Record<string, never>> {\n kind: HttpRequestKind;\n rawRequest: Request;\n headers: Omit<Headers, \"set\" | \"delete\">;\n cookies: Omit<Map<string, string>, \"set\" | \"delete\">;\n search: Input<any>;\n schema: any = {};\n routePath: string;\n params: Params;\n /**\n * The `route.domains` group this request was routed by — `domain.params`\n * holds a `:param` subdomain's value, or what `custom.resolve` returned for\n * a custom domain. `null` when the app declares no `route.domains`.\n *\n * Kept apart from `params`, which are the path's alone.\n */\n domain: ResolvedDomain | null;\n\n constructor(req?: Request, params?: any, kind?: HttpRequestKind, routePath?: string) {\n if (!req) {\n const _req = RequestContext.getStore().req;\n this.params = _req.params as any;\n this.rawRequest = _req.rawRequest;\n this.kind = _req.kind;\n this.routePath = _req.routePath;\n this.domain = _req.domain ?? null;\n } else {\n this.params = params;\n this.rawRequest = req;\n this.routePath = routePath;\n this.kind = kind ?? \"api\";\n this.domain = requestDomain(req);\n }\n\n this.headers = this.rawRequest.headers;\n\n const cookies = parseCookieHeader(this.rawRequest.headers.get(\"Cookie\"));\n const url = new URL(this.rawRequest.url);\n const map = new Map<string, string | string[]>();\n for (const [key, value] of url.searchParams) {\n if (map.has(key)) {\n const currentValue = map.get(key);\n if (Array.isArray(currentValue)) {\n currentValue.push(value);\n map.set(key, currentValue);\n } else {\n map.set(key, [currentValue, value]);\n }\n } else {\n map.set(key, value);\n }\n }\n const _params = Object.fromEntries(map.entries());\n this.search = new Input(_params);\n this.cookies = cookies;\n }\n\n locale() {\n return RequestContext.getStore().locale;\n }\n\n ctx() {\n return RequestContext.getStore();\n }\n\n /**\n * Whether the framework dispatched this request in-process for a model — a\n * tool call — rather than a client sending it. Readable in `onRequestStart`,\n * in middleware and in the handler alike.\n *\n * No header or cookie can make this true; see `http/modelOriginated.ts`.\n */\n isModelOriginated(): boolean {\n return isModelOriginated(this.rawRequest);\n }\n\n /**\n * The parsed `Range` header, or `null` when absent or unusable. Pass it to\n * `FileStorage.read(name, { range })` to range explicitly; inside a\n * `this.stream()` route `read()` already picks it up on its own.\n */\n range() {\n return parseRangeHeader(this.rawRequest.headers.get(\"Range\"));\n }\n\n refine(_input: any): any {\n return {};\n }\n\n private async parseBody() {\n let inputMap = new Input<T>({} as T);\n if (this.rawRequest.headers.get(\"Content-Type\") === \"application/json\") {\n const body = await this.rawRequest.json();\n inputMap = new Input<T>(body as T);\n }\n if (this.rawRequest.headers.get(\"Content-Type\") === \"application/x-www-form-urlencoded\") {\n const body = (await this.rawRequest.formData()) as any; // TODO: fix type\n inputMap = new Input<T>(body as T);\n }\n\n if (this.rawRequest.headers.get(\"Content-Type\")?.startsWith(\"multipart/form-data\")) {\n const body = (await this.rawRequest.formData()) as any; // TODO: fix type\n const _inputMap = new Map<string, any>();\n for (const [key, value] of body.entries()) {\n if (_inputMap.has(key)) {\n const currentValue = _inputMap.get(key);\n if (Array.isArray(currentValue)) {\n currentValue.push(value);\n _inputMap.set(key, currentValue);\n } else {\n _inputMap.set(key, [currentValue, value] as any);\n }\n } else {\n _inputMap.set(key, value as T[keyof T]);\n }\n }\n inputMap = new Input<T>(Object.fromEntries(_inputMap.entries()) as T);\n }\n return inputMap;\n }\n\n private validateInput(input: Input<T>) {\n const errors: Record<string, string[]> = {};\n const fields = Object.entries(this.schema as Record<string, Record<string, unknown>>).map(\n ([key, rules]) => ({\n key,\n // Every rule is looked up before any value is checked, so a schema that\n // names an unknown rule throws on every request, whatever the body —\n // not only on the ones whose earlier rules happened to pass. A function\n // is its own validator: its key is a label, and is not looked up.\n rules: Object.entries(rules).map(([rule, message]) => ({\n rule,\n message,\n check: typeof message === \"function\" ? null : this.ruleFor(key, rule),\n })),\n }),\n );\n\n for (const { key, rules } of fields) {\n const value = input.get(key as keyof T);\n const isRequired = rules.some(({ rule }) => rule === \"required\");\n // Absent: skipped unless `required`. `0` and `false` are values, and are\n // checked like any other — skipping every falsy value let `0` and `false` through a\n // `string` rule and `0` through a `boolean` one.\n const isAbsent = value === undefined || value === null || (value as unknown) === \"\";\n const messages: string[] = [];\n\n for (const { rule, message, check } of rules) {\n let _message = message;\n let _isValid = false;\n if (typeof message === \"function\") {\n _message = message(value);\n _isValid = typeof _message === \"undefined\";\n } else {\n _isValid = check!(value);\n }\n\n if (_isValid) {\n continue;\n }\n\n if (isAbsent && !isRequired) {\n continue;\n }\n\n if (rule === \"required\") {\n // A missing field reports that it is missing, and only that — not\n // also that `undefined` is not a string. Wherever `required` sits\n // among the field's rules.\n messages.splice(0, messages.length, String(_message));\n break;\n }\n\n messages.push(String(_message));\n }\n\n if (messages.length > 0) {\n errors[key] = messages;\n }\n }\n\n for (const [key, value] of Object.entries(this.refine(input.toJSON()) ?? {})) {\n if (!errors[key]) {\n errors[key] = [];\n }\n errors[key] = [...(errors[key] ?? []), value as string];\n }\n\n if (Object.keys(errors).length > 0) {\n throw new ValidationError(errors);\n }\n\n return input;\n }\n\n private ruleFor(key: string, rule: string) {\n try {\n return validate(rule);\n } catch (err) {\n if (err instanceof InvalidValidationRuleError) {\n throw new InvalidValidationRuleError(\n `${this.constructor.name}.schema.${key}: ${err.message}`,\n );\n }\n throw err;\n }\n }\n\n async input(): Promise<Input<T>> {\n return this.validateInput(await this.parseBody());\n }\n\n async safeInput(): Promise<{\n isValid: boolean;\n errors: Record<string, string[]>;\n input: Input<T>;\n }> {\n const input = await this.parseBody();\n try {\n this.validateInput(input);\n return {\n isValid: true,\n errors: {},\n input,\n };\n } catch (err) {\n if (!(err instanceof ValidationError)) {\n throw err;\n }\n return {\n isValid: false,\n errors: err.errors,\n input,\n };\n }\n }\n}\n",
14
14
  "import { RequestBreakerError } from \"./Error\";\nimport { formatUnsatisfiedContentRange } from \"./range\";\n\nexport class AuthorizationError extends RequestBreakerError {\n private error: string;\n constructor(error: string = \"Not authorized\") {\n super(error);\n this.name = \"AuthorizationError\";\n this.error = error;\n this.payload = {\n api: {\n status: 401,\n data: { error: this.error },\n },\n view: {},\n };\n }\n}\n\n/**\n * A signed-in user who is not allowed to do this. Thrown by `Auth.guard()`.\n *\n * 403, not 401: a 401 tells the client to re-authenticate, so a client that\n * sends a 401 to the sign-in page would loop a signed-in user without the role\n * straight back to where they started. A request with no user at all is\n * `AuthenticationError`, which stays 401.\n */\nexport class InsufficientPermissionsError extends RequestBreakerError {\n /**\n * The status of `payload.api`, which answers API routes and `.json` view\n * navigations alike. Before 0.63 it was 401, and a shipped native client may\n * still branch on that — it cannot be rolled forward in the same deploy as\n * the server. Such an app sets this back to 401 once at boot, and removes the\n * line when its clients handle 403:\n *\n * ```ts\n * InsufficientPermissionsError.apiStatus = 401;\n * ```\n *\n * A full page load answers 403 either way; before 0.63 it fell through to\n * the view dispatcher's 400 default, which no client could have relied on.\n */\n static apiStatus: 401 | 403 = 403;\n\n private error: string;\n constructor(error: string = \"Insufficient permissions\") {\n super(error);\n this.name = \"InsufficientPermissionsError\";\n this.error = error;\n this.payload = {\n api: {\n status: InsufficientPermissionsError.apiStatus,\n data: { error: this.error },\n },\n // Without a status a view request would fall through to the\n // dispatcher's 400 default.\n view: { status: 403 },\n };\n }\n}\n\n/**\n * A `Range` that cannot be satisfied against the object's current size.\n *\n * Extends `RequestBreakerError` so a bare `FileStorage.read()` inside an\n * ordinary route still produces a correct 416 — and, importantly, so it does\n * not trip `onRequestFail`. A 416 is the client's header being wrong about the\n * object, not a server failure.\n */\nexport class RangeNotSatisfiableError extends RequestBreakerError {\n constructor(public total: number) {\n super(\"Range not satisfiable\");\n this.name = \"RangeNotSatisfiableError\";\n this.payload = {\n api: {\n status: 416,\n data: { error: { message: \"Range not satisfiable\" } },\n headers: {\n \"Content-Range\": formatUnsatisfiedContentRange(total),\n \"Accept-Ranges\": \"bytes\",\n // Decided by the client's own Range against the object's current\n // length, so it must never be replayed from a cache to a request\n // that did not ask for that window.\n \"Cache-Control\": \"no-store\",\n },\n },\n view: {},\n };\n }\n}\n\nexport class FileNotFoundError extends RequestBreakerError {\n constructor(public fileName: string) {\n super(\"File not found\");\n this.name = \"FileNotFoundError\";\n this.payload = {\n api: {\n status: 404,\n data: { error: { message: \"Not found\" } },\n headers: { \"Cache-Control\": \"no-store\" },\n },\n view: {},\n };\n }\n}\n\n/**\n * No signed-in user. A 401 to an API client; a view request is sent to\n * `redirectTo` instead — a 302 for a page load, and a `Redirect` directive for\n * a `.json` navigation, so the client router follows it rather than leaving\n * the previous page on screen.\n *\n * `redirectTo` is the whole location, intended-URL parameter included.\n * `AuthenticationMiddleware` and `Auth.user()` build it from the request and\n * the `auth.signInPath` config; code throwing this by hand can pass its own.\n */\nexport class AuthenticationError extends RequestBreakerError {\n constructor(options: { redirectTo?: string } = {}) {\n super(\"Authentication error\");\n this.name = \"AuthenticationError\";\n const location = options.redirectTo ?? \"/auth/sign-in\";\n this.payload = {\n api: {\n status: 401,\n data: { error: \"Authentication error\" },\n },\n viewData: {\n status: 200,\n data: {},\n // A refusal is per-visitor, and this one answers 200 so that\n // `loadRoutePayload` reads it at all — which makes it exactly the\n // shape a shared cache would happily store and replay to the next\n // visitor. The `view` payload below says the same thing.\n headers: {\n \"Cache-Control\": \"private, no-cache, no-store, max-age=0, must-revalidate\",\n },\n directive: { kind: \"Redirect\", path: location },\n },\n view: {\n status: 302,\n headers: {\n \"Cache-Control\":\n \"private, no-cache, no-store, max-age=0, must-revalidate\",\n Location: location,\n },\n },\n };\n }\n}\n",
15
15
  "import type { ServiceToken } from \"../container/Container\";\nimport { app } from \"../foundation/app\";\n\n/**\n * Base for the facades that front a container binding. A subclass names the\n * service it proxies with `getFacadeAccessor()` and reaches the live instance\n * through `this.getFacadeRoot()`, so the binding is resolved per call against\n * the Application for the current async context — never captured at module\n * load, which is what makes a facade swappable in tests.\n *\n * Two deliberate divergences from `Illuminate\\Support\\Facades\\Facade`:\n *\n * 1. No `__callStatic`. TypeScript has no typed equivalent, and a Proxy would\n * erase the very signatures that make these facades worth having. Subclasses\n * therefore declare explicit statics that forward to `getFacadeRoot()`.\n *\n * 2. `getFacadeAccessor()` is public, not protected. `getFacadeRoot()` types\n * its `this` structurally in order to infer the service type from the\n * accessor's return, and a protected static is not structurally assignable\n * to that.\n *\n * Facades that resolve nothing from the container — Cookie, Redirect, Url,\n * Meta — do not extend this class.\n */\nexport abstract class Facade {\n static getFacadeAccessor(): ServiceToken<any> {\n throw new Error(\n `Facade [${this.name}] does not implement getFacadeAccessor().`,\n );\n }\n\n static getFacadeRoot<T>(this: {\n getFacadeAccessor(): ServiceToken<T>;\n }): T {\n return app(this.getFacadeAccessor());\n }\n}\n",
16
- "import { FileNotFoundError } from \"../../../http/errors\";\nimport type {\n DeleteFileParams,\n IFileStorageDriver,\n PutFileOptions,\n PutFileParams,\n ReadFileParams,\n ReadResult,\n} from \"./types\";\n\nexport abstract class FileStorageDriver implements IFileStorageDriver {\n abstract fetch(params: ReadFileParams | string): Promise<Response>;\n abstract put(\n params: PutFileParams | Blob,\n options?: PutFileOptions,\n ): Promise<string>;\n abstract list(folder: string): Promise<any>;\n\n /**\n * Removes an object. A missing object is not an error: the promise resolves,\n * so cleanup can run twice, or after a write that never landed.\n *\n * Not abstract, for the same reason `read()` is not: a custom driver written\n * before `delete()` existed keeps compiling. It must not keep *working* as if\n * it deleted, though — silently resolving here is exactly the bug `delete()`\n * used to have (#608) — so the default throws and names the driver.\n */\n async delete(_params: DeleteFileParams | string): Promise<void> {\n throw new Error(\n `${this.constructor.name} does not implement delete(). Override it to remove objects from this backend.`,\n );\n }\n\n /**\n * Default `read()` for drivers that only implement `fetch()`.\n *\n * Deliberately not abstract: every driver written before `read()` existed\n * keeps compiling and gains working range support for free. It is not\n * *efficient* though — to serve a range it buffers the whole object so the\n * framework can slice it, which saves no bandwidth from the backend. Any\n * driver whose backend can range natively should override this.\n */\n async read(input: ReadFileParams | string): Promise<ReadResult> {\n const params = typeof input === \"string\" ? { name: input } : input;\n const response = await this.fetch({\n name: params.name,\n bucket: params.bucket,\n });\n\n if (!response.ok) {\n throw new FileNotFoundError(params.name);\n }\n\n const type =\n response.headers.get(\"Content-Type\") ?? \"application/octet-stream\";\n const etag = response.headers.get(\"ETag\") ?? undefined;\n const lastModifiedHeader = response.headers.get(\"Last-Modified\");\n const lastModified = lastModifiedHeader\n ? new Date(lastModifiedHeader)\n : undefined;\n\n if (params.range) {\n const blob = await response.blob();\n return {\n body: blob,\n start: 0,\n end: blob.size - 1,\n total: blob.size,\n // The range was not applied by the backend. Reporting `false` hands\n // the slicing to `createStreamResponse`, which has the total in hand.\n partial: false,\n type,\n etag,\n lastModified,\n name: params.name,\n };\n }\n\n const contentLength = Number(response.headers.get(\"Content-Length\"));\n const total = Number.isFinite(contentLength) ? contentLength : 0;\n\n return {\n body: response.body,\n start: 0,\n end: total - 1,\n total,\n partial: false,\n type,\n etag,\n lastModified,\n name: params.name,\n };\n }\n\n /**\n * Total size of an object. Used to resolve suffix ranges on backends without\n * native suffix support, and to report the total on a 416. Override with a\n * HEAD-style request wherever one is available.\n */\n async size(params: ReadFileParams | string): Promise<number> {\n const name = typeof params === \"string\" ? params : params.name;\n const bucket = typeof params === \"string\" ? undefined : params.bucket;\n const response = await this.fetch({ name, bucket });\n if (!response.ok) {\n throw new FileNotFoundError(name);\n }\n const contentLength = Number(response.headers.get(\"Content-Length\"));\n if (Number.isFinite(contentLength)) {\n await response.body?.cancel();\n return contentLength;\n }\n return (await response.blob()).size;\n }\n}\n",
17
- "import type { DeleteFileParams, PutFileOptions, PutFileParams, ReadFileParams, ReadResult } from \"./types\";\nimport { FileStorageDriver } from \"./FileStorageDriver\";\nimport { readdir, unlink } from \"fs/promises\";\nimport { isAbsolute, relative, resolve, sep } from \"node:path\";\nimport { resolveRange } from \"../../../http/range\";\nimport { FileNotFoundError, RangeNotSatisfiableError } from \"../../../http/errors\";\nimport { projectRoot } from \"../../../support/discover\";\n\nexport class FileSystemDriver extends FileStorageDriver {\n private readonly configured?: string;\n\n constructor(folderPath?: string) {\n super();\n this.configured = folderPath;\n }\n\n /**\n * Computed per read, not baked into a constructor default.\n *\n * This is the second time this exact bug has been written in this repository,\n * and `LogManager.logsDirPath` carries the first one's post-mortem: a driver\n * is constructed when `app/config/filesystem.ts` is evaluated, and that\n * happens *before* the http layer sets `ROOT_DIR`. So the old default,\n * `` `${process.env.ROOT_DIR}/storage` ``, interpolated `undefined` and froze\n * it — measured, `new FileSystemDriver().folderPath` was `\"undefined/storage\"`\n * with `ROOT_DIR` unset, and stayed `\"undefined/storage\"` after the server set\n * it a moment later.\n *\n * It fails quietly, which is what makes it worth a comment rather than a\n * one-line fix: reads and writes both used the same wrong folder, so nothing\n * threw and nothing 404'd. Files simply accumulated in a stray `undefined/`\n * directory beside the project, and the only way to notice was to look.\n *\n * `projectRoot()` is the same rule `httpProd` computes `ROOT_DIR` from, so an\n * explicit folder still wins and an app that configured nothing now gets the\n * directory it always meant.\n */\n private get folderPath(): string {\n return this.configured ?? `${projectRoot()}/storage`;\n }\n\n async put(params: PutFileParams | Blob, { signal }: PutFileOptions = {}) {\n signal?.throwIfAborted();\n\n let body: Blob | File | Buffer;\n let name: string;\n\n if (params instanceof Blob) {\n body = params;\n name = `${Bun.randomUUIDv7()}.${params.type.split(\"/\")[1].split(\";\")[0]}`;\n } else {\n body = params.body;\n name = params.name;\n }\n\n const buffer =\n body instanceof Buffer\n ? body\n : body instanceof Blob || body instanceof File\n ? Buffer.from(await body.arrayBuffer())\n : \"\";\n\n const path = `${this.folderPath}/${name}`;\n\n // `Bun.write` takes no signal, and a local write is not worth interrupting\n // halfway, so the last chance to abort is once the body has been read.\n signal?.throwIfAborted();\n await Bun.write(path, buffer as any);\n\n return name;\n }\n\n async fetch(params: ReadFileParams | string) {\n let bucket = process.env.BUCKET_NAME;\n let name: string | undefined;\n\n if (typeof params === \"string\") {\n name = params;\n } else {\n bucket = params.bucket ?? bucket;\n name = params.name;\n }\n\n if (!name) {\n throw new Error(\"Object name has to be specified\");\n }\n\n const path = `${this.folderPath}/${name}`;\n const file = Bun.file(path);\n const result = Bun.file(path).stream();\n const date = new Date(file.lastModified).toUTCString();\n\n return new Response(result, {\n headers: {\n \"Content-Type\": file.type,\n \"Content-Length\": String(file.size),\n \"Cache-Control\": \"private, max-age=12000, must-revalidate\",\n // TODO: fix this.\n \"Last-Modified\": date,\n },\n });\n }\n\n async read(input: ReadFileParams | string): Promise<ReadResult> {\n const params = typeof input === \"string\" ? { name: input } : input;\n const { name, range = null } = params;\n\n if (!name) {\n throw new Error(\"Object name has to be specified\");\n }\n\n const file = Bun.file(`${this.folderPath}/${name}`);\n\n // `Bun.file()` is lazy. Without this the response commits with a 200 and\n // the ENOENT only surfaces once the stream is pulled, as an unhandled\n // rejection with the status already on the wire.\n if (!(await file.exists())) {\n throw new FileNotFoundError(name);\n }\n\n const total = file.size;\n const resolved = range ? resolveRange(range, total) : null;\n\n if (range && !resolved) {\n throw new RangeNotSatisfiableError(total);\n }\n\n const start = resolved?.start ?? 0;\n const end = resolved ? resolved.end : total - 1;\n\n return {\n // A BunFile slice stays lazy and keeps a known size, so Bun can send it\n // with a real Content-Length instead of falling back to chunked.\n body: resolved ? file.slice(start, end + 1) : file,\n start,\n end,\n total,\n partial: Boolean(resolved),\n type: file.type || \"application/octet-stream\",\n lastModified: new Date(file.lastModified),\n name,\n };\n }\n\n async size(params: ReadFileParams | string) {\n const name = typeof params === \"string\" ? params : params.name;\n const file = Bun.file(`${this.folderPath}/${name}`);\n if (!(await file.exists())) {\n throw new FileNotFoundError(name);\n }\n return file.size;\n }\n\n async delete(params: DeleteFileParams | string) {\n const name = typeof params === \"string\" ? params : params.name;\n\n if (!name) {\n throw new Error(\"Object name has to be specified\");\n }\n\n // A bucket key cannot climb out of its bucket, but a path can: refuse a\n // name that resolves outside the storage folder rather than unlink it.\n const root = resolve(this.folderPath);\n const path = resolve(root, name);\n const rel = relative(root, path);\n if (!rel || rel === \"..\" || rel.startsWith(`..${sep}`) || isAbsolute(rel)) {\n throw new Error(`Refusing to delete \"${name}\": it is outside the storage folder`);\n }\n\n try {\n await unlink(path);\n } catch (err: any) {\n // Already gone is the outcome the caller asked for.\n if (err?.code === \"ENOENT\") {\n return;\n }\n throw err;\n }\n }\n\n async list() {\n const files = await readdir(this.folderPath);\n\n return files;\n }\n}\n",
16
+ "import { FileNotFoundError } from \"../../../http/errors\";\nimport type {\n DeleteFileParams,\n FetchFileOptions,\n IFileStorageDriver,\n PutFileOptions,\n PutFileParams,\n ReadFileParams,\n ReadResult,\n} from \"./types\";\n\nexport abstract class FileStorageDriver implements IFileStorageDriver {\n abstract fetch(\n params: ReadFileParams | string,\n options?: FetchFileOptions,\n ): Promise<Response>;\n abstract put(\n params: PutFileParams | Blob,\n options?: PutFileOptions,\n ): Promise<string>;\n abstract list(folder: string): Promise<any>;\n\n /**\n * Removes an object. A missing object is not an error: the promise resolves,\n * so cleanup can run twice, or after a write that never landed.\n *\n * Not abstract, for the same reason `read()` is not: a custom driver written\n * before `delete()` existed keeps compiling. It must not keep *working* as if\n * it deleted, though — silently resolving here is exactly the bug `delete()`\n * used to have (#608) — so the default throws and names the driver.\n */\n async delete(_params: DeleteFileParams | string): Promise<void> {\n throw new Error(\n `${this.constructor.name} does not implement delete(). Override it to remove objects from this backend.`,\n );\n }\n\n /**\n * Default `read()` for drivers that only implement `fetch()`.\n *\n * Deliberately not abstract: every driver written before `read()` existed\n * keeps compiling and gains working range support for free. It is not\n * *efficient* though — to serve a range it buffers the whole object so the\n * framework can slice it, which saves no bandwidth from the backend. Any\n * driver whose backend can range natively should override this.\n */\n async read(input: ReadFileParams | string): Promise<ReadResult> {\n const params = typeof input === \"string\" ? { name: input } : input;\n const response = await this.fetch({\n name: params.name,\n bucket: params.bucket,\n });\n\n if (!response.ok) {\n throw new FileNotFoundError(params.name);\n }\n\n const type =\n response.headers.get(\"Content-Type\") ?? \"application/octet-stream\";\n const etag = response.headers.get(\"ETag\") ?? undefined;\n const lastModifiedHeader = response.headers.get(\"Last-Modified\");\n const lastModified = lastModifiedHeader\n ? new Date(lastModifiedHeader)\n : undefined;\n\n if (params.range) {\n const blob = await response.blob();\n return {\n body: blob,\n start: 0,\n end: blob.size - 1,\n total: blob.size,\n // The range was not applied by the backend. Reporting `false` hands\n // the slicing to `createStreamResponse`, which has the total in hand.\n partial: false,\n type,\n etag,\n lastModified,\n name: params.name,\n };\n }\n\n const contentLength = Number(response.headers.get(\"Content-Length\"));\n const total = Number.isFinite(contentLength) ? contentLength : 0;\n\n return {\n body: response.body,\n start: 0,\n end: total - 1,\n total,\n partial: false,\n type,\n etag,\n lastModified,\n name: params.name,\n };\n }\n\n /**\n * Total size of an object. Used to resolve suffix ranges on backends without\n * native suffix support, and to report the total on a 416. Override with a\n * HEAD-style request wherever one is available.\n */\n async size(params: ReadFileParams | string): Promise<number> {\n const name = typeof params === \"string\" ? params : params.name;\n const bucket = typeof params === \"string\" ? undefined : params.bucket;\n const response = await this.fetch({ name, bucket });\n if (!response.ok) {\n throw new FileNotFoundError(name);\n }\n const contentLength = Number(response.headers.get(\"Content-Length\"));\n if (Number.isFinite(contentLength)) {\n await response.body?.cancel();\n return contentLength;\n }\n return (await response.blob()).size;\n }\n}\n",
17
+ "/**\n * Ties a response body to an `AbortSignal`, so aborting after `fetch()` has\n * resolved still reaches a caller that is reading the body.\n *\n * Handing the signal to the SDK is not enough on its own: once the headers are\n * back, whether an abort also errors the body stream depends on the SDK and\n * the runtime, and a caller parked in `arrayBuffer()` must not hang. So on\n * abort the returned stream errors with the signal's reason, and the source\n * stream is cancelled, which releases the file handle or the connection.\n *\n * The abort listener is removed once the body finishes, errors or is\n * cancelled, so a long-lived signal (a request's, say) does not collect one\n * listener per read.\n */\nexport function abortableBody(\n body: ReadableStream<Uint8Array>,\n signal: AbortSignal | undefined,\n): ReadableStream<Uint8Array> {\n if (!signal) {\n return body;\n }\n\n const reader = body.getReader();\n let settled = false;\n let onAbort: (() => void) | undefined;\n\n const detach = () => {\n settled = true;\n if (onAbort) {\n signal.removeEventListener(\"abort\", onAbort);\n }\n };\n\n return new ReadableStream<Uint8Array>(\n {\n start(controller) {\n onAbort = () => {\n if (settled) return;\n detach();\n controller.error(signal.reason);\n reader.cancel(signal.reason).catch(() => {});\n };\n if (signal.aborted) {\n onAbort();\n } else {\n signal.addEventListener(\"abort\", onAbort, { once: true });\n }\n },\n async pull(controller) {\n let chunk: Awaited<ReturnType<typeof reader.read>>;\n try {\n chunk = await reader.read();\n } catch (err) {\n if (settled) return;\n detach();\n controller.error(err);\n return;\n }\n // An abort that landed while the read was pending has already\n // errored the stream, and a cancelled reader resolves `done`.\n if (settled) return;\n if (chunk.done) {\n detach();\n controller.close();\n return;\n }\n controller.enqueue(chunk.value);\n },\n cancel(reason) {\n detach();\n return reader.cancel(reason);\n },\n },\n // Pull only on demand, so nothing is read ahead of the consumer.\n { highWaterMark: 0 },\n );\n}\n",
18
+ "import type {\n DeleteFileParams,\n FetchFileOptions,\n PutFileOptions,\n PutFileParams,\n ReadFileParams,\n ReadResult,\n} from \"./types\";\nimport { FileStorageDriver } from \"./FileStorageDriver\";\nimport { abortableBody } from \"./abortableBody\";\nimport { readdir, unlink } from \"fs/promises\";\nimport { isAbsolute, relative, resolve, sep } from \"node:path\";\nimport { resolveRange } from \"../../../http/range\";\nimport { FileNotFoundError, RangeNotSatisfiableError } from \"../../../http/errors\";\nimport { projectRoot } from \"../../../support/discover\";\n\nexport class FileSystemDriver extends FileStorageDriver {\n private readonly configured?: string;\n\n constructor(folderPath?: string) {\n super();\n this.configured = folderPath;\n }\n\n /**\n * Computed per read, not baked into a constructor default.\n *\n * This is the second time this exact bug has been written in this repository,\n * and `LogManager.logsDirPath` carries the first one's post-mortem: a driver\n * is constructed when `app/config/filesystem.ts` is evaluated, and that\n * happens *before* the http layer sets `ROOT_DIR`. So the old default,\n * `` `${process.env.ROOT_DIR}/storage` ``, interpolated `undefined` and froze\n * it — measured, `new FileSystemDriver().folderPath` was `\"undefined/storage\"`\n * with `ROOT_DIR` unset, and stayed `\"undefined/storage\"` after the server set\n * it a moment later.\n *\n * It fails quietly, which is what makes it worth a comment rather than a\n * one-line fix: reads and writes both used the same wrong folder, so nothing\n * threw and nothing 404'd. Files simply accumulated in a stray `undefined/`\n * directory beside the project, and the only way to notice was to look.\n *\n * `projectRoot()` is the same rule `httpProd` computes `ROOT_DIR` from, so an\n * explicit folder still wins and an app that configured nothing now gets the\n * directory it always meant.\n */\n private get folderPath(): string {\n return this.configured ?? `${projectRoot()}/storage`;\n }\n\n async put(params: PutFileParams | Blob, { signal }: PutFileOptions = {}) {\n signal?.throwIfAborted();\n\n let body: Blob | File | Buffer;\n let name: string;\n\n if (params instanceof Blob) {\n body = params;\n name = `${Bun.randomUUIDv7()}.${params.type.split(\"/\")[1].split(\";\")[0]}`;\n } else {\n body = params.body;\n name = params.name;\n }\n\n const buffer =\n body instanceof Buffer\n ? body\n : body instanceof Blob || body instanceof File\n ? Buffer.from(await body.arrayBuffer())\n : \"\";\n\n const path = `${this.folderPath}/${name}`;\n\n // `Bun.write` takes no signal, and a local write is not worth interrupting\n // halfway, so the last chance to abort is once the body has been read.\n signal?.throwIfAborted();\n await Bun.write(path, buffer as any);\n\n return name;\n }\n\n async fetch(\n params: ReadFileParams | string,\n { signal }: FetchFileOptions = {},\n ) {\n signal?.throwIfAborted();\n\n let bucket = process.env.BUCKET_NAME;\n let name: string | undefined;\n\n if (typeof params === \"string\") {\n name = params;\n } else {\n bucket = params.bucket ?? bucket;\n name = params.name;\n }\n\n if (!name) {\n throw new Error(\"Object name has to be specified\");\n }\n\n const path = `${this.folderPath}/${name}`;\n const file = Bun.file(path);\n // The disk read has no signal of its own. The body is wrapped instead, so\n // an abort stops the stream and closes the file mid-read.\n const result = abortableBody(Bun.file(path).stream(), signal);\n const date = new Date(file.lastModified).toUTCString();\n\n return new Response(result, {\n headers: {\n \"Content-Type\": file.type,\n \"Content-Length\": String(file.size),\n \"Cache-Control\": \"private, max-age=12000, must-revalidate\",\n // TODO: fix this.\n \"Last-Modified\": date,\n },\n });\n }\n\n async read(input: ReadFileParams | string): Promise<ReadResult> {\n const params = typeof input === \"string\" ? { name: input } : input;\n const { name, range = null } = params;\n\n if (!name) {\n throw new Error(\"Object name has to be specified\");\n }\n\n const file = Bun.file(`${this.folderPath}/${name}`);\n\n // `Bun.file()` is lazy. Without this the response commits with a 200 and\n // the ENOENT only surfaces once the stream is pulled, as an unhandled\n // rejection with the status already on the wire.\n if (!(await file.exists())) {\n throw new FileNotFoundError(name);\n }\n\n const total = file.size;\n const resolved = range ? resolveRange(range, total) : null;\n\n if (range && !resolved) {\n throw new RangeNotSatisfiableError(total);\n }\n\n const start = resolved?.start ?? 0;\n const end = resolved ? resolved.end : total - 1;\n\n return {\n // A BunFile slice stays lazy and keeps a known size, so Bun can send it\n // with a real Content-Length instead of falling back to chunked.\n body: resolved ? file.slice(start, end + 1) : file,\n start,\n end,\n total,\n partial: Boolean(resolved),\n type: file.type || \"application/octet-stream\",\n lastModified: new Date(file.lastModified),\n name,\n };\n }\n\n async size(params: ReadFileParams | string) {\n const name = typeof params === \"string\" ? params : params.name;\n const file = Bun.file(`${this.folderPath}/${name}`);\n if (!(await file.exists())) {\n throw new FileNotFoundError(name);\n }\n return file.size;\n }\n\n async delete(params: DeleteFileParams | string) {\n const name = typeof params === \"string\" ? params : params.name;\n\n if (!name) {\n throw new Error(\"Object name has to be specified\");\n }\n\n // A bucket key cannot climb out of its bucket, but a path can: refuse a\n // name that resolves outside the storage folder rather than unlink it.\n const root = resolve(this.folderPath);\n const path = resolve(root, name);\n const rel = relative(root, path);\n if (!rel || rel === \"..\" || rel.startsWith(`..${sep}`) || isAbsolute(rel)) {\n throw new Error(`Refusing to delete \"${name}\": it is outside the storage folder`);\n }\n\n try {\n await unlink(path);\n } catch (err: any) {\n // Already gone is the outcome the caller asked for.\n if (err?.code === \"ENOENT\") {\n return;\n }\n throw err;\n }\n }\n\n async list() {\n const files = await readdir(this.folderPath);\n\n return files;\n }\n}\n",
18
19
  "import type { FileStorageDriver } from \"./drivers/FileStorageDriver\";\nimport { FileSystemDriver } from \"./drivers/FileSystemDriver\";\n\n// Config key: `filesystem`. Derived from `FileStorageServiceProvider`.\nexport interface FilesystemConfig {\n driver?: FileStorageDriver;\n}\n\nexport function defineFilesystemConfig(\n config: FilesystemConfig,\n): FilesystemConfig {\n return config;\n}\n\nexport function filesystemConfigDefaults(): Required<FilesystemConfig> {\n return {\n driver: new FileSystemDriver(),\n };\n}\n",
19
20
  "import type { FileStorageDriver } from \"./drivers/FileStorageDriver\";\nimport { filesystemConfigDefaults, type FilesystemConfig } from \"./config\";\n\nexport class FilesystemManager {\n static token = \"filesystem\";\n\n readonly driver: FileStorageDriver;\n\n constructor(config: FilesystemConfig = {}) {\n this.driver = config.driver ?? filesystemConfigDefaults().driver;\n }\n}\n",
20
- "//@ts-ignore - type-only; the module itself is loaded on first use by `metadata()`.\nimport type sharp from \"sharp\";\n\nimport { Buffer } from \"node:buffer\";\nimport { loadSharp } from \"../support/sharp\";\nimport type { Prettify } from \"../utils/type\";\n\nimport { RequestContext } from \"../http/requestContext\";\nimport type { ByteRange } from \"../http/range\";\nimport type {\n DeleteFileParams,\n PutFileOptions,\n PutFileParams,\n ReadFileParams,\n ReadResult,\n} from \"../services/file-storage/drivers/types\";\nimport { FilesystemManager } from \"../services/file-storage/FilesystemManager\";\nimport { Facade } from \"./Facade\";\n\ntype Metadata = Prettify<sharp.Metadata>;\n\nexport class Storage extends Facade {\n static getFacadeAccessor() {\n return FilesystemManager;\n }\n\n /**\n * Stores a file and returns its object name. Pass `{ signal }` to cancel the\n * upload, e.g. with the incoming request's signal or `AbortSignal.timeout()`.\n */\n static async put(params: PutFileParams | Blob, options: PutFileOptions = {}) {\n return this.getFacadeRoot().driver.put(params, options);\n }\n\n static async metadata(obj: Blob | File): Promise<Partial<Metadata>> {\n const buffer = Buffer.from(await obj.arrayBuffer());\n // Outside the catch: the empty object below means \"this blob is not an\n // image sharp can read\", and a missing `sharp` install must not be able to\n // hide behind it.\n const sharp = await loadSharp(\"Storage.metadata()\");\n try {\n return await sharp(buffer).metadata();\n } catch {\n return {};\n }\n }\n\n static async fetch(params: ReadFileParams | string) {\n return this.getFacadeRoot().driver.fetch(params);\n }\n\n /**\n * Reads an object as bytes plus metadata, pushing any byte range down to the\n * storage backend so a seek transfers one window rather than the whole file.\n *\n * The range is resolved in this order: an explicit `options.range`, then a\n * `range` on `params`, then the in-flight request's `Range` header when this\n * is called inside a `this.stream()` route. Pass `{ range: null }` to force a\n * full read inside a stream route.\n */\n static async read(\n params: ReadFileParams | string,\n options: { range?: ByteRange | null } = {},\n ): Promise<ReadResult> {\n const base: ReadFileParams =\n typeof params === \"string\" ? { name: params } : { ...params };\n\n const range =\n \"range\" in options\n ? (options.range ?? null)\n : base.range !== undefined\n ? base.range\n : (RequestContext.getStore()?.rangeRequest ?? null);\n\n return this.getFacadeRoot().driver.read({\n ...base,\n range,\n });\n }\n static list(folder: string) {\n return this.getFacadeRoot().driver.list(folder);\n }\n\n /**\n * Removes a stored object. Deleting one that does not exist resolves without\n * throwing, so a cleanup path can retry safely.\n */\n static async delete(params: DeleteFileParams | string): Promise<void> {\n return this.getFacadeRoot().driver.delete(params);\n }\n}\n",
21
- "// @ts-ignore - `sharp` is a peer dependency; only its types are wanted here.\nimport type sharpNamespace from \"sharp\";\n\n/**\n * `sharp`, imported on first use rather than at module load.\n *\n * Three modules need it — the `Sharp` optimization driver, the `Storage` facade\n * and the OG-image branch of `ViewRouteDispatcher` — and all three are reachable\n * from the `gemi/services` and `gemi/facades` barrels, which are also the only\n * door an application has to `CronJob`, `Job`, `DB` and `Lang`. A static import\n * made every one of those imports load a native binary (#403).\n *\n * `sharp` is the only one of the four that can be genuinely absent — it is a\n * peer dependency, so an install can skip its platform binary — which is why\n * the failure gets a message naming the caller rather than a bare resolution\n * error. `usedBy` is that name, written as the caller reads in a stack trace.\n *\n * No memo: the module registry already caches a resolved `import()`, and\n * caching the *failure* would make every later call report the first call's\n * stack instead of its own.\n */\nexport async function loadSharp(usedBy: string): Promise<typeof sharpNamespace> {\n try {\n // @ts-ignore - peer dependency, resolved out of the application's own tree\n return (await import(\"sharp\")).default;\n } catch (error) {\n throw new Error(\n `${usedBy} requires the 'sharp' package. Install it with \\`bun add sharp\\`.`,\n { cause: error },\n );\n }\n}\n"
21
+ "//@ts-ignore - type-only; the module itself is loaded on first use by `metadata()`.\nimport type sharp from \"sharp\";\n\nimport { Buffer } from \"node:buffer\";\nimport { loadSharp } from \"../support/sharp\";\nimport type { Prettify } from \"../utils/type\";\n\nimport { RequestContext } from \"../http/requestContext\";\nimport type { ByteRange } from \"../http/range\";\nimport type {\n DeleteFileParams,\n FetchFileOptions,\n PutFileOptions,\n PutFileParams,\n ReadFileParams,\n ReadResult,\n} from \"../services/file-storage/drivers/types\";\nimport { FilesystemManager } from \"../services/file-storage/FilesystemManager\";\nimport { Facade } from \"./Facade\";\n\ntype Metadata = Prettify<sharp.Metadata>;\n\nexport class Storage extends Facade {\n static getFacadeAccessor() {\n return FilesystemManager;\n }\n\n /**\n * Stores a file and returns its object name. Pass `{ signal }` to cancel the\n * upload, e.g. with the incoming request's signal or `AbortSignal.timeout()`.\n */\n static async put(params: PutFileParams | Blob, options: PutFileOptions = {}) {\n return this.getFacadeRoot().driver.put(params, options);\n }\n\n static async metadata(obj: Blob | File): Promise<Partial<Metadata>> {\n const buffer = Buffer.from(await obj.arrayBuffer());\n // Outside the catch: the empty object below means \"this blob is not an\n // image sharp can read\", and a missing `sharp` install must not be able to\n // hide behind it.\n const sharp = await loadSharp(\"Storage.metadata()\");\n try {\n return await sharp(buffer).metadata();\n } catch {\n return {};\n }\n }\n\n /**\n * Reads an object as a streamed `Response`. Pass `{ signal }` to cancel the\n * read, e.g. with the incoming request's signal or `AbortSignal.timeout()`:\n * an abort rejects `fetch()` itself, or errors the body if it lands after\n * `fetch()` resolved.\n */\n static async fetch(\n params: ReadFileParams | string,\n options: FetchFileOptions = {},\n ) {\n // Checked here too, so a custom driver that predates the option still\n // refuses an already-aborted read.\n options.signal?.throwIfAborted();\n return this.getFacadeRoot().driver.fetch(params, options);\n }\n\n /**\n * Reads an object as bytes plus metadata, pushing any byte range down to the\n * storage backend so a seek transfers one window rather than the whole file.\n *\n * The range is resolved in this order: an explicit `options.range`, then a\n * `range` on `params`, then the in-flight request's `Range` header when this\n * is called inside a `this.stream()` route. Pass `{ range: null }` to force a\n * full read inside a stream route.\n */\n static async read(\n params: ReadFileParams | string,\n options: { range?: ByteRange | null } = {},\n ): Promise<ReadResult> {\n const base: ReadFileParams =\n typeof params === \"string\" ? { name: params } : { ...params };\n\n const range =\n \"range\" in options\n ? (options.range ?? null)\n : base.range !== undefined\n ? base.range\n : (RequestContext.getStore()?.rangeRequest ?? null);\n\n return this.getFacadeRoot().driver.read({\n ...base,\n range,\n });\n }\n static list(folder: string) {\n return this.getFacadeRoot().driver.list(folder);\n }\n\n /**\n * Removes a stored object. Deleting one that does not exist resolves without\n * throwing, so a cleanup path can retry safely.\n */\n static async delete(params: DeleteFileParams | string): Promise<void> {\n return this.getFacadeRoot().driver.delete(params);\n }\n}\n",
22
+ "// @ts-ignore - `sharp` is a peer dependency; only its types are wanted here.\nimport type sharpNamespace from \"sharp\";\n\n/**\n * `sharp`, imported on first use rather than at module load.\n *\n * Three modules need it — the `Sharp` optimization driver, the `Storage` facade\n * and the OG-image branch of `ViewRouteDispatcher` — and all three are reachable\n * from the `gemi/services` and `gemi/facades` barrels, which are also the only\n * door an application has to `CronJob`, `Job`, `DB` and `Lang`. A static import\n * made every one of those imports load a native binary (#403).\n *\n * `sharp` is the only one of the four that can be genuinely absent — it is a\n * peer dependency, so an install can skip its platform binary — which is why\n * the failure gets a message naming the caller rather than a bare resolution\n * error. `usedBy` is that name, written as the caller reads in a stack trace.\n *\n * No memo: the module registry already caches a resolved `import()`, and\n * caching the *failure* would make every later call report the first call's\n * stack instead of its own.\n */\nexport async function loadSharp(usedBy: string): Promise<typeof sharpNamespace> {\n try {\n // @ts-ignore - peer dependency, resolved out of the application's own tree\n return (await import(\"sharp\")).default;\n } catch (error) {\n throw new Error(\n `${usedBy} requires the 'sharp' package. Install it with \\`bun add sharp\\`.`,\n { cause: error },\n );\n }\n}\n",
23
+ "import type { FileSink } from \"bun\";\nimport { mkdir, readdir, access } from \"fs/promises\";\n\nasync function exists(path: string): Promise<boolean> {\n try {\n await access(path);\n return true;\n } catch {\n return false;\n }\n}\nimport { RequestContext } from \"../../http/requestContext\";\nimport { projectRoot } from \"../../support/discover\";\nimport type { LogConfig } from \"./config\";\nimport type { LogEntry, LogLevel } from \"./types\";\n\nexport class LogManager {\n static token = \"log\";\n\n writer: FileSink;\n isReady: boolean = false;\n\n private flushTimeout: Timer;\n private fileSize: number = 0;\n private writerSize: number = 0;\n private isCreatingFile: boolean = false;\n private bootPromise: Promise<void> | null = null;\n public currentLogFilePath: string;\n\n /**\n * Computed per read, not once in the constructor: `Server.start` awaits\n * `waitForBoot()` — where `LogServiceProvider.boot()` builds this directory —\n * and only *then* imports the http layer that sets `ROOT_DIR`. A field\n * initializer (or any `process.env.ROOT_DIR` read here) resolves to\n * `undefined/storage/logs` at boot, which is how every `Log.info()` ended up\n * throwing on an undefined writer. `projectRoot()` is the same rule\n * `httpProd` sets `ROOT_DIR` from, a moment later.\n */\n private get logsDirPath(): string {\n return `${projectRoot()}/storage/logs`;\n }\n\n constructor(public config: Required<LogConfig>) {}\n\n /**\n * Idempotent. `LogServiceProvider.boot()` calls this so the storage\n * directory exists before the first request; a lazy first `log()` triggers\n * it too, so the manager still works when it is resolved on its own.\n */\n boot(): Promise<void> {\n if (!this.bootPromise) {\n this.bootPromise = this.createStorage()\n .catch((err) => {\n // A logger that rejects turns every `Log.info()` into the caller's\n // error. Report the storage failure once and carry on without a file\n // sink — `log()` still feeds `onLogCreated`.\n console.error(\"Log storage unavailable, file logging disabled\", err);\n })\n .then(() => {\n this.isReady = true;\n });\n }\n return this.bootPromise;\n }\n\n private async createStorage() {\n const storageDirPath = `${projectRoot()}/storage`;\n if (!(await exists(storageDirPath))) {\n await mkdir(storageDirPath);\n }\n if (!(await exists(this.logsDirPath))) {\n await mkdir(this.logsDirPath);\n }\n await this.newLogFile();\n }\n\n async newLogFile() {\n if (!(await exists(this.logsDirPath))) {\n await mkdir(this.logsDirPath);\n }\n this.isCreatingFile = true;\n if (this.currentLogFilePath) {\n this.writer.flush();\n this.writer.end();\n this.writer = null;\n const file = new File(\n [await Bun.file(this.currentLogFilePath).arrayBuffer()],\n this.currentLogFilePath.split(\"/\").pop(),\n { type: \"text/plain\" },\n );\n this.config.onLogFileClosed(file);\n this.fileSize = 0;\n this.writerSize = 0;\n }\n\n const logFiles = await readdir(this.logsDirPath);\n\n const lastLogFile = logFiles.sort().reverse()[0];\n\n if (lastLogFile) {\n const _file = Bun.file(`${this.logsDirPath}/${lastLogFile}`);\n if (_file.size < this.config.maxFileSize) {\n this.currentLogFilePath = `${this.logsDirPath}/${lastLogFile}`;\n\n this.writer = _file.writer();\n this.writer.write(await _file.text());\n this.writer.write(\"\\n\");\n this.writer.flush();\n this.fileSize = _file.size;\n }\n }\n\n if (!this.writer) {\n const logFileName =\n `${new Date(Date.now()).toISOString()}.log`.replaceAll(\":\", \"-\");\n this.currentLogFilePath = `${this.logsDirPath}/${logFileName}`;\n const file = Bun.file(`${this.logsDirPath}/${logFileName}`);\n this.writer = file.writer();\n this.fileSize = 0;\n this.writerSize = 0;\n }\n this.isCreatingFile = false;\n }\n\n async log(\n level: LogLevel,\n message: string,\n metadata: Record<string, any> = {},\n ) {\n if (!this.isReady) {\n await this.boot();\n }\n\n const reqCtx = RequestContext.getStore();\n let requestMetadata = {};\n if (reqCtx) {\n requestMetadata = {\n url: reqCtx.req.rawRequest.url,\n method: reqCtx.req.rawRequest.method,\n headers: reqCtx.req.rawRequest.headers,\n body: reqCtx.req.rawRequest.body,\n };\n }\n\n const logObject: LogEntry = {\n timestamp: new Date(Date.now()).toISOString(),\n env: process.env.NODE_ENV,\n level,\n message,\n metadata: { ...requestMetadata, ...metadata },\n };\n\n let log = \"\";\n try {\n log = JSON.stringify(logObject);\n } catch (err) {\n console.log(\"Error parsing log object\", err);\n }\n // Broadcast.channel(\"/logs/live\", {}).publish(JSON.stringify(logObject));\n //\n // Contained, because this is an app-supplied hook and every facade method\n // calls `log()` without awaiting it: a hook that throws would otherwise\n // leave a floating `Log.info()` as an unhandled rejection, which is the\n // failure this method exists to not have. A rejected promise from an async\n // hook is the same thing arriving later, so it is caught too — what is not\n // done is *awaiting* it, which would put the app's transport in front of\n // the file write.\n try {\n const handled = this.config.onLogCreated(logObject);\n if (handled instanceof Promise) {\n handled.catch((err) => console.error(\"Error in onLogCreated\", err));\n }\n } catch (err) {\n console.error(\"Error in onLogCreated\", err);\n }\n\n // No writer means `createStorage` failed (or a rotation is mid-flight);\n // either way the entry has already been handed to `onLogCreated`, so drop\n // the file copy rather than throwing at the call site.\n if (!this.writer) {\n return;\n }\n\n this.writerSize += log.length;\n this.fileSize += log.length;\n\n try {\n this.writer.write(log);\n this.writer.write(\"\\n\");\n this.tryFlush();\n } catch (err) {\n console.error(\"Error writing log\", err);\n // Do something\n }\n }\n\n async tryFlush() {\n if (this.fileSize > this.config.maxFileSize) {\n if (!this.isCreatingFile) {\n await this.newLogFile();\n }\n }\n if (this.writerSize > this.config.maxFileSize / 2) {\n await this.writer.flush();\n this.writerSize = 0;\n await this.newLogFile();\n } else {\n clearTimeout(this.flushTimeout);\n this.flushTimeout = setTimeout(async () => {\n await this.writer.flush();\n this.writerSize = 0;\n }, 100);\n }\n }\n}\n",
24
+ "import { LogManager } from \"../services/logging/LogManager\";\nimport { Facade } from \"./Facade\";\n\nexport class Log extends Facade {\n static getFacadeAccessor() {\n return LogManager;\n }\n\n static debug(message: string, metadata?: Record<string, any>) {\n this.getFacadeRoot().log(\"debug\", message, metadata);\n }\n\n static info(message: string, metadata?: Record<string, any>) {\n this.getFacadeRoot().log(\"info\", message, metadata);\n }\n\n static notice(message: string, metadata?: Record<string, any>) {\n this.getFacadeRoot().log(\"notice\", message, metadata);\n }\n\n static warning(message: string, metadata?: Record<string, any>) {\n this.getFacadeRoot().log(\"warning\", message, metadata);\n }\n\n static error(message: string, metadata?: Record<string, any>) {\n this.getFacadeRoot().log(\"error\", message, metadata);\n }\n\n static critical(message: string, metadata?: Record<string, any>) {\n this.getFacadeRoot().log(\"critical\", message, metadata);\n }\n\n static alert(message: string, metadata?: Record<string, any>) {\n this.getFacadeRoot().log(\"alert\", message, metadata);\n }\n\n static emergency(message: string, metadata?: Record<string, any>) {\n this.getFacadeRoot().log(\"emergency\", message, metadata);\n }\n}\n"
22
25
  ],
23
- "mappings": ";uLAEO,AAAM,LAAW,CACf,MAAO,aAEd,WAAW,EAAG,EAChB,CAIO,MAAe,UAA2B,CAAW,CAM5D,CCFO,SAAS,CAAiB,CAAC,EAAwD,CACxF,IAAM,EAAU,IAAI,IACpB,GAAI,CAAC,EACH,OAAO,EAET,QAAW,KAAQ,EAAO,MAAM,GAAG,EAAG,CACpC,IAAM,EAAK,EAAK,QAAQ,GAAG,EAC3B,GAAI,IAAO,GAAI,SACf,IAAM,EAAO,EAAK,MAAM,EAAG,CAAE,EAAE,KAAK,EACpC,GAAI,CAAC,EAAM,SACX,EAAQ,IAAI,EAAM,EAAK,MAAM,EAAK,CAAC,EAAE,KAAK,CAAC,EAE7C,OAAO,EAGF,SAAS,EAAU,CAAC,EAAmC,CAC5D,OAAO,EAAkB,EAAI,QAAQ,IAAI,QAAQ,CAAC,ECTpD,SAAS,CAAY,CAAC,EAA4B,CAGhD,GAAI,CAAC,QAAQ,KAAK,CAAG,EACnB,OAAO,KAET,IAAM,EAAQ,OAAO,CAAG,EACxB,OAAO,OAAO,cAAc,CAAK,EAAI,EAAQ,KAcxC,SAAS,CAAgB,CAC9B,EACkB,CAClB,GAAI,CAAC,EACH,OAAO,KAGT,IAAM,EAAU,EAAO,KAAK,EAC5B,GAAI,CAAC,WAAW,KAAK,CAAO,EAC1B,OAAO,KAUT,IAAM,EAPQ,EACX,MAAM,CAAe,EAC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OAAO,YAAc,EAC9C,MAAM,KAAK,OAAO,MAAM,EACxB,KAAK,WAAa,EAClB,MAAM,KAAK,WAAW,EAEtB,kBAAa,KAAK,YAAY,EAC9B,KAAK,aAAe,WAAW,SAAY,CACzC,MAAM,KAAK,OAAO,MAAM,EACxB,KAAK,WAAa,GACjB,GAAG,EAGZ,CCnNO,MAAM,WAAY,CAAO,OACvB,kBAAiB,EAAG,CACzB,OAAO,QAGF,MAAK,CAAC,EAAiB,EAAgC,CAC5D,KAAK,cAAc,EAAE,IAAI,QAAS,EAAS,CAAQ,QAG9C,KAAI,CAAC,EAAiB,EAAgC,CAC3D,KAAK,cAAc,EAAE,IAAI,OAAQ,EAAS,CAAQ,QAG7C,OAAM,CAAC,EAAiB,EAAgC,CAC7D,KAAK,cAAc,EAAE,IAAI,SAAU,EAAS,CAAQ,QAG/C,QAAO,CAAC,EAAiB,EAAgC,CAC9D,KAAK,cAAc,EAAE,IAAI,UAAW,EAAS,CAAQ,QAGhD,MAAK,CAAC,EAAiB,EAAgC,CAC5D,KAAK,cAAc,EAAE,IAAI,QAAS,EAAS,CAAQ,QAG9C,SAAQ,CAAC,EAAiB,EAAgC,CAC/D,KAAK,cAAc,EAAE,IAAI,WAAY,EAAS,CAAQ,QAGjD,MAAK,CAAC,EAAiB,EAAgC,CAC5D,KAAK,cAAc,EAAE,IAAI,QAAS,EAAS,CAAQ,QAG9C,UAAS,CAAC,EAAiB,EAAgC,CAChE,KAAK,cAAc,EAAE,IAAI,YAAa,EAAS,CAAQ,EAE3D",
27
+ "debugId": "C06EF1FC40EB69B364756E2164756E21",
25
28
  "names": []
26
29
  }
@@ -2,6 +2,6 @@
2
2
  import{existsSync as $,readdirSync as B}from"fs";import{join as Y,relative as G}from"path";function J(K,Q=[]){let U=[],X=(H)=>{let z=G(K,H).split("\\").join("/");return Q.some((q)=>z===q||z.startsWith(`${q}/`))},V=(H)=>{for(let z of B(H,{withFileTypes:!0}).sort((q,Z)=>q.name<Z.name?-1:q.name>Z.name?1:0)){let q=Y(H,z.name);if(X(q))continue;if(z.isDirectory()){if(z.name.startsWith(".")||z.name==="node_modules")continue;if($(Y(q,"package.json")))continue;V(q);continue}if(!z.name.endsWith(".ts")&&!z.name.endsWith(".tsx"))continue;if(z.name.endsWith(".d.ts"))continue;if(/\.(test|test-d|spec|bench)\.tsx?$/.test(z.name))continue;U.push(q)}};if(!$(K))return U;return V(K),U}class A extends Error{constructor(K,Q){super(K,Q);this.name="DiscoveryError"}}async function W(K,Q,U=[],X){let V=new Set;for(let H of J(K,U)){let z;try{z=await import(H)}catch(q){throw new A(`${H} could not be imported, so the classes in it could not be discovered:
3
3
  ${q.message}
4
4
  List the classes explicitly in the config slice for this directory to skip the walk.`,{cause:q})}for(let q of Object.values(z)){if(typeof q==="function"&&q!==Q&&Object.prototype.isPrototypeOf.call(Q,q)){V.add(q);continue}X?.(q,H)}}return[...V]}function F(){return Y(process.cwd(),process.env.GEMI_PROJECT_DIR??"")}
5
- export{J as Ag,A as Bg,W as Cg,F as Dg};
5
+ export{J as Bg,A as Cg,W as Dg,F as Eg};
6
6
 
7
- //# debugId=A2DFB742558EECAB64756E2164756E21
7
+ //# debugId=9E2441CB432A804E64756E2164756E21
@@ -5,6 +5,6 @@
5
5
  "import { existsSync, readdirSync } from \"node:fs\";\nimport { join, relative } from \"node:path\";\n\n/**\n * Finding the classes an application declared and never imported — the walk\n * #322 and #323 both end at.\n *\n * ### Why it has to run the files\n *\n * A job that is written and not listed does not fail; it disappears.\n * `QueueManager.run` looks a dispatched name up in the map its config built and\n * drops what is not there, so the dispatch is simply lost. A cron drifts worse:\n * nothing is waiting on a tick, so a job that never fires reports nothing to\n * anyone. What both come down to is that `app/config/queue.ts` naming every\n * `Job` subclass is the *only* thing putting those classes in the module graph —\n * the list and the directory are two spellings of one set, kept in step by hand.\n *\n * The way out of that is to read the directory, and there is no static read that\n * will do: the class does not exist until its module has run. So **every file\n * walked here is imported**, and a file that *does something* when imported does\n * it here — at boot, in production, on every start. `gemi check models` makes\n * the same trade for the same reason and pays it once per CI run; a caller of\n * this pays it once per process.\n *\n * ### What that asks of a caller\n *\n * **Point it at a directory of class declarations, not at `app/`.** The skip\n * rules on `sourceFiles` drop what certainly is not one — tests, benchmarks,\n * `.d.ts`, vendored packages — and nothing else. Widening the guesses is how a\n * discovery pass ends up quietly covering less than the directory holds, which\n * is the same silence in a new place.\n *\n * **Let a broken file stop the boot.** `discoverClasses` rethrows an import\n * failure naming the file rather than dropping it and carrying on, for the same\n * reason: four classes found out of five looks exactly like five out of five.\n *\n * **Leave a way out.** Discovery is what should happen when an app said\n * nothing. An app that lists its classes explicitly must not reach this file at\n * all — that is the escape hatch for a directory holding something this cannot\n * import, and it is the sentence an error from here should point at.\n *\n * ### One more thing worth knowing\n *\n * This imports by absolute path, while the application imports the same files\n * through the `@/app/*` alias. Bun keys its module registry by the *resolved*\n * path, so those two specifiers land on one module: a job already reached from\n * a controller is not evaluated a second time here, and the class object is the\n * same one. `gemi build` leaves that true in production — `packages: \"external\"`\n * keeps the app's own code out of `dist/server/server.mjs` and resolves it from\n * source at runtime, exactly as `gemi dev` does.\n *\n * Nothing here depends on that holding, and deliberately: `QueueManager` and the\n * `Scheduler`'s cross-reload registry are both keyed by name rather than by\n * class identity, so a build that did inline the app's modules would produce a\n * duplicate class object and still register the right job. Worth knowing before\n * writing a registry keyed the other way.\n */\n\n/**\n * The files under `dir` that could declare a class.\n *\n * Everything underneath it, because apps do group classes into folders, minus\n * what cannot be one. Each of these is going to be *imported*, so the exclusions\n * are about what is certainly not source rather than about what is probably not:\n *\n * - **Declaration files.** `.d.ts` has no runtime module behind it.\n * - **Tests, type tests and benchmarks**, by the suffix a runner already\n * recognises.\n * - **Dot-directories and `node_modules`.**\n * - **Any directory holding a `package.json`.** That is a package that happens\n * to live here — a vendored client, a generated SDK — not this app's source,\n * and importing its entry point runs somebody else's module graph. The\n * template has two under `app/models`.\n *\n * `ignore` is the escape hatch for the rest: a path prefix, relative to `dir`,\n * naming a file or a directory of adjacent code that runs something on import.\n * Nothing is ignored by default.\n *\n * The order is the same on every run over the same tree, which matters because\n * the caller is going to import in it: entries are sorted per directory before\n * recursing, and `readdirSync` order is the filesystem's rather than\n * alphabetical — a tree written `A.ts` then `B.ts` reads back `B.ts` first on\n * the machines this was tested on. Sorting per directory rather than sorting the\n * finished list is deliberate: for a tree holding both `a.ts` and `a/b.ts`, this\n * emits `a/b.ts` first, because the directory sorts before the file.\n *\n * A directory that does not exist yields an empty list rather than throwing.\n * \"The app has no jobs yet\" is an ordinary state and not this function's to\n * complain about — but it is indistinguishable from \"the app's source did not\n * ship\", so a caller that boots on the answer owes the reader a word about which\n * one it got.\n */\nexport function sourceFiles(dir: string, ignore: string[] = []): string[] {\n const out: string[] = [];\n\n const ignored = (path: string) => {\n const rel = relative(dir, path).split(\"\\\\\").join(\"/\");\n return ignore.some(\n (pattern) => rel === pattern || rel.startsWith(`${pattern}/`),\n );\n };\n\n const walk = (current: string) => {\n for (const entry of readdirSync(current, { withFileTypes: true }).sort(\n (a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0),\n )) {\n const path = join(current, entry.name);\n if (ignored(path)) continue;\n\n if (entry.isDirectory()) {\n if (entry.name.startsWith(\".\") || entry.name === \"node_modules\")\n continue;\n if (existsSync(join(path, \"package.json\"))) continue;\n walk(path);\n continue;\n }\n\n if (!entry.name.endsWith(\".ts\") && !entry.name.endsWith(\".tsx\")) continue;\n if (entry.name.endsWith(\".d.ts\")) continue;\n if (/\\.(test|test-d|spec|bench)\\.tsx?$/.test(entry.name)) continue;\n\n out.push(path);\n }\n };\n\n if (!existsSync(dir)) return out;\n\n walk(dir);\n return out;\n}\n\n/**\n * A class, as much of one as this file can name. `abstract` so that a base an\n * app never instantiates directly is a legal argument.\n */\ntype ClassLike = abstract new (...args: never[]) => unknown;\n\n/**\n * A file that would not import, reported with the file that would not import.\n *\n * Separate from a bare rethrow because the stack of a failed dynamic import\n * names the module that failed to *resolve*, several frames deep, and says\n * nothing about the walk that asked for it — so the reader learns that some\n * `?raw` specifier is unresolvable without learning that discovery is what\n * imported it, or that listing the classes explicitly is how they get their boot\n * back.\n */\nexport class DiscoveryError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = \"DiscoveryError\";\n }\n}\n\n/**\n * Every exported class under `dir` whose prototype chain reaches `base`.\n *\n * `base` is a parameter rather than an import so that this file names no\n * service and stays cheap to depend on — `bin/check-models.ts` uses the walker\n * above and is bundled into `dist/bin/gemi.js`, which is not somewhere gemi's\n * service layer should end up. It is also what lets a test hand in a base class\n * of its own instead of standing up a project that can resolve `gemi/services`.\n *\n * `base` itself is never returned. A directory whose files import their base\n * from a sibling — the shape an app reaches for when several jobs share a gate —\n * re-exports it as often as not, and a framework that scheduled the abstract\n * base along with its subclasses would be running a job nobody wrote.\n *\n * A class is returned once no matter how many exports name it. A barrel in the\n * directory re-exporting everything beside it is the ordinary case, and it makes\n * every class reachable twice.\n *\n * The order is the walk's, and within a file the module namespace's, which the\n * language sorts by name. So the answer is the same on every run — worth having\n * where the caller is a scheduler and the alternative is a boot order that\n * depends on the filesystem.\n *\n * `onSkipped` is handed every export that did *not* match, with the file it came\n * from. Discovery's characteristic failure is a thing the author wrote and this\n * walk cannot see, and by the time an export has been discarded here the\n * information about why is gone — the caller is left holding \"four classes\"\n * where the directory holds five. A caller that can recognise its own\n * near-misses, as `discoverCommands` recognises a builder chain that was never\n * finished, uses this to say so by name instead.\n *\n * @throws DiscoveryError if a walked file cannot be imported. Not a skip: a file\n * that will not load is a class the caller was going to be told about and now is\n * not, which is the failure discovery exists to remove.\n */\nexport async function discoverClasses<T extends ClassLike>(\n dir: string,\n base: T,\n ignore: string[] = [],\n onSkipped?: (value: unknown, file: string) => void,\n): Promise<T[]> {\n const found = new Set<T>();\n\n for (const path of sourceFiles(dir, ignore)) {\n let module: Record<string, unknown>;\n\n try {\n module = (await import(path)) as Record<string, unknown>;\n } catch (error) {\n throw new DiscoveryError(\n `${path} could not be imported, so the classes in it could not be ` +\n `discovered:\\n ${(error as Error).message}\\n` +\n `List the classes explicitly in the config slice for this directory ` +\n `to skip the walk.`,\n { cause: error },\n );\n }\n\n for (const value of Object.values(module)) {\n if (\n typeof value === \"function\" &&\n value !== base &&\n Object.prototype.isPrototypeOf.call(base, value)\n ) {\n found.add(value as unknown as T);\n continue;\n }\n\n onSkipped?.(value, path);\n }\n }\n\n return [...found];\n}\n\n/**\n * The directory an app's `app/` sits in, as the running process can know it.\n *\n * `ROOT_DIR` is the obvious answer and is not available: `Server.start` awaits\n * `waitForBoot()` — every provider's `register` and `boot` — and only then\n * imports the http layer that sets it. Anything resolving paths during boot is\n * earlier than the variable it would want.\n *\n * What it can use is the same rule `httpProd` computes `ROOT_DIR` with a moment\n * later, which is why that file now calls this instead of repeating it. `gemi\n * dev` and `gemi start` both spawn the server with no `cwd`, so the process\n * inherits the CLI's, and the CLI takes `process.cwd()` for the project root\n * itself — `bun/preload.ts` reads `gemi.config` from it on the same assumption.\n *\n * `httpDev` computes a bare `process.cwd()`, so it and `httpProd` already\n * disagree whenever `GEMI_PROJECT_DIR` is set. Nothing in this repo sets it and\n * `gemi start` ignores it when locating the built entry point, so the two rules\n * are the same rule for every configuration that runs today; the divergence is\n * older than this function and wants its own fix.\n */\nexport function projectRoot(): string {\n return join(process.cwd(), process.env.GEMI_PROJECT_DIR ?? \"\");\n}\n"
6
6
  ],
7
7
  "mappings": ";AAAA,qBAAS,iBAAY,WACrB,eAAS,cAAM,aA2FR,SAAS,CAAW,CAAC,EAAa,EAAmB,CAAC,EAAa,CACxE,IAAM,EAAgB,CAAC,EAEjB,EAAU,CAAC,IAAiB,CAChC,IAAM,EAAM,EAAS,EAAK,CAAI,EAAE,MAAM,IAAI,EAAE,KAAK,GAAG,EACpD,OAAO,EAAO,KACZ,CAAC,IAAY,IAAQ,GAAW,EAAI,WAAW,GAAG,IAAU,CAC9D,GAGI,EAAO,CAAC,IAAoB,CAChC,QAAW,KAAS,EAAY,EA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