@uploadista/core 0.0.2 → 0.0.3

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 (329) hide show
  1. package/.turbo/turbo-build.log +88 -1
  2. package/README.md +6 -20
  3. package/dist/checksum-C5qE-5eg.js +2 -0
  4. package/dist/checksum-C5qE-5eg.js.map +1 -0
  5. package/dist/checksum-wSBuXX84.cjs +1 -0
  6. package/dist/errors/index.cjs +1 -1
  7. package/dist/errors/index.d.cts +2 -2
  8. package/dist/errors/index.d.ts +3 -3
  9. package/dist/errors/index.js +1 -2
  10. package/dist/flow/index.cjs +1 -1
  11. package/dist/flow/index.d.cts +5 -5
  12. package/dist/flow/index.d.ts +6 -24
  13. package/dist/flow/index.js +1 -24
  14. package/dist/flow-B0mMJM5Y.js +2 -0
  15. package/dist/flow-B0mMJM5Y.js.map +1 -0
  16. package/dist/flow-s5bgJsdb.cjs +1 -0
  17. package/dist/index-0xq1cArb.d.cts +4132 -0
  18. package/dist/index-0xq1cArb.d.cts.map +1 -0
  19. package/dist/index-B46hb7yB.d.cts +36 -0
  20. package/dist/index-B46hb7yB.d.cts.map +1 -0
  21. package/dist/{streams/stream-limiter.d.cts → index-C1mxuUxK.d.ts} +3 -3
  22. package/dist/index-C1mxuUxK.d.ts.map +1 -0
  23. package/dist/index-DMJv8Tvo.d.ts +168 -0
  24. package/dist/index-DMJv8Tvo.d.ts.map +1 -0
  25. package/dist/index-GLPiXqj4.d.cts +168 -0
  26. package/dist/index-GLPiXqj4.d.cts.map +1 -0
  27. package/dist/index-YegzC0p1.d.ts +3952 -0
  28. package/dist/index-YegzC0p1.d.ts.map +1 -0
  29. package/dist/index.cjs +1 -1
  30. package/dist/index.d.cts +5 -5
  31. package/dist/index.d.ts +6 -5
  32. package/dist/index.js +1 -5
  33. package/dist/stream-limiter-CTuiXkcq.js +2 -0
  34. package/dist/{stream-limiter-CoWKv39w.js.map → stream-limiter-CTuiXkcq.js.map} +1 -1
  35. package/dist/stream-limiter-DYGG4t9f.cjs +1 -0
  36. package/dist/streams/index.cjs +1 -0
  37. package/dist/streams/index.d.cts +3 -0
  38. package/dist/streams/index.d.ts +3 -0
  39. package/dist/streams/index.js +1 -0
  40. package/dist/streams-BiD_pOPH.cjs +0 -0
  41. package/dist/streams-Bs3GDNKJ.js +1 -0
  42. package/dist/types/index.cjs +1 -1
  43. package/dist/types/index.d.cts +5 -5
  44. package/dist/types/index.d.ts +6 -10
  45. package/dist/types/index.js +1 -9
  46. package/dist/types-Dj9g8ocl.cjs +1 -0
  47. package/dist/types-m26wrG-Z.js +2 -0
  48. package/dist/types-m26wrG-Z.js.map +1 -0
  49. package/dist/upload/index.cjs +1 -1
  50. package/dist/upload/index.d.cts +5 -5
  51. package/dist/upload/index.d.ts +6 -4
  52. package/dist/upload/index.js +1 -3
  53. package/dist/upload-BzU7ifyH.js +2 -0
  54. package/dist/upload-BzU7ifyH.js.map +1 -0
  55. package/dist/upload-DvLp6TXO.cjs +1 -0
  56. package/dist/uploadista-error-CAtkQiAv.d.cts +221 -0
  57. package/dist/uploadista-error-CAtkQiAv.d.cts.map +1 -0
  58. package/dist/{uploadista-error-BVsVxqvz.js → uploadista-error-CjfcFnVa.js} +9 -2
  59. package/dist/uploadista-error-CjfcFnVa.js.map +1 -0
  60. package/dist/uploadista-error-D9SONF9K.d.ts +221 -0
  61. package/dist/uploadista-error-D9SONF9K.d.ts.map +1 -0
  62. package/dist/{uploadista-error-BB-Wdiz9.cjs → uploadista-error-DdTP-Rjx.cjs} +9 -2
  63. package/dist/utils/index.cjs +1 -0
  64. package/dist/utils/index.d.cts +3 -0
  65. package/dist/utils/index.d.ts +3 -0
  66. package/dist/utils/index.js +1 -0
  67. package/dist/utils-BILytQlb.js +2 -0
  68. package/dist/utils-BILytQlb.js.map +1 -0
  69. package/dist/utils-BLsIUd8c.cjs +1 -0
  70. package/package.json +12 -16
  71. package/src/index.ts +2 -0
  72. package/src/streams/index.ts +1 -0
  73. package/src/utils/index.ts +5 -0
  74. package/tsdown.config.ts +2 -10
  75. package/dist/chunk-CUT6urMc.cjs +0 -1
  76. package/dist/debounce-C2SeqcxD.js +0 -2
  77. package/dist/debounce-C2SeqcxD.js.map +0 -1
  78. package/dist/debounce-LZK7yS7Z.cjs +0 -1
  79. package/dist/errors/index.d.ts.map +0 -1
  80. package/dist/errors/uploadista-error.d.ts +0 -209
  81. package/dist/errors/uploadista-error.d.ts.map +0 -1
  82. package/dist/errors/uploadista-error.js +0 -322
  83. package/dist/flow/edge.d.ts +0 -47
  84. package/dist/flow/edge.d.ts.map +0 -1
  85. package/dist/flow/edge.js +0 -40
  86. package/dist/flow/event.d.ts +0 -206
  87. package/dist/flow/event.d.ts.map +0 -1
  88. package/dist/flow/event.js +0 -53
  89. package/dist/flow/flow-server.d.ts +0 -223
  90. package/dist/flow/flow-server.d.ts.map +0 -1
  91. package/dist/flow/flow-server.js +0 -614
  92. package/dist/flow/flow.d.ts +0 -238
  93. package/dist/flow/flow.d.ts.map +0 -1
  94. package/dist/flow/flow.js +0 -629
  95. package/dist/flow/index.d.ts.map +0 -1
  96. package/dist/flow/node.d.ts +0 -136
  97. package/dist/flow/node.d.ts.map +0 -1
  98. package/dist/flow/node.js +0 -153
  99. package/dist/flow/nodes/index.d.ts +0 -8
  100. package/dist/flow/nodes/index.d.ts.map +0 -1
  101. package/dist/flow/nodes/index.js +0 -7
  102. package/dist/flow/nodes/input-node.d.ts +0 -78
  103. package/dist/flow/nodes/input-node.d.ts.map +0 -1
  104. package/dist/flow/nodes/input-node.js +0 -233
  105. package/dist/flow/nodes/storage-node.d.ts +0 -67
  106. package/dist/flow/nodes/storage-node.d.ts.map +0 -1
  107. package/dist/flow/nodes/storage-node.js +0 -94
  108. package/dist/flow/nodes/streaming-input-node.d.ts +0 -69
  109. package/dist/flow/nodes/streaming-input-node.d.ts.map +0 -1
  110. package/dist/flow/nodes/streaming-input-node.js +0 -156
  111. package/dist/flow/nodes/transform-node.d.ts +0 -85
  112. package/dist/flow/nodes/transform-node.d.ts.map +0 -1
  113. package/dist/flow/nodes/transform-node.js +0 -107
  114. package/dist/flow/parallel-scheduler.d.ts +0 -175
  115. package/dist/flow/parallel-scheduler.d.ts.map +0 -1
  116. package/dist/flow/parallel-scheduler.js +0 -193
  117. package/dist/flow/plugins/credential-provider.d.ts +0 -47
  118. package/dist/flow/plugins/credential-provider.d.ts.map +0 -1
  119. package/dist/flow/plugins/credential-provider.js +0 -24
  120. package/dist/flow/plugins/image-ai-plugin.d.ts +0 -61
  121. package/dist/flow/plugins/image-ai-plugin.d.ts.map +0 -1
  122. package/dist/flow/plugins/image-ai-plugin.js +0 -21
  123. package/dist/flow/plugins/image-plugin.d.ts +0 -52
  124. package/dist/flow/plugins/image-plugin.d.ts.map +0 -1
  125. package/dist/flow/plugins/image-plugin.js +0 -22
  126. package/dist/flow/plugins/types/describe-image-node.d.ts +0 -16
  127. package/dist/flow/plugins/types/describe-image-node.d.ts.map +0 -1
  128. package/dist/flow/plugins/types/describe-image-node.js +0 -9
  129. package/dist/flow/plugins/types/index.d.ts +0 -9
  130. package/dist/flow/plugins/types/index.d.ts.map +0 -1
  131. package/dist/flow/plugins/types/index.js +0 -8
  132. package/dist/flow/plugins/types/optimize-node.d.ts +0 -20
  133. package/dist/flow/plugins/types/optimize-node.d.ts.map +0 -1
  134. package/dist/flow/plugins/types/optimize-node.js +0 -11
  135. package/dist/flow/plugins/types/remove-background-node.d.ts +0 -16
  136. package/dist/flow/plugins/types/remove-background-node.d.ts.map +0 -1
  137. package/dist/flow/plugins/types/remove-background-node.js +0 -9
  138. package/dist/flow/plugins/types/resize-node.d.ts +0 -21
  139. package/dist/flow/plugins/types/resize-node.d.ts.map +0 -1
  140. package/dist/flow/plugins/types/resize-node.js +0 -16
  141. package/dist/flow/plugins/zip-plugin.d.ts +0 -62
  142. package/dist/flow/plugins/zip-plugin.d.ts.map +0 -1
  143. package/dist/flow/plugins/zip-plugin.js +0 -21
  144. package/dist/flow/typed-flow.d.ts +0 -90
  145. package/dist/flow/typed-flow.d.ts.map +0 -1
  146. package/dist/flow/typed-flow.js +0 -59
  147. package/dist/flow/types/flow-file.d.ts +0 -45
  148. package/dist/flow/types/flow-file.d.ts.map +0 -1
  149. package/dist/flow/types/flow-file.js +0 -27
  150. package/dist/flow/types/flow-job.d.ts +0 -118
  151. package/dist/flow/types/flow-job.d.ts.map +0 -1
  152. package/dist/flow/types/flow-job.js +0 -11
  153. package/dist/flow/types/flow-types.d.ts +0 -321
  154. package/dist/flow/types/flow-types.d.ts.map +0 -1
  155. package/dist/flow/types/flow-types.js +0 -52
  156. package/dist/flow/types/index.d.ts +0 -4
  157. package/dist/flow/types/index.d.ts.map +0 -1
  158. package/dist/flow/types/index.js +0 -3
  159. package/dist/flow/types/run-args.d.ts +0 -38
  160. package/dist/flow/types/run-args.d.ts.map +0 -1
  161. package/dist/flow/types/run-args.js +0 -30
  162. package/dist/flow/types/type-validator.d.ts +0 -26
  163. package/dist/flow/types/type-validator.d.ts.map +0 -1
  164. package/dist/flow/types/type-validator.js +0 -134
  165. package/dist/flow/utils/resolve-upload-metadata.d.ts +0 -11
  166. package/dist/flow/utils/resolve-upload-metadata.d.ts.map +0 -1
  167. package/dist/flow/utils/resolve-upload-metadata.js +0 -28
  168. package/dist/flow-2zXnEiWL.cjs +0 -1
  169. package/dist/flow-CRaKy7Vj.js +0 -2
  170. package/dist/flow-CRaKy7Vj.js.map +0 -1
  171. package/dist/generate-id-Dm-Vboxq.d.ts +0 -34
  172. package/dist/generate-id-Dm-Vboxq.d.ts.map +0 -1
  173. package/dist/generate-id-LjJRLD6N.d.cts +0 -34
  174. package/dist/generate-id-LjJRLD6N.d.cts.map +0 -1
  175. package/dist/generate-id-xHp_Z7Cl.cjs +0 -1
  176. package/dist/generate-id-yohS1ZDk.js +0 -2
  177. package/dist/generate-id-yohS1ZDk.js.map +0 -1
  178. package/dist/index-BO8GZlbD.d.cts +0 -1040
  179. package/dist/index-BO8GZlbD.d.cts.map +0 -1
  180. package/dist/index-D-CoVpkZ.d.ts +0 -1004
  181. package/dist/index-D-CoVpkZ.d.ts.map +0 -1
  182. package/dist/index.d.ts.map +0 -1
  183. package/dist/logger/logger.cjs +0 -1
  184. package/dist/logger/logger.d.cts +0 -8
  185. package/dist/logger/logger.d.cts.map +0 -1
  186. package/dist/logger/logger.d.ts +0 -5
  187. package/dist/logger/logger.d.ts.map +0 -1
  188. package/dist/logger/logger.js +0 -10
  189. package/dist/logger/logger.js.map +0 -1
  190. package/dist/semaphore-0ZwjVpyF.js +0 -2
  191. package/dist/semaphore-0ZwjVpyF.js.map +0 -1
  192. package/dist/semaphore-BHprIjFI.d.cts +0 -37
  193. package/dist/semaphore-BHprIjFI.d.cts.map +0 -1
  194. package/dist/semaphore-DThupBkc.d.ts +0 -37
  195. package/dist/semaphore-DThupBkc.d.ts.map +0 -1
  196. package/dist/semaphore-DVrONiAV.cjs +0 -1
  197. package/dist/stream-limiter-CoWKv39w.js +0 -2
  198. package/dist/stream-limiter-JgOwmkMa.cjs +0 -1
  199. package/dist/streams/multi-stream.cjs +0 -1
  200. package/dist/streams/multi-stream.d.cts +0 -91
  201. package/dist/streams/multi-stream.d.cts.map +0 -1
  202. package/dist/streams/multi-stream.d.ts +0 -86
  203. package/dist/streams/multi-stream.d.ts.map +0 -1
  204. package/dist/streams/multi-stream.js +0 -149
  205. package/dist/streams/multi-stream.js.map +0 -1
  206. package/dist/streams/stream-limiter.cjs +0 -1
  207. package/dist/streams/stream-limiter.d.cts.map +0 -1
  208. package/dist/streams/stream-limiter.d.ts +0 -27
  209. package/dist/streams/stream-limiter.d.ts.map +0 -1
  210. package/dist/streams/stream-limiter.js +0 -49
  211. package/dist/streams/stream-splitter.cjs +0 -1
  212. package/dist/streams/stream-splitter.d.cts +0 -68
  213. package/dist/streams/stream-splitter.d.cts.map +0 -1
  214. package/dist/streams/stream-splitter.d.ts +0 -51
  215. package/dist/streams/stream-splitter.d.ts.map +0 -1
  216. package/dist/streams/stream-splitter.js +0 -175
  217. package/dist/streams/stream-splitter.js.map +0 -1
  218. package/dist/types/data-store-registry.d.ts +0 -13
  219. package/dist/types/data-store-registry.d.ts.map +0 -1
  220. package/dist/types/data-store-registry.js +0 -4
  221. package/dist/types/data-store.d.ts +0 -316
  222. package/dist/types/data-store.d.ts.map +0 -1
  223. package/dist/types/data-store.js +0 -157
  224. package/dist/types/event-broadcaster.d.ts +0 -28
  225. package/dist/types/event-broadcaster.d.ts.map +0 -1
  226. package/dist/types/event-broadcaster.js +0 -6
  227. package/dist/types/event-emitter.d.ts +0 -378
  228. package/dist/types/event-emitter.d.ts.map +0 -1
  229. package/dist/types/event-emitter.js +0 -223
  230. package/dist/types/index.d.ts.map +0 -1
  231. package/dist/types/input-file.d.ts +0 -104
  232. package/dist/types/input-file.d.ts.map +0 -1
  233. package/dist/types/input-file.js +0 -27
  234. package/dist/types/kv-store.d.ts +0 -281
  235. package/dist/types/kv-store.d.ts.map +0 -1
  236. package/dist/types/kv-store.js +0 -234
  237. package/dist/types/middleware.d.ts +0 -17
  238. package/dist/types/middleware.d.ts.map +0 -1
  239. package/dist/types/middleware.js +0 -21
  240. package/dist/types/upload-event.d.ts +0 -105
  241. package/dist/types/upload-event.d.ts.map +0 -1
  242. package/dist/types/upload-event.js +0 -71
  243. package/dist/types/upload-file.d.ts +0 -136
  244. package/dist/types/upload-file.d.ts.map +0 -1
  245. package/dist/types/upload-file.js +0 -34
  246. package/dist/types/websocket.d.ts +0 -144
  247. package/dist/types/websocket.d.ts.map +0 -1
  248. package/dist/types/websocket.js +0 -40
  249. package/dist/types-BT-cvi7T.cjs +0 -1
  250. package/dist/types-DhU2j-XF.js +0 -2
  251. package/dist/types-DhU2j-XF.js.map +0 -1
  252. package/dist/upload/convert-to-stream.d.ts +0 -38
  253. package/dist/upload/convert-to-stream.d.ts.map +0 -1
  254. package/dist/upload/convert-to-stream.js +0 -43
  255. package/dist/upload/convert-upload-to-flow-file.d.ts +0 -14
  256. package/dist/upload/convert-upload-to-flow-file.d.ts.map +0 -1
  257. package/dist/upload/convert-upload-to-flow-file.js +0 -21
  258. package/dist/upload/create-upload.d.ts +0 -68
  259. package/dist/upload/create-upload.d.ts.map +0 -1
  260. package/dist/upload/create-upload.js +0 -157
  261. package/dist/upload/index.d.ts.map +0 -1
  262. package/dist/upload/mime.d.ts +0 -24
  263. package/dist/upload/mime.d.ts.map +0 -1
  264. package/dist/upload/mime.js +0 -351
  265. package/dist/upload/upload-chunk.d.ts +0 -58
  266. package/dist/upload/upload-chunk.d.ts.map +0 -1
  267. package/dist/upload/upload-chunk.js +0 -277
  268. package/dist/upload/upload-server.d.ts +0 -221
  269. package/dist/upload/upload-server.d.ts.map +0 -1
  270. package/dist/upload/upload-server.js +0 -181
  271. package/dist/upload/upload-strategy-negotiator.d.ts +0 -148
  272. package/dist/upload/upload-strategy-negotiator.d.ts.map +0 -1
  273. package/dist/upload/upload-strategy-negotiator.js +0 -217
  274. package/dist/upload/upload-url.d.ts +0 -68
  275. package/dist/upload/upload-url.d.ts.map +0 -1
  276. package/dist/upload/upload-url.js +0 -142
  277. package/dist/upload/write-to-store.d.ts +0 -77
  278. package/dist/upload/write-to-store.d.ts.map +0 -1
  279. package/dist/upload/write-to-store.js +0 -147
  280. package/dist/upload-DLuICjpP.cjs +0 -1
  281. package/dist/upload-DaXO34dE.js +0 -2
  282. package/dist/upload-DaXO34dE.js.map +0 -1
  283. package/dist/uploadista-error-BVsVxqvz.js.map +0 -1
  284. package/dist/uploadista-error-CwxYs4EB.d.ts +0 -52
  285. package/dist/uploadista-error-CwxYs4EB.d.ts.map +0 -1
  286. package/dist/uploadista-error-kKlhLRhY.d.cts +0 -52
  287. package/dist/uploadista-error-kKlhLRhY.d.cts.map +0 -1
  288. package/dist/utils/checksum.d.ts +0 -22
  289. package/dist/utils/checksum.d.ts.map +0 -1
  290. package/dist/utils/checksum.js +0 -49
  291. package/dist/utils/debounce.cjs +0 -1
  292. package/dist/utils/debounce.d.cts +0 -38
  293. package/dist/utils/debounce.d.cts.map +0 -1
  294. package/dist/utils/debounce.d.ts +0 -36
  295. package/dist/utils/debounce.d.ts.map +0 -1
  296. package/dist/utils/debounce.js +0 -73
  297. package/dist/utils/generate-id.cjs +0 -1
  298. package/dist/utils/generate-id.d.cts +0 -2
  299. package/dist/utils/generate-id.d.ts +0 -32
  300. package/dist/utils/generate-id.d.ts.map +0 -1
  301. package/dist/utils/generate-id.js +0 -23
  302. package/dist/utils/md5.cjs +0 -1
  303. package/dist/utils/md5.d.cts +0 -73
  304. package/dist/utils/md5.d.cts.map +0 -1
  305. package/dist/utils/md5.d.ts +0 -71
  306. package/dist/utils/md5.d.ts.map +0 -1
  307. package/dist/utils/md5.js +0 -417
  308. package/dist/utils/md5.js.map +0 -1
  309. package/dist/utils/once.cjs +0 -1
  310. package/dist/utils/once.d.cts +0 -25
  311. package/dist/utils/once.d.cts.map +0 -1
  312. package/dist/utils/once.d.ts +0 -21
  313. package/dist/utils/once.d.ts.map +0 -1
  314. package/dist/utils/once.js +0 -54
  315. package/dist/utils/once.js.map +0 -1
  316. package/dist/utils/semaphore.cjs +0 -1
  317. package/dist/utils/semaphore.d.cts +0 -3
  318. package/dist/utils/semaphore.d.ts +0 -78
  319. package/dist/utils/semaphore.d.ts.map +0 -1
  320. package/dist/utils/semaphore.js +0 -134
  321. package/dist/utils/throttle.cjs +0 -1
  322. package/dist/utils/throttle.d.cts +0 -24
  323. package/dist/utils/throttle.d.cts.map +0 -1
  324. package/dist/utils/throttle.d.ts +0 -18
  325. package/dist/utils/throttle.d.ts.map +0 -1
  326. package/dist/utils/throttle.js +0 -20
  327. package/dist/utils/throttle.js.map +0 -1
  328. package/src/logger/logger.ts +0 -14
  329. /package/dist/{errors-CRm1FHHT.cjs → errors-D-K-vxsP.cjs} +0 -0
@@ -0,0 +1,2 @@
1
+ import{n as e}from"./uploadista-error-CjfcFnVa.js";import{T as t,n,u as r,v as i}from"./types-m26wrG-Z.js";import{r as a,t as o}from"./checksum-C5qE-5eg.js";import{t as s}from"./stream-limiter-CTuiXkcq.js";import{Context as c,Effect as l,Layer as u,Metric as d,MetricBoundaries as f,Ref as p,Stream as m}from"effect";function h(e,t,n=0){return e.length<n+t.length?!1:t.every((t,r)=>e[n+r]===t)}function g(e,t,n=0){if(e.length<n+t.length)return!1;for(let r=0;r<t.length;r++)if(e[n+r]!==t.charCodeAt(r))return!1;return!0}const _=(e,t)=>{if(e.length===0)return`application/octet-stream`;if(h(e,[137,80,78,71,13,10,26,10]))return`image/png`;if(h(e,[255,216,255]))return`image/jpeg`;if(g(e,`GIF87a`)||g(e,`GIF89a`))return`image/gif`;if(h(e,[82,73,70,70])&&e.length>=12&&g(e,`WEBP`,8))return`image/webp`;if(e.length>=12&&h(e,[0,0,0],0)&&g(e,`ftyp`,4)&&(g(e,`avif`,8)||g(e,`avis`,8)))return`image/avif`;if(e.length>=12&&g(e,`ftyp`,4)&&(g(e,`heic`,8)||g(e,`heif`,8)||g(e,`mif1`,8)))return`image/heic`;if(h(e,[66,77]))return`image/bmp`;if(h(e,[73,73,42,0])||h(e,[77,77,0,42]))return`image/tiff`;if(h(e,[0,0,1,0]))return`image/x-icon`;if(e.length>=5){let t=new TextDecoder(`utf-8`,{fatal:!1}).decode(e.slice(0,Math.min(1024,e.length)));if(t.includes(`<svg`)||t.includes(`<?xml`)&&t.includes(`<svg`))return`image/svg+xml`}if(e.length>=12&&g(e,`ftyp`,4)){let t=new TextDecoder().decode(e.slice(8,12));if(t.startsWith(`mp4`)||t.startsWith(`M4`)||t.startsWith(`isom`))return`video/mp4`}if(h(e,[26,69,223,163]))return`video/webm`;if(h(e,[82,73,70,70])&&e.length>=12&&g(e,`AVI `,8))return`video/x-msvideo`;if(e.length>=8&&(g(e,`moov`,4)||g(e,`mdat`,4)||g(e,`free`,4)))return`video/quicktime`;if(h(e,[26,69,223,163])&&e.length>=100&&new TextDecoder(`utf-8`,{fatal:!1}).decode(e.slice(0,100)).includes(`matroska`))return`video/x-matroska`;if(h(e,[255,251])||h(e,[255,243])||h(e,[255,242])||g(e,`ID3`))return`audio/mpeg`;if(h(e,[82,73,70,70])&&e.length>=12&&g(e,`WAVE`,8))return`audio/wav`;if(g(e,`fLaC`))return`audio/flac`;if(g(e,`OggS`))return`audio/ogg`;if(e.length>=12&&g(e,`ftyp`,4)&&g(e,`M4A`,8))return`audio/mp4`;if(g(e,`%PDF`))return`application/pdf`;if(h(e,[80,75,3,4])||h(e,[80,75,5,6])||h(e,[80,75,7,8])){if(e.length>=1024){let t=new TextDecoder(`utf-8`,{fatal:!1}).decode(e);if(t.includes(`word/`))return`application/vnd.openxmlformats-officedocument.wordprocessingml.document`;if(t.includes(`xl/`))return`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`;if(t.includes(`ppt/`))return`application/vnd.openxmlformats-officedocument.presentationml.presentation`}return`application/zip`}if(h(e,[82,97,114,33,26,7]))return`application/x-rar-compressed`;if(h(e,[55,122,188,175,39,28]))return`application/x-7z-compressed`;if(h(e,[31,139]))return`application/gzip`;if(e.length>=262&&g(e,`ustar`,257))return`application/x-tar`;if(g(e,`wOFF`))return`font/woff`;if(g(e,`wOF2`))return`font/woff2`;if(h(e,[0,1,0,0,0]))return`font/ttf`;if(g(e,`OTTO`))return`font/otf`;if(e.length>=1){let t=e[0];if(t===123||t===91)try{let t=new TextDecoder(`utf-8`).decode(e.slice(0,Math.min(1024,e.length)));return JSON.parse(t.trim()),`application/json`}catch{}}if(t)switch(t.split(`.`).pop()?.toLowerCase()){case`jpg`:case`jpeg`:return`image/jpeg`;case`png`:return`image/png`;case`gif`:return`image/gif`;case`webp`:return`image/webp`;case`avif`:return`image/avif`;case`heic`:case`heif`:return`image/heic`;case`bmp`:return`image/bmp`;case`tiff`:case`tif`:return`image/tiff`;case`ico`:return`image/x-icon`;case`svg`:return`image/svg+xml`;case`mp4`:case`m4v`:return`video/mp4`;case`webm`:return`video/webm`;case`avi`:return`video/x-msvideo`;case`mov`:return`video/quicktime`;case`mkv`:return`video/x-matroska`;case`mp3`:return`audio/mpeg`;case`wav`:return`audio/wav`;case`flac`:return`audio/flac`;case`ogg`:return`audio/ogg`;case`m4a`:return`audio/mp4`;case`pdf`:return`application/pdf`;case`docx`:return`application/vnd.openxmlformats-officedocument.wordprocessingml.document`;case`xlsx`:return`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`;case`pptx`:return`application/vnd.openxmlformats-officedocument.presentationml.presentation`;case`zip`:return`application/zip`;case`rar`:return`application/x-rar-compressed`;case`7z`:return`application/x-7z-compressed`;case`gz`:case`gzip`:return`application/gzip`;case`tar`:return`application/x-tar`;case`woff`:return`font/woff`;case`woff2`:return`font/woff2`;case`ttf`:return`font/ttf`;case`otf`:return`font/otf`;case`txt`:return`text/plain`;case`json`:return`application/json`;case`xml`:return`application/xml`;case`html`:case`htm`:return`text/html`;case`css`:return`text/css`;case`js`:return`application/javascript`;case`csv`:return`text/csv`;default:return`application/octet-stream`}return`application/octet-stream`};function v(e,t){return e===t?!0:e.split(`/`)[0]===t.split(`/`)[0]}const y=(e,t,{dataStoreService:r,kvStore:i,eventEmitter:a,generateId:o})=>l.gen(function*(){let s=yield*r.getDataStore(e.storageId,t),c=yield*o.generateId(),{size:l,type:u,fileName:d,lastModified:f,metadata:p,flow:m}=e,h={};if(p)try{h=JSON.parse(p)}catch{h={}}let g={...h,type:u,fileName:d??``};f&&(g.lastModified=f.toString());let _={id:c,size:l,metadata:g,offset:0,creationDate:new Date().toISOString(),storage:{id:e.storageId,type:u,path:``,bucket:s.bucket},flow:m},v=yield*s.create(_);return yield*i.set(c,v),yield*a.emit(c,{type:n.UPLOAD_STARTED,data:v,flow:v.flow}),v}).pipe(l.withSpan(`upload-create`,{attributes:{"upload.file_name":e.fileName??`unknown`,"upload.file_size":e.size?.toString()??`0`,"upload.storage_id":e.storageId,"upload.mime_type":e.type,"upload.has_flow":e.flow?`true`:`false`}}),l.tap(e=>l.gen(function*(){if(yield*d.increment(d.counter(`upload_created_total`,{description:`Total number of uploads created`})),e.size){let t=d.histogram(`upload_file_size_bytes`,f.exponential({start:1024,factor:2,count:25}));yield*d.update(t,e.size)}let t=d.gauge(`active_uploads`);yield*d.increment(t)})),l.tap(t=>l.logInfo(`Upload created`).pipe(l.annotateLogs({"upload.id":t.id,"upload.file_name":e.fileName??`unknown`,"upload.file_size":e.size?.toString()??`0`,"upload.storage_id":e.storageId}))),l.tapError(t=>l.gen(function*(){yield*l.logError(`Upload creation failed`).pipe(l.annotateLogs({"upload.file_name":e.fileName??`unknown`,"upload.storage_id":e.storageId,error:String(t)})),yield*d.increment(d.counter(`upload_failed_total`,{description:`Total number of uploads that failed`}))})));function b(t){return m.fromReadableStream(()=>t,t=>new e({code:`UNKNOWN_ERROR`,status:500,body:String(t)}))}function x({data:t,upload:r,dataStore:i,maxFileSize:a,controller:o,eventEmitter:c,uploadProgressInterval:u=200}){return l.gen(function*(){let d=b(t);if(o.signal.aborted)return yield*l.fail(e.fromCode(`ABORTED`));let f=new AbortController,{signal:m}=f,h=()=>{f.abort()};return o.signal.addEventListener(`abort`,h,{once:!0}),yield*l.acquireUseRelease(l.sync(()=>({signal:m,onAbort:h})),({signal:t})=>l.gen(function*(){let e=yield*p.make(0),t=s.limit({maxSize:a})(d);return yield*i.write({stream:t,file_id:r.id,offset:r.offset},{onProgress:t=>{let i=Date.now();p.get(e).pipe(l.flatMap(a=>i-a>=u?l.gen(function*(){yield*p.set(e,i),yield*c.emit(r.id,{type:n.UPLOAD_PROGRESS,data:{id:r.id,progress:t,total:r.size??0},flow:r.flow})}):l.void),l.runPromise).catch(()=>{})}})}).pipe(l.catchAll(t=>t instanceof Error&&t.name===`AbortError`?l.fail(e.fromCode(`ABORTED`)):t instanceof e?l.fail(t):l.fail(e.fromCode(`FILE_WRITE_ERROR`,{cause:t})))),({onAbort:e})=>l.sync(()=>{o.signal.removeEventListener(`abort`,e)}))}).pipe(l.withSpan(`upload-write-to-store`,{attributes:{"upload.id":r.id,"upload.offset":r.offset.toString(),"upload.max_file_size":a.toString(),"upload.file_size":r.size?.toString()??`0`}}),l.tap(e=>l.logDebug(`Data written to store`).pipe(l.annotateLogs({"upload.id":r.id,"write.offset":e.toString(),"write.bytes_written":(e-r.offset).toString()}))),l.tapError(t=>l.logError(`Failed to write to store`).pipe(l.annotateLogs({"upload.id":r.id,"upload.offset":r.offset.toString(),error:t instanceof e?t.code:String(t)}))))}const S=(e,t,r,{dataStoreService:i,kvStore:a,eventEmitter:o})=>l.gen(function*(){let s=yield*a.get(e),c=yield*i.getDataStore(s.storage.id,t);return s.offset=yield*x({dataStore:c,data:r,upload:s,maxFileSize:1e8,controller:new AbortController,uploadProgressInterval:200,eventEmitter:o}),yield*a.set(e,s),yield*o.emit(s.id,{type:n.UPLOAD_PROGRESS,data:{id:s.id,progress:s.offset,total:s.size??0},flow:s.flow}),s.size&&s.offset===s.size&&(yield*C({file:s,dataStore:c,eventEmitter:o})),s}).pipe(l.withSpan(`upload-chunk`,{attributes:{"upload.id":e,"chunk.upload_id":e}}),l.tap(e=>l.gen(function*(){yield*d.increment(d.counter(`chunk_uploaded_total`,{description:`Total number of chunks uploaded`}));let t=e.offset,n=d.histogram(`chunk_size_bytes`,f.linear({start:262144,width:262144,count:20}));if(yield*d.update(n,t),e.size&&e.size>0){let e=t,n=d.gauge(`upload_throughput_bytes_per_second`);yield*d.set(n,e)}})),l.tap(e=>l.logDebug(`Chunk uploaded`).pipe(l.annotateLogs({"upload.id":e.id,"chunk.size":e.offset.toString(),"chunk.progress":e.size&&e.size>0?(e.offset/e.size*100).toFixed(2):`0`,"upload.total_size":e.size?.toString()??`0`}))),l.tapError(t=>l.logError(`Chunk upload failed`).pipe(l.annotateLogs({"upload.id":e,error:String(t)})))),C=({file:t,dataStore:r,eventEmitter:i})=>l.gen(function*(){let a=r.getCapabilities();if(a.maxValidationSize&&t.size&&t.size>a.maxValidationSize){yield*i.emit(t.id,{type:n.UPLOAD_VALIDATION_WARNING,data:{id:t.id,message:`File size (${t.size} bytes) exceeds max validation size (${a.maxValidationSize} bytes). Validation skipped.`},flow:t.flow});return}let s=yield*r.read(t.id);if(t.checksum&&t.checksumAlgorithm){let a=yield*o(s,t.checksumAlgorithm);if(a!==t.checksum)return yield*i.emit(t.id,{type:n.UPLOAD_VALIDATION_FAILED,data:{id:t.id,reason:`checksum_mismatch`,expected:t.checksum,actual:a},flow:t.flow}),yield*r.remove(t.id),yield*e.fromCode(`CHECKSUM_MISMATCH`,{body:`Checksum validation failed. Expected: ${t.checksum}, Got: ${a}`,details:{uploadId:t.id,expected:t.checksum,actual:a,algorithm:t.checksumAlgorithm}}).toEffect();yield*i.emit(t.id,{type:n.UPLOAD_VALIDATION_SUCCESS,data:{id:t.id,validationType:`checksum`,algorithm:t.checksumAlgorithm},flow:t.flow})}if(a.requiresMimeTypeValidation){let a=_(s),o=t.metadata?.type;if(o&&!v(o,a))return yield*i.emit(t.id,{type:n.UPLOAD_VALIDATION_FAILED,data:{id:t.id,reason:`mimetype_mismatch`,expected:o,actual:a},flow:t.flow}),yield*r.remove(t.id),yield*e.fromCode(`MIMETYPE_MISMATCH`,{body:`MIME type validation failed. Expected: ${o}, Detected: ${a}`,details:{uploadId:t.id,expected:o,actual:a}}).toEffect();yield*i.emit(t.id,{type:n.UPLOAD_VALIDATION_SUCCESS,data:{id:t.id,validationType:`mimetype`},flow:t.flow})}}).pipe(l.withSpan(`validate-upload`,{attributes:{"upload.id":t.id,"validation.checksum_provided":t.checksum?`true`:`false`,"validation.mime_required":r.getCapabilities().requiresMimeTypeValidation?`true`:`false`}})),w=t=>l.tryPromise({try:async()=>await fetch(t),catch:t=>e.fromCode(`UNKNOWN_ERROR`,{cause:t})}).pipe(l.withSpan(`upload-fetch-url`,{attributes:{"upload.url":t,"upload.operation":`fetch`}}),l.tap(e=>l.gen(function*(){yield*d.increment(d.counter(`upload_from_url_total`,{description:`Total number of URL-based uploads`})),e.ok&&(yield*d.increment(d.counter(`upload_from_url_success_total`,{description:`Total number of successful URL-based uploads`})))})),l.tap(e=>l.logInfo(`URL fetch completed`).pipe(l.annotateLogs({"upload.url":t,"response.status":e.status.toString(),"response.ok":e.ok.toString(),"response.content_length":e.headers.get(`content-length`)??`unknown`}))),l.tapError(e=>l.gen(function*(){yield*d.increment(d.counter(`upload_from_url_failed_total`,{description:`Total number of failed URL-based uploads`})),yield*l.logError(`URL fetch failed`).pipe(l.annotateLogs({"upload.url":t,error:String(e)}))}))),T=t=>l.tryPromise({try:async()=>await t.arrayBuffer(),catch:t=>e.fromCode(`UNKNOWN_ERROR`,{cause:t})}).pipe(l.withSpan(`upload-convert-to-buffer`,{attributes:{"upload.operation":`arrayBuffer`}}),l.tap(e=>l.logDebug(`Response converted to array buffer`).pipe(l.annotateLogs({"buffer.size":e.byteLength.toString()}))),l.tapError(e=>l.logError(`Failed to convert response to array buffer`).pipe(l.annotateLogs({error:String(e)}))));var E=class extends c.Tag(`UploadServer`)(){};function D(){return l.gen(function*(){let e=yield*r,n=yield*i,o=yield*a,s=yield*t;return{upload:(t,r,i)=>l.gen(function*(){return yield*S((yield*y(t,r,{dataStoreService:s,kvStore:e,eventEmitter:n,generateId:o})).id,r,i,{dataStoreService:s,kvStore:e,eventEmitter:n})}),uploadFromUrl:(t,r,i)=>l.gen(function*(){let a=yield*T(yield*w(i)),c=new ReadableStream({start(e){e.enqueue(new Uint8Array(a)),e.close()}});return yield*S((yield*y({...t,size:a.byteLength},r,{dataStoreService:s,kvStore:e,eventEmitter:n,generateId:o})).id,r,c,{dataStoreService:s,kvStore:e,eventEmitter:n})}),createUpload:(t,r)=>l.gen(function*(){return yield*y(t,r,{dataStoreService:s,kvStore:e,eventEmitter:n,generateId:o})}),uploadChunk:(t,r,i)=>l.gen(function*(){return yield*S(t,r,i,{dataStoreService:s,kvStore:e,eventEmitter:n})}),getUpload:t=>l.gen(function*(){return yield*e.get(t)}),read:(t,n)=>l.gen(function*(){let r=yield*e.get(t);return yield*(yield*s.getDataStore(r.storage.id,n)).read(t)}),delete:(t,n)=>l.gen(function*(){let r=yield*e.get(t);yield*(yield*s.getDataStore(r.storage.id,n)).remove(t),yield*e.delete(t)}),getCapabilities:(e,t)=>l.gen(function*(){return(yield*s.getDataStore(e,t)).getCapabilities()}),subscribeToUploadEvents:(e,t)=>l.gen(function*(){yield*n.subscribe(e,t)}),unsubscribeFromUploadEvents:e=>l.gen(function*(){yield*n.unsubscribe(e)})}})}const O=u.effect(E,D());var k=class{constructor(e,t){this.capabilities=e,this.validateUploadStrategy=t}negotiateStrategy(e){let t=[],n=[],r=`single`,i=e.preferredChunkSize??this.capabilities.optimalChunkSize??1024*1024,a=e.parallelUploads??1;if(e.preferredStrategy&&(this.validateUploadStrategy(e.preferredStrategy)?(r=e.preferredStrategy,t.push(`Using preferred strategy: ${r}`)):n.push(`Preferred strategy '${e.preferredStrategy}' not supported by data store, falling back`)),(!e.preferredStrategy||!this.validateUploadStrategy(e.preferredStrategy))&&(this.capabilities.supportsParallelUploads&&e.fileSize>(e.minChunkSizeForParallel??10*1024*1024)?(r=`parallel`,t.push(`Selected parallel upload for large file (${e.fileSize} bytes)`)):(r=`single`,t.push(this.capabilities.supportsParallelUploads?`Selected single upload for small file (${e.fileSize} bytes)`:`Selected single upload (parallel not supported by data store)`))),this.capabilities.minChunkSize&&i<this.capabilities.minChunkSize&&(n.push(`Chunk size ${i} below minimum ${this.capabilities.minChunkSize}, adjusting`),i=this.capabilities.minChunkSize),this.capabilities.maxChunkSize&&i>this.capabilities.maxChunkSize&&(n.push(`Chunk size ${i} above maximum ${this.capabilities.maxChunkSize}, adjusting`),i=this.capabilities.maxChunkSize),r===`parallel`&&(this.capabilities.maxConcurrentUploads&&a>this.capabilities.maxConcurrentUploads&&(n.push(`Parallel uploads ${a} exceeds maximum ${this.capabilities.maxConcurrentUploads}, adjusting`),a=this.capabilities.maxConcurrentUploads),this.capabilities.maxParts)){let t=Math.ceil(e.fileSize/i);if(t>this.capabilities.maxParts){let r=Math.ceil(e.fileSize/this.capabilities.maxParts);n.push(`Estimated parts ${t} exceeds maximum ${this.capabilities.maxParts}, increasing chunk size`),i=Math.max(i,r)}}return this.validateUploadStrategy(r)||(n.push(`Final strategy validation failed, falling back to single upload`),r=`single`,a=1),t.push(`Data store capabilities: parallel=${this.capabilities.supportsParallelUploads}, concatenation=${this.capabilities.supportsConcatenation}, resumable=${this.capabilities.supportsResumableUploads}`),{strategy:r,chunkSize:i,parallelUploads:r===`parallel`?a:1,reasoning:t,warnings:n}}getDataStoreCapabilities(){return this.capabilities}validateConfiguration(e){let t=[];return e.preferredStrategy&&!this.validateUploadStrategy(e.preferredStrategy)&&t.push(`Preferred strategy '${e.preferredStrategy}' not supported by data store`),e.preferredChunkSize&&(this.capabilities.minChunkSize&&e.preferredChunkSize<this.capabilities.minChunkSize&&t.push(`Chunk size ${e.preferredChunkSize} below data store minimum ${this.capabilities.minChunkSize}`),this.capabilities.maxChunkSize&&e.preferredChunkSize>this.capabilities.maxChunkSize&&t.push(`Chunk size ${e.preferredChunkSize} above data store maximum ${this.capabilities.maxChunkSize}`)),e.parallelUploads&&this.capabilities.maxConcurrentUploads&&e.parallelUploads>this.capabilities.maxConcurrentUploads&&t.push(`Parallel uploads ${e.parallelUploads} exceeds data store maximum ${this.capabilities.maxConcurrentUploads}`),{valid:t.length===0,errors:t}}};export{T as a,_ as c,O as i,E as n,w as o,D as r,v as s,k as t};
2
+ //# sourceMappingURL=upload-BzU7ifyH.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"upload-BzU7ifyH.js","names":["parsedMetadata: Record<string, string>","metadataObject: Record<string, string>","file: UploadFile","onAbort","capabilities: DataStoreCapabilities","validateUploadStrategy: (strategy: UploadStrategy) => boolean","reasoning: string[]","warnings: string[]","strategy: UploadStrategy","errors: string[]"],"sources":["../src/upload/mime.ts","../src/upload/create-upload.ts","../src/upload/convert-to-stream.ts","../src/upload/write-to-store.ts","../src/upload/upload-chunk.ts","../src/upload/upload-url.ts","../src/upload/upload-server.ts","../src/upload/upload-strategy-negotiator.ts"],"sourcesContent":["/**\n * Helper to check if buffer matches a byte pattern at given offset\n */\nfunction checkBytes(\n buffer: Uint8Array,\n pattern: number[],\n offset = 0,\n): boolean {\n if (buffer.length < offset + pattern.length) return false;\n return pattern.every((byte, i) => buffer[offset + i] === byte);\n}\n\n/**\n * Helper to check if buffer matches a string pattern at given offset\n */\nfunction checkString(\n buffer: Uint8Array,\n str: string,\n offset = 0,\n): boolean {\n if (buffer.length < offset + str.length) return false;\n for (let i = 0; i < str.length; i++) {\n if (buffer[offset + i] !== str.charCodeAt(i)) return false;\n }\n return true;\n}\n\n/**\n * Detect MIME type from buffer using magic bytes (file signatures).\n * Supports a wide range of common file types including images, videos, audio, documents, and archives.\n *\n * @param buffer - File content as Uint8Array\n * @param filename - Optional filename for extension-based fallback\n * @returns Detected MIME type or \"application/octet-stream\" if unknown\n */\nexport const detectMimeType = (\n buffer: Uint8Array,\n filename?: string,\n): string => {\n if (buffer.length === 0) {\n return \"application/octet-stream\";\n }\n\n // ===== IMAGES =====\n\n // PNG: 89 50 4E 47 0D 0A 1A 0A\n if (checkBytes(buffer, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) {\n return \"image/png\";\n }\n\n // JPEG: FF D8 FF\n if (checkBytes(buffer, [0xff, 0xd8, 0xff])) {\n return \"image/jpeg\";\n }\n\n // GIF87a or GIF89a\n if (checkString(buffer, \"GIF87a\") || checkString(buffer, \"GIF89a\")) {\n return \"image/gif\";\n }\n\n // WebP: RIFF....WEBP\n if (\n checkBytes(buffer, [0x52, 0x49, 0x46, 0x46]) &&\n buffer.length >= 12 &&\n checkString(buffer, \"WEBP\", 8)\n ) {\n return \"image/webp\";\n }\n\n // AVIF: ....ftypavif or ....ftypavis\n if (\n buffer.length >= 12 &&\n checkBytes(buffer, [0x00, 0x00, 0x00], 0) &&\n checkString(buffer, \"ftyp\", 4) &&\n (checkString(buffer, \"avif\", 8) || checkString(buffer, \"avis\", 8))\n ) {\n return \"image/avif\";\n }\n\n // HEIC/HEIF: ....ftypheic or ....ftypheif or ....ftypmif1\n if (\n buffer.length >= 12 &&\n checkString(buffer, \"ftyp\", 4) &&\n (checkString(buffer, \"heic\", 8) ||\n checkString(buffer, \"heif\", 8) ||\n checkString(buffer, \"mif1\", 8))\n ) {\n return \"image/heic\";\n }\n\n // BMP: 42 4D\n if (checkBytes(buffer, [0x42, 0x4d])) {\n return \"image/bmp\";\n }\n\n // TIFF (little-endian): 49 49 2A 00\n if (checkBytes(buffer, [0x49, 0x49, 0x2a, 0x00])) {\n return \"image/tiff\";\n }\n\n // TIFF (big-endian): 4D 4D 00 2A\n if (checkBytes(buffer, [0x4d, 0x4d, 0x00, 0x2a])) {\n return \"image/tiff\";\n }\n\n // ICO: 00 00 01 00\n if (checkBytes(buffer, [0x00, 0x00, 0x01, 0x00])) {\n return \"image/x-icon\";\n }\n\n // SVG (XML-based, check for <svg or <?xml)\n if (buffer.length >= 5) {\n const text = new TextDecoder(\"utf-8\", { fatal: false }).decode(\n buffer.slice(0, Math.min(1024, buffer.length)),\n );\n if (text.includes(\"<svg\") || (text.includes(\"<?xml\") && text.includes(\"<svg\"))) {\n return \"image/svg+xml\";\n }\n }\n\n // ===== VIDEOS =====\n\n // MP4/M4V/M4A: ....ftyp\n if (buffer.length >= 12 && checkString(buffer, \"ftyp\", 4)) {\n const subtype = new TextDecoder().decode(buffer.slice(8, 12));\n if (\n subtype.startsWith(\"mp4\") ||\n subtype.startsWith(\"M4\") ||\n subtype.startsWith(\"isom\")\n ) {\n return \"video/mp4\";\n }\n }\n\n // WebM: 1A 45 DF A3\n if (checkBytes(buffer, [0x1a, 0x45, 0xdf, 0xa3])) {\n return \"video/webm\";\n }\n\n // AVI: RIFF....AVI\n if (\n checkBytes(buffer, [0x52, 0x49, 0x46, 0x46]) &&\n buffer.length >= 12 &&\n checkString(buffer, \"AVI \", 8)\n ) {\n return \"video/x-msvideo\";\n }\n\n // MOV (QuickTime): ....moov or ....mdat or ....free\n if (\n buffer.length >= 8 &&\n (checkString(buffer, \"moov\", 4) ||\n checkString(buffer, \"mdat\", 4) ||\n checkString(buffer, \"free\", 4))\n ) {\n return \"video/quicktime\";\n }\n\n // MKV: 1A 45 DF A3 (same as WebM but check for Matroska)\n if (\n checkBytes(buffer, [0x1a, 0x45, 0xdf, 0xa3]) &&\n buffer.length >= 100\n ) {\n const text = new TextDecoder(\"utf-8\", { fatal: false }).decode(\n buffer.slice(0, 100),\n );\n if (text.includes(\"matroska\")) {\n return \"video/x-matroska\";\n }\n }\n\n // ===== AUDIO =====\n\n // MP3: FF FB or FF F3 or FF F2 or ID3\n if (\n checkBytes(buffer, [0xff, 0xfb]) ||\n checkBytes(buffer, [0xff, 0xf3]) ||\n checkBytes(buffer, [0xff, 0xf2]) ||\n checkString(buffer, \"ID3\")\n ) {\n return \"audio/mpeg\";\n }\n\n // WAV: RIFF....WAVE\n if (\n checkBytes(buffer, [0x52, 0x49, 0x46, 0x46]) &&\n buffer.length >= 12 &&\n checkString(buffer, \"WAVE\", 8)\n ) {\n return \"audio/wav\";\n }\n\n // FLAC: 66 4C 61 43 (fLaC)\n if (checkString(buffer, \"fLaC\")) {\n return \"audio/flac\";\n }\n\n // OGG: 4F 67 67 53 (OggS)\n if (checkString(buffer, \"OggS\")) {\n return \"audio/ogg\";\n }\n\n // M4A: ....ftypM4A\n if (\n buffer.length >= 12 &&\n checkString(buffer, \"ftyp\", 4) &&\n checkString(buffer, \"M4A\", 8)\n ) {\n return \"audio/mp4\";\n }\n\n // ===== DOCUMENTS =====\n\n // PDF: 25 50 44 46 (%PDF)\n if (checkString(buffer, \"%PDF\")) {\n return \"application/pdf\";\n }\n\n // ===== ARCHIVES =====\n\n // ZIP: 50 4B 03 04 or 50 4B 05 06 (empty archive) or 50 4B 07 08 (spanned archive)\n if (\n checkBytes(buffer, [0x50, 0x4b, 0x03, 0x04]) ||\n checkBytes(buffer, [0x50, 0x4b, 0x05, 0x06]) ||\n checkBytes(buffer, [0x50, 0x4b, 0x07, 0x08])\n ) {\n // Could be ZIP, DOCX, XLSX, PPTX, JAR, APK, etc.\n // Check for Office formats\n if (buffer.length >= 1024) {\n const text = new TextDecoder(\"utf-8\", { fatal: false }).decode(buffer);\n if (text.includes(\"word/\")) return \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\";\n if (text.includes(\"xl/\")) return \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\";\n if (text.includes(\"ppt/\")) return \"application/vnd.openxmlformats-officedocument.presentationml.presentation\";\n }\n return \"application/zip\";\n }\n\n // RAR: 52 61 72 21 1A 07 (Rar!)\n if (checkBytes(buffer, [0x52, 0x61, 0x72, 0x21, 0x1a, 0x07])) {\n return \"application/x-rar-compressed\";\n }\n\n // 7Z: 37 7A BC AF 27 1C\n if (checkBytes(buffer, [0x37, 0x7a, 0xbc, 0xaf, 0x27, 0x1c])) {\n return \"application/x-7z-compressed\";\n }\n\n // GZIP: 1F 8B\n if (checkBytes(buffer, [0x1f, 0x8b])) {\n return \"application/gzip\";\n }\n\n // TAR (ustar): \"ustar\" at offset 257\n if (buffer.length >= 262 && checkString(buffer, \"ustar\", 257)) {\n return \"application/x-tar\";\n }\n\n // ===== FONTS =====\n\n // WOFF: 77 4F 46 46 (wOFF)\n if (checkString(buffer, \"wOFF\")) {\n return \"font/woff\";\n }\n\n // WOFF2: 77 4F 46 32 (wOF2)\n if (checkString(buffer, \"wOF2\")) {\n return \"font/woff2\";\n }\n\n // TTF: 00 01 00 00 00\n if (checkBytes(buffer, [0x00, 0x01, 0x00, 0x00, 0x00])) {\n return \"font/ttf\";\n }\n\n // OTF: 4F 54 54 4F (OTTO)\n if (checkString(buffer, \"OTTO\")) {\n return \"font/otf\";\n }\n\n // ===== TEXT =====\n\n // JSON (basic check for { or [)\n if (buffer.length >= 1) {\n const firstByte = buffer[0];\n if (firstByte === 0x7b || firstByte === 0x5b) {\n // { or [\n try {\n const text = new TextDecoder(\"utf-8\").decode(\n buffer.slice(0, Math.min(1024, buffer.length)),\n );\n JSON.parse(text.trim());\n return \"application/json\";\n } catch {\n // Not valid JSON\n }\n }\n }\n\n // Fallback to extension-based detection\n if (filename) {\n const ext = filename.split(\".\").pop()?.toLowerCase();\n switch (ext) {\n // Images\n case \"jpg\":\n case \"jpeg\":\n return \"image/jpeg\";\n case \"png\":\n return \"image/png\";\n case \"gif\":\n return \"image/gif\";\n case \"webp\":\n return \"image/webp\";\n case \"avif\":\n return \"image/avif\";\n case \"heic\":\n case \"heif\":\n return \"image/heic\";\n case \"bmp\":\n return \"image/bmp\";\n case \"tiff\":\n case \"tif\":\n return \"image/tiff\";\n case \"ico\":\n return \"image/x-icon\";\n case \"svg\":\n return \"image/svg+xml\";\n\n // Videos\n case \"mp4\":\n case \"m4v\":\n return \"video/mp4\";\n case \"webm\":\n return \"video/webm\";\n case \"avi\":\n return \"video/x-msvideo\";\n case \"mov\":\n return \"video/quicktime\";\n case \"mkv\":\n return \"video/x-matroska\";\n\n // Audio\n case \"mp3\":\n return \"audio/mpeg\";\n case \"wav\":\n return \"audio/wav\";\n case \"flac\":\n return \"audio/flac\";\n case \"ogg\":\n return \"audio/ogg\";\n case \"m4a\":\n return \"audio/mp4\";\n\n // Documents\n case \"pdf\":\n return \"application/pdf\";\n case \"docx\":\n return \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\";\n case \"xlsx\":\n return \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\";\n case \"pptx\":\n return \"application/vnd.openxmlformats-officedocument.presentationml.presentation\";\n\n // Archives\n case \"zip\":\n return \"application/zip\";\n case \"rar\":\n return \"application/x-rar-compressed\";\n case \"7z\":\n return \"application/x-7z-compressed\";\n case \"gz\":\n case \"gzip\":\n return \"application/gzip\";\n case \"tar\":\n return \"application/x-tar\";\n\n // Fonts\n case \"woff\":\n return \"font/woff\";\n case \"woff2\":\n return \"font/woff2\";\n case \"ttf\":\n return \"font/ttf\";\n case \"otf\":\n return \"font/otf\";\n\n // Text\n case \"txt\":\n return \"text/plain\";\n case \"json\":\n return \"application/json\";\n case \"xml\":\n return \"application/xml\";\n case \"html\":\n case \"htm\":\n return \"text/html\";\n case \"css\":\n return \"text/css\";\n case \"js\":\n return \"application/javascript\";\n case \"csv\":\n return \"text/csv\";\n\n default:\n return \"application/octet-stream\";\n }\n }\n\n return \"application/octet-stream\";\n};\n\n/**\n * Compare two MIME types with lenient matching.\n * Matches on major type (e.g., \"image/*\") to allow for minor variations.\n *\n * @param declared - MIME type provided by client\n * @param detected - MIME type detected from file content\n * @returns true if MIME types are compatible\n *\n * @example\n * compareMimeTypes(\"image/png\", \"image/apng\") // true\n * compareMimeTypes(\"image/jpeg\", \"image/png\") // true (both images)\n * compareMimeTypes(\"image/png\", \"application/pdf\") // false\n */\nexport function compareMimeTypes(declared: string, detected: string): boolean {\n // Exact match\n if (declared === detected) {\n return true;\n }\n\n // Extract major types (e.g., \"image\" from \"image/png\")\n const declaredMajor = declared.split(\"/\")[0];\n const detectedMajor = detected.split(\"/\")[0];\n\n // Compare major types for lenient matching\n return declaredMajor === detectedMajor;\n}\n","import { Effect, Metric, MetricBoundaries } from \"effect\";\nimport {\n type EventEmitter,\n type InputFile,\n type KvStore,\n type UploadEvent,\n UploadEventType,\n type UploadFile,\n type UploadFileDataStoresShape,\n} from \"../types\";\nimport type { GenerateIdShape } from \"../utils/generate-id\";\n\n/**\n * Creates a new upload and initializes it in the storage system.\n *\n * This function handles the initial upload creation process including:\n * - Generating a unique upload ID\n * - Routing to appropriate data store based on storage ID\n * - Creating the upload record in the data store\n * - Storing upload metadata in KV store\n * - Emitting upload started events\n * - Parsing and validating metadata\n *\n * The function includes comprehensive observability with:\n * - Effect tracing spans for performance monitoring\n * - Metrics tracking for upload creation, file sizes, and success rates\n * - Structured logging for debugging and monitoring\n * - Error handling with proper UploadistaError types\n *\n * @param inputFile - Input file configuration including storage, size, type, etc.\n * @param clientId - Client identifier (null for anonymous uploads)\n * @param dataStoreService - Service for routing to appropriate data stores\n * @param kvStore - KV store for upload metadata persistence\n * @param eventEmitter - Event emitter for upload lifecycle events\n * @param generateId - ID generator for creating unique upload identifiers\n * @returns Effect that yields the created UploadFile\n *\n * @example\n * ```typescript\n * // Create a new upload\n * const inputFile: InputFile = {\n * storageId: \"s3-production\",\n * size: 1024000,\n * type: \"image/jpeg\",\n * fileName: \"photo.jpg\",\n * metadata: JSON.stringify({ category: \"photos\" })\n * };\n *\n * const createEffect = createUpload(\n * inputFile,\n * \"client-123\",\n * {\n * dataStoreService,\n * kvStore,\n * eventEmitter,\n * generateId\n * }\n * );\n *\n * // Run with dependencies\n * const upload = await Effect.runPromise(\n * createEffect.pipe(\n * Effect.provide(dataStoreLayer),\n * Effect.provide(kvStoreLayer),\n * Effect.provide(eventEmitterLayer),\n * Effect.provide(generateIdLayer)\n * )\n * );\n * ```\n */\nexport const createUpload = (\n inputFile: InputFile,\n clientId: string | null,\n {\n dataStoreService,\n kvStore,\n eventEmitter,\n generateId,\n }: {\n dataStoreService: UploadFileDataStoresShape;\n kvStore: KvStore<UploadFile>;\n eventEmitter: EventEmitter<UploadEvent>;\n generateId: GenerateIdShape;\n }\n) =>\n Effect.gen(function* () {\n // Get datastore using Effect\n const dataStore = yield* dataStoreService.getDataStore(\n inputFile.storageId,\n clientId\n );\n\n const id = yield* generateId.generateId();\n const { size, type, fileName, lastModified, metadata, flow } = inputFile;\n\n let parsedMetadata: Record<string, string> = {};\n if (metadata) {\n try {\n parsedMetadata = JSON.parse(metadata) as Record<string, string>;\n } catch {\n parsedMetadata = {};\n }\n }\n\n const metadataObject: Record<string, string> = {\n ...parsedMetadata,\n type,\n fileName: fileName ?? \"\",\n };\n if (lastModified) {\n metadataObject.lastModified = lastModified.toString();\n }\n\n const file: UploadFile = {\n id,\n size,\n metadata: metadataObject,\n offset: 0,\n creationDate: new Date().toISOString(),\n storage: {\n id: inputFile.storageId,\n\n type,\n path: \"\",\n bucket: dataStore.bucket,\n },\n flow,\n };\n\n // Create file using Effect\n const fileCreated = yield* dataStore.create(file);\n\n // Store in KV store\n yield* kvStore.set(id, fileCreated);\n\n // Emit event\n yield* eventEmitter.emit(id, {\n type: UploadEventType.UPLOAD_STARTED,\n data: fileCreated,\n flow: fileCreated.flow,\n });\n\n return fileCreated;\n }).pipe(\n // Add tracing span for the entire create operation\n Effect.withSpan(\"upload-create\", {\n attributes: {\n \"upload.file_name\": inputFile.fileName ?? \"unknown\",\n \"upload.file_size\": inputFile.size?.toString() ?? \"0\",\n \"upload.storage_id\": inputFile.storageId,\n \"upload.mime_type\": inputFile.type,\n \"upload.has_flow\": inputFile.flow ? \"true\" : \"false\",\n },\n }),\n // Track upload creation metrics\n Effect.tap((file) =>\n Effect.gen(function* () {\n // Increment upload created counter\n yield* Metric.increment(\n Metric.counter(\"upload_created_total\", {\n description: \"Total number of uploads created\",\n })\n );\n\n // Record file size\n if (file.size) {\n const fileSizeHistogram = Metric.histogram(\n \"upload_file_size_bytes\",\n MetricBoundaries.exponential({\n start: 1024,\n factor: 2,\n count: 25,\n })\n );\n yield* Metric.update(fileSizeHistogram, file.size);\n }\n\n // Track active uploads gauge\n const activeUploadsGauge = Metric.gauge(\"active_uploads\");\n yield* Metric.increment(activeUploadsGauge);\n })\n ),\n // Add structured logging\n Effect.tap((file) =>\n Effect.logInfo(\"Upload created\").pipe(\n Effect.annotateLogs({\n \"upload.id\": file.id,\n \"upload.file_name\": inputFile.fileName ?? \"unknown\",\n \"upload.file_size\": inputFile.size?.toString() ?? \"0\",\n \"upload.storage_id\": inputFile.storageId,\n })\n )\n ),\n // Handle errors with logging and metrics\n Effect.tapError((error) =>\n Effect.gen(function* () {\n // Log error\n yield* Effect.logError(\"Upload creation failed\").pipe(\n Effect.annotateLogs({\n \"upload.file_name\": inputFile.fileName ?? \"unknown\",\n \"upload.storage_id\": inputFile.storageId,\n error: String(error),\n })\n );\n\n // Track failed upload metric\n yield* Metric.increment(\n Metric.counter(\"upload_failed_total\", {\n description: \"Total number of uploads that failed\",\n })\n );\n })\n )\n );\n","import { Stream } from \"effect\";\nimport { UploadistaError } from \"../errors\";\n\n/**\n * Converts a ReadableStream to an Effect Stream.\n *\n * This utility function wraps a ReadableStream in an Effect Stream, providing\n * proper error handling and integration with the Effect ecosystem. It's used\n * throughout the upload system to convert raw streams into Effect-compatible\n * streams for processing.\n *\n * The function handles:\n * - Stream conversion with proper error mapping\n * - UploadistaError creation for stream errors\n * - Integration with Effect Stream processing\n *\n * @param data - The ReadableStream to convert\n * @returns Effect Stream that can be processed with Effect operations\n *\n * @example\n * ```typescript\n * // Convert a file stream to Effect Stream\n * const fileStream = new ReadableStream(...);\n * const effectStream = convertToStream(fileStream);\n *\n * // Process with Effect operations\n * const processedStream = effectStream.pipe(\n * Stream.map((chunk) => processChunk(chunk)),\n * Stream.filter((chunk) => chunk.length > 0)\n * );\n *\n * // Run the stream\n * await Stream.runForEach(processedStream, (chunk) =>\n * Effect.logInfo(`Processed chunk: ${chunk.length} bytes`)\n * );\n * ```\n */\nexport function convertToStream<T>(data: ReadableStream<T>) {\n return Stream.fromReadableStream(\n () => data,\n (error) =>\n new UploadistaError({\n code: \"UNKNOWN_ERROR\",\n status: 500,\n body: String(error),\n })\n );\n}\n","import { Effect, Ref } from \"effect\";\nimport { UploadistaError } from \"../errors\";\nimport { StreamLimiterEffect } from \"../streams/stream-limiter\";\nimport type { DataStore, UploadEvent, UploadFile } from \"../types\";\nimport { type EventEmitter, UploadEventType } from \"../types\";\nimport { convertToStream } from \"./convert-to-stream\";\n\n/**\n * Configuration options for writing data to a data store.\n *\n * @property data - The stream of data to write\n * @property upload - Upload file metadata\n * @property dataStore - Target data store for writing\n * @property maxFileSize - Maximum allowed file size in bytes\n * @property controller - AbortController for cancellation\n * @property eventEmitter - Event emitter for progress tracking\n * @property uploadProgressInterval - Progress emission interval in milliseconds (default: 200)\n */\ntype WriteToStoreOptions = {\n data: ReadableStream<Uint8Array>;\n upload: UploadFile;\n dataStore: DataStore<UploadFile>;\n maxFileSize: number;\n controller: AbortController;\n eventEmitter: EventEmitter<UploadEvent>;\n uploadProgressInterval?: number;\n};\n\n/**\n * Writes data stream to a data store with progress tracking and size limits.\n *\n * This function handles the core data writing logic including:\n * - Stream conversion and processing\n * - File size validation and limiting\n * - Progress tracking with throttled events\n * - Abort signal handling for cancellation\n * - Error handling and cleanup\n *\n * The function includes comprehensive observability with:\n * - Effect tracing spans for performance monitoring\n * - Structured logging for debugging and monitoring\n * - Progress event emission with throttling\n * - Error handling with proper UploadistaError types\n *\n * @param data - The stream of data to write to storage\n * @param upload - Upload file metadata containing ID, offset, etc.\n * @param dataStore - Target data store for writing the data\n * @param maxFileSize - Maximum allowed file size in bytes\n * @param controller - AbortController for handling cancellation\n * @param eventEmitter - Event emitter for progress tracking\n * @param uploadProgressInterval - Progress emission interval in milliseconds (default: 200)\n * @returns Effect that yields the number of bytes written\n *\n * @example\n * ```typescript\n * // Write data to store with progress tracking\n * const writeEffect = writeToStore({\n * data: fileStream,\n * upload: uploadMetadata,\n * dataStore: s3DataStore,\n * maxFileSize: 100_000_000, // 100MB\n * controller: abortController,\n * eventEmitter: progressEmitter,\n * uploadProgressInterval: 500 // Emit progress every 500ms\n * });\n *\n * // Run with error handling\n * const bytesWritten = await Effect.runPromise(\n * writeEffect.pipe(\n * Effect.catchAll((error) =>\n * Effect.logError(\"Failed to write to store\").pipe(\n * Effect.andThen(Effect.fail(error))\n * )\n * )\n * )\n * );\n * ```\n */\nexport function writeToStore({\n data,\n upload,\n dataStore,\n maxFileSize,\n controller,\n eventEmitter,\n uploadProgressInterval = 200,\n}: WriteToStoreOptions) {\n return Effect.gen(function* () {\n const stream = convertToStream(data);\n // Check if already aborted\n if (controller.signal.aborted) {\n return yield* Effect.fail(UploadistaError.fromCode(\"ABORTED\"));\n }\n\n // Create an AbortController to manage the stream pipeline\n const abortController = new AbortController();\n const { signal } = abortController;\n\n // Set up abort handling\n const onAbort = () => {\n // stream.cancel();\n abortController.abort();\n };\n\n controller.signal.addEventListener(\"abort\", onAbort, { once: true });\n\n return yield* Effect.acquireUseRelease(\n Effect.sync(() => ({ signal, onAbort })),\n ({ signal: _signal }) =>\n Effect.gen(function* () {\n // Create a ref to track the last progress emission time for throttling\n const lastEmitTime = yield* Ref.make(0);\n\n // Create the stream limiter\n const limiter = StreamLimiterEffect.limit({\n maxSize: maxFileSize,\n });\n\n // Pipe the data through the limiter\n const limitedStream = limiter(stream);\n\n // Write to the data store with progress tracking\n const offset = yield* dataStore.write(\n {\n stream: limitedStream,\n file_id: upload.id,\n offset: upload.offset,\n },\n {\n onProgress: (newOffset: number) => {\n // Simple throttling using timestamp check\n const now = Date.now();\n Ref.get(lastEmitTime)\n .pipe(\n Effect.flatMap((lastTime) => {\n if (now - lastTime >= uploadProgressInterval) {\n return Effect.gen(function* () {\n yield* Ref.set(lastEmitTime, now);\n yield* eventEmitter.emit(upload.id, {\n type: UploadEventType.UPLOAD_PROGRESS,\n data: {\n id: upload.id,\n progress: newOffset,\n total: upload.size ?? 0,\n },\n flow: upload.flow,\n });\n });\n }\n return Effect.void;\n }),\n Effect.runPromise\n )\n .catch(() => {\n // Ignore errors during progress emission\n });\n },\n }\n );\n\n return offset;\n }).pipe(\n Effect.catchAll((error) => {\n if (error instanceof Error && error.name === \"AbortError\") {\n return Effect.fail(UploadistaError.fromCode(\"ABORTED\"));\n }\n if (error instanceof UploadistaError) {\n return Effect.fail(error);\n }\n return Effect.fail(\n UploadistaError.fromCode(\"FILE_WRITE_ERROR\", { cause: error })\n );\n })\n ),\n ({ onAbort }) =>\n Effect.sync(() => {\n controller.signal.removeEventListener(\"abort\", onAbort);\n })\n );\n }).pipe(\n // Add tracing span for write operation\n Effect.withSpan(\"upload-write-to-store\", {\n attributes: {\n \"upload.id\": upload.id,\n \"upload.offset\": upload.offset.toString(),\n \"upload.max_file_size\": maxFileSize.toString(),\n \"upload.file_size\": upload.size?.toString() ?? \"0\",\n },\n }),\n // Add structured logging for write operation\n Effect.tap((offset) =>\n Effect.logDebug(\"Data written to store\").pipe(\n Effect.annotateLogs({\n \"upload.id\": upload.id,\n \"write.offset\": offset.toString(),\n \"write.bytes_written\": (offset - upload.offset).toString(),\n })\n )\n ),\n // Handle errors with logging\n Effect.tapError((error) =>\n Effect.logError(\"Failed to write to store\").pipe(\n Effect.annotateLogs({\n \"upload.id\": upload.id,\n \"upload.offset\": upload.offset.toString(),\n error: error instanceof UploadistaError ? error.code : String(error),\n })\n )\n )\n );\n}\n","import { Effect, Metric, MetricBoundaries } from \"effect\";\nimport { UploadistaError } from \"../errors/uploadista-error\";\nimport {\n type DataStore,\n type EventEmitter,\n type KvStore,\n type UploadEvent,\n UploadEventType,\n type UploadFile,\n type UploadFileDataStoresShape,\n} from \"../types\";\nimport { computeChecksum } from \"../utils/checksum\";\nimport { compareMimeTypes, detectMimeType } from \"./mime\";\nimport { writeToStore } from \"./write-to-store\";\n\n/**\n * Uploads a chunk of data for an existing upload.\n *\n * This function handles the core chunk upload logic including:\n * - Retrieving upload metadata from KV store\n * - Routing to appropriate data store based on storage ID\n * - Writing chunk data to storage with progress tracking\n * - Updating upload offset and metadata\n * - Emitting progress events\n * - Validating upload completion (checksum, MIME type)\n *\n * The function includes comprehensive observability with:\n * - Effect tracing spans for performance monitoring\n * - Metrics tracking for chunk size, throughput, and success rates\n * - Structured logging for debugging and monitoring\n * - Error handling with proper UploadistaError types\n *\n * @param uploadId - Unique identifier for the upload\n * @param clientId - Client identifier (null for anonymous uploads)\n * @param chunk - ReadableStream containing the chunk data to upload\n * @param dataStoreService - Service for routing to appropriate data stores\n * @param kvStore - KV store for upload metadata persistence\n * @param eventEmitter - Event emitter for progress and validation events\n * @returns Effect that yields the updated UploadFile with new offset\n *\n * @example\n * ```typescript\n * // Upload a chunk for an existing upload\n * const uploadChunkEffect = uploadChunk(\n * \"upload-123\",\n * \"client-456\",\n * chunkStream,\n * {\n * dataStoreService,\n * kvStore,\n * eventEmitter\n * }\n * );\n *\n * // Run with dependencies\n * const result = await Effect.runPromise(\n * uploadChunkEffect.pipe(\n * Effect.provide(dataStoreLayer),\n * Effect.provide(kvStoreLayer),\n * Effect.provide(eventEmitterLayer)\n * )\n * );\n * ```\n */\nexport const uploadChunk = (\n uploadId: string,\n clientId: string | null,\n chunk: ReadableStream,\n {\n dataStoreService,\n kvStore,\n eventEmitter,\n }: {\n dataStoreService: UploadFileDataStoresShape;\n kvStore: KvStore<UploadFile>;\n eventEmitter: EventEmitter<UploadEvent>;\n }\n) =>\n Effect.gen(function* () {\n // Get file from KV store\n const file = yield* kvStore.get(uploadId);\n\n // Get datastore\n const dataStore = yield* dataStoreService.getDataStore(\n file.storage.id,\n clientId\n );\n\n // Note: AbortController could be used for cancellation if needed\n\n // Write to store using writeToStore Effect\n const controller = new AbortController();\n\n const chunkSize = yield* writeToStore({\n dataStore,\n data: chunk,\n upload: file,\n maxFileSize: 100_000_000,\n controller,\n uploadProgressInterval: 200,\n eventEmitter,\n });\n\n file.offset = chunkSize;\n\n // Update KV store\n yield* kvStore.set(uploadId, file);\n\n // Emit progress event\n yield* eventEmitter.emit(file.id, {\n type: UploadEventType.UPLOAD_PROGRESS,\n data: {\n id: file.id,\n progress: file.offset,\n total: file.size ?? 0,\n },\n flow: file.flow,\n });\n\n // Check if upload is complete and run validation\n if (file.size && file.offset === file.size) {\n yield* validateUpload({\n file,\n dataStore,\n eventEmitter,\n });\n }\n\n return file;\n }).pipe(\n // Add tracing span for chunk upload\n Effect.withSpan(\"upload-chunk\", {\n attributes: {\n \"upload.id\": uploadId,\n \"chunk.upload_id\": uploadId,\n },\n }),\n // Track chunk upload metrics\n Effect.tap((file) =>\n Effect.gen(function* () {\n // Increment chunk uploaded counter\n yield* Metric.increment(\n Metric.counter(\"chunk_uploaded_total\", {\n description: \"Total number of chunks uploaded\",\n })\n );\n\n // Record chunk size\n const chunkSize = file.offset;\n const chunkSizeHistogram = Metric.histogram(\n \"chunk_size_bytes\",\n MetricBoundaries.linear({\n start: 262_144,\n width: 262_144,\n count: 20,\n })\n );\n yield* Metric.update(chunkSizeHistogram, chunkSize);\n\n // Update throughput gauge\n if (file.size && file.size > 0) {\n const throughput = chunkSize; // bytes processed\n const throughputGauge = Metric.gauge(\n \"upload_throughput_bytes_per_second\"\n );\n yield* Metric.set(throughputGauge, throughput);\n }\n })\n ),\n // Add structured logging for chunk progress\n Effect.tap((file) =>\n Effect.logDebug(\"Chunk uploaded\").pipe(\n Effect.annotateLogs({\n \"upload.id\": file.id,\n \"chunk.size\": file.offset.toString(),\n \"chunk.progress\":\n file.size && file.size > 0\n ? ((file.offset / file.size) * 100).toFixed(2)\n : \"0\",\n \"upload.total_size\": file.size?.toString() ?? \"0\",\n })\n )\n ),\n // Handle errors with logging\n Effect.tapError((error) =>\n Effect.logError(\"Chunk upload failed\").pipe(\n Effect.annotateLogs({\n \"upload.id\": uploadId,\n error: String(error),\n })\n )\n )\n );\n\n/**\n * Validates an upload after completion.\n *\n * Performs comprehensive validation including:\n * - Checksum validation (if provided) using the specified algorithm\n * - MIME type validation (if required by data store capabilities)\n * - File size validation against data store limits\n *\n * Validation results are emitted as events and failures result in:\n * - Cleanup of uploaded data from storage\n * - Removal of metadata from KV store\n * - Appropriate error responses\n *\n * The function respects data store capabilities for validation limits\n * and provides detailed error information for debugging.\n *\n * @param file - The upload file to validate\n * @param dataStore - Data store containing the uploaded file\n * @param eventEmitter - Event emitter for validation events\n * @returns Effect that completes validation or fails with UploadistaError\n *\n * @example\n * ```typescript\n * // Validate upload after completion\n * const validationEffect = validateUpload({\n * file: completedUpload,\n * dataStore: s3DataStore,\n * eventEmitter: progressEmitter\n * });\n *\n * // Run validation\n * await Effect.runPromise(validationEffect);\n * ```\n */\nconst validateUpload = ({\n file,\n dataStore,\n eventEmitter,\n}: {\n file: UploadFile;\n dataStore: DataStore<UploadFile>;\n eventEmitter: EventEmitter<UploadEvent>;\n}): Effect.Effect<void, UploadistaError, never> =>\n Effect.gen(function* () {\n const capabilities = dataStore.getCapabilities();\n\n // Check if file exceeds max validation size\n if (\n capabilities.maxValidationSize &&\n file.size &&\n file.size > capabilities.maxValidationSize\n ) {\n yield* eventEmitter.emit(file.id, {\n type: UploadEventType.UPLOAD_VALIDATION_WARNING,\n data: {\n id: file.id,\n message: `File size (${file.size} bytes) exceeds max validation size (${capabilities.maxValidationSize} bytes). Validation skipped.`,\n },\n flow: file.flow,\n });\n return;\n }\n\n // Read file from datastore for validation\n const fileBytes = yield* dataStore.read(file.id);\n\n // Validate checksum if provided\n if (file.checksum && file.checksumAlgorithm) {\n const computedChecksum = yield* computeChecksum(\n fileBytes,\n file.checksumAlgorithm\n );\n\n if (computedChecksum !== file.checksum) {\n // Emit validation failure event\n yield* eventEmitter.emit(file.id, {\n type: UploadEventType.UPLOAD_VALIDATION_FAILED,\n data: {\n id: file.id,\n reason: \"checksum_mismatch\",\n expected: file.checksum,\n actual: computedChecksum,\n },\n flow: file.flow,\n });\n\n // Clean up file and remove from KV store\n yield* dataStore.remove(file.id);\n\n // Fail with checksum mismatch error\n return yield* UploadistaError.fromCode(\"CHECKSUM_MISMATCH\", {\n body: `Checksum validation failed. Expected: ${file.checksum}, Got: ${computedChecksum}`,\n details: {\n uploadId: file.id,\n expected: file.checksum,\n actual: computedChecksum,\n algorithm: file.checksumAlgorithm,\n },\n }).toEffect();\n }\n\n // Emit checksum validation success\n yield* eventEmitter.emit(file.id, {\n type: UploadEventType.UPLOAD_VALIDATION_SUCCESS,\n data: {\n id: file.id,\n validationType: \"checksum\",\n algorithm: file.checksumAlgorithm,\n },\n flow: file.flow,\n });\n }\n\n // Validate MIME type if required by capabilities\n if (capabilities.requiresMimeTypeValidation) {\n const detectedMimeType = detectMimeType(fileBytes);\n const declaredMimeType = file.metadata?.type as string | undefined;\n\n if (\n declaredMimeType &&\n !compareMimeTypes(declaredMimeType, detectedMimeType)\n ) {\n // Emit validation failure event\n yield* eventEmitter.emit(file.id, {\n type: UploadEventType.UPLOAD_VALIDATION_FAILED,\n data: {\n id: file.id,\n reason: \"mimetype_mismatch\",\n expected: declaredMimeType,\n actual: detectedMimeType,\n },\n flow: file.flow,\n });\n\n // Clean up file and remove from KV store\n yield* dataStore.remove(file.id);\n\n // Fail with MIME type mismatch error\n return yield* UploadistaError.fromCode(\"MIMETYPE_MISMATCH\", {\n body: `MIME type validation failed. Expected: ${declaredMimeType}, Detected: ${detectedMimeType}`,\n details: {\n uploadId: file.id,\n expected: declaredMimeType,\n actual: detectedMimeType,\n },\n }).toEffect();\n }\n\n // Emit MIME type validation success\n yield* eventEmitter.emit(file.id, {\n type: UploadEventType.UPLOAD_VALIDATION_SUCCESS,\n data: {\n id: file.id,\n validationType: \"mimetype\",\n },\n flow: file.flow,\n });\n }\n }).pipe(\n Effect.withSpan(\"validate-upload\", {\n attributes: {\n \"upload.id\": file.id,\n \"validation.checksum_provided\": file.checksum ? \"true\" : \"false\",\n \"validation.mime_required\": dataStore.getCapabilities()\n .requiresMimeTypeValidation\n ? \"true\"\n : \"false\",\n },\n })\n );\n","import { Effect, Metric } from \"effect\";\nimport { UploadistaError } from \"../errors\";\n\n/**\n * Fetches a file from a remote URL.\n *\n * This function handles HTTP requests to remote URLs for file uploads,\n * including proper error handling, metrics tracking, and observability.\n *\n * Features:\n * - HTTP request with proper error handling\n * - Effect tracing for performance monitoring\n * - Metrics tracking for URL-based uploads\n * - Structured logging for debugging\n * - Response validation and error reporting\n *\n * @param url - The remote URL to fetch the file from\n * @returns Effect that yields the Response object\n *\n * @example\n * ```typescript\n * // Fetch a file from URL\n * const fetchEffect = fetchFile(\"https://example.com/image.jpg\");\n *\n * // Run with error handling\n * const response = await Effect.runPromise(\n * fetchEffect.pipe(\n * Effect.catchAll((error) =>\n * Effect.logError(\"Failed to fetch file\").pipe(\n * Effect.andThen(Effect.fail(error))\n * )\n * )\n * )\n * );\n * ```\n */\nexport const fetchFile = (url: string) => {\n return Effect.tryPromise({\n try: async () => {\n return await fetch(url);\n },\n catch: (error) => {\n return UploadistaError.fromCode(\"UNKNOWN_ERROR\", {\n cause: error,\n });\n },\n }).pipe(\n // Add tracing span for URL fetch\n Effect.withSpan(\"upload-fetch-url\", {\n attributes: {\n \"upload.url\": url,\n \"upload.operation\": \"fetch\",\n },\n }),\n // Track URL fetch metrics\n Effect.tap((response) =>\n Effect.gen(function* () {\n // Increment URL upload counter\n yield* Metric.increment(\n Metric.counter(\"upload_from_url_total\", {\n description: \"Total number of URL-based uploads\",\n })\n );\n\n // Track success/failure\n if (response.ok) {\n yield* Metric.increment(\n Metric.counter(\"upload_from_url_success_total\", {\n description: \"Total number of successful URL-based uploads\",\n })\n );\n }\n })\n ),\n // Add structured logging\n Effect.tap((response) =>\n Effect.logInfo(\"URL fetch completed\").pipe(\n Effect.annotateLogs({\n \"upload.url\": url,\n \"response.status\": response.status.toString(),\n \"response.ok\": response.ok.toString(),\n \"response.content_length\":\n response.headers.get(\"content-length\") ?? \"unknown\",\n })\n )\n ),\n // Handle errors with logging and metrics\n Effect.tapError((error) =>\n Effect.gen(function* () {\n // Track failed URL upload\n yield* Metric.increment(\n Metric.counter(\"upload_from_url_failed_total\", {\n description: \"Total number of failed URL-based uploads\",\n })\n );\n\n // Log error\n yield* Effect.logError(\"URL fetch failed\").pipe(\n Effect.annotateLogs({\n \"upload.url\": url,\n error: String(error),\n })\n );\n })\n )\n );\n};\n\n/**\n * Converts a Response object to an ArrayBuffer.\n *\n * This function safely converts HTTP response data to binary format\n * for processing and storage, with proper error handling and observability.\n *\n * Features:\n * - Safe conversion from Response to ArrayBuffer\n * - Effect tracing for performance monitoring\n * - Structured logging for debugging\n * - Error handling with proper UploadistaError types\n *\n * @param response - The HTTP Response object to convert\n * @returns Effect that yields the ArrayBuffer data\n *\n * @example\n * ```typescript\n * // Convert response to buffer\n * const bufferEffect = arrayBuffer(response);\n *\n * // Use in upload pipeline\n * const buffer = await Effect.runPromise(\n * bufferEffect.pipe(\n * Effect.tap((buffer) =>\n * Effect.logInfo(`Buffer size: ${buffer.byteLength} bytes`)\n * )\n * )\n * );\n * ```\n */\nexport const arrayBuffer = (response: Response) => {\n return Effect.tryPromise({\n try: async () => {\n return await response.arrayBuffer();\n },\n catch: (error) => {\n return UploadistaError.fromCode(\"UNKNOWN_ERROR\", {\n cause: error,\n });\n },\n }).pipe(\n // Add tracing span for buffer conversion\n Effect.withSpan(\"upload-convert-to-buffer\", {\n attributes: {\n \"upload.operation\": \"arrayBuffer\",\n },\n }),\n // Add structured logging\n Effect.tap((buffer) =>\n Effect.logDebug(\"Response converted to array buffer\").pipe(\n Effect.annotateLogs({\n \"buffer.size\": buffer.byteLength.toString(),\n })\n )\n ),\n // Handle errors with logging\n Effect.tapError((error) =>\n Effect.logError(\"Failed to convert response to array buffer\").pipe(\n Effect.annotateLogs({\n error: String(error),\n })\n )\n )\n );\n};\n","import { Context, Effect, Layer } from \"effect\";\nimport type { UploadistaError } from \"../errors\";\nimport type {\n DataStore,\n DataStoreCapabilities,\n EventEmitter,\n InputFile,\n KvStore,\n Middleware,\n UploadEvent,\n UploadFile,\n WebSocketConnection,\n} from \"../types\";\nimport {\n UploadEventEmitter,\n UploadFileDataStores,\n UploadFileKVStore,\n} from \"../types\";\nimport { GenerateId, type GenerateIdShape } from \"../utils/generate-id\";\nimport { createUpload } from \"./create-upload\";\nimport { uploadChunk } from \"./upload-chunk\";\nimport { arrayBuffer, fetchFile } from \"./upload-url\";\n\n/**\n * Legacy configuration options for UploadServer.\n *\n * @deprecated Use Effect Layers instead of this configuration object.\n * This type is kept for backward compatibility.\n *\n * @property dataStore - DataStore instance or factory function\n * @property kvStore - KV store for upload metadata\n * @property eventEmitter - Event emitter for upload progress\n * @property generateId - Optional ID generator (defaults to UUID)\n * @property middlewares - Optional request middlewares\n * @property withTracing - Enable Effect tracing for debugging\n */\nexport type UploadServerOptions = {\n dataStore:\n | ((storageId: string) => Promise<DataStore<UploadFile>>)\n | DataStore<UploadFile>;\n kvStore: KvStore<UploadFile>;\n eventEmitter: EventEmitter<UploadEvent>;\n generateId?: GenerateIdShape;\n middlewares?: Middleware[];\n withTracing?: boolean;\n};\n\n/**\n * UploadServer service interface.\n *\n * This is the core upload handling service that provides all file upload operations.\n * It manages upload lifecycle, resumable uploads, progress tracking, and storage integration.\n *\n * All operations return Effect types for composable, type-safe error handling.\n *\n * @property createUpload - Initiates a new upload and returns metadata\n * @property uploadChunk - Uploads a chunk of data for an existing upload\n * @property getCapabilities - Returns storage backend capabilities\n * @property upload - Complete upload in one operation (create + upload data)\n * @property uploadFromUrl - Uploads a file from a remote URL\n * @property getUpload - Retrieves upload metadata by ID\n * @property read - Reads the complete uploaded file data\n * @property delete - Deletes an upload and its data\n * @property subscribeToUploadEvents - Subscribes WebSocket to upload progress events\n * @property unsubscribeFromUploadEvents - Unsubscribes from upload events\n *\n * @example\n * ```typescript\n * // Basic upload flow\n * const program = Effect.gen(function* () {\n * const server = yield* UploadServer;\n *\n * // 1. Create upload\n * const inputFile: InputFile = {\n * storageId: \"s3-production\",\n * size: 1024000,\n * type: \"image/jpeg\",\n * fileName: \"photo.jpg\"\n * };\n * const upload = yield* server.createUpload(inputFile, \"client123\");\n *\n * // 2. Upload chunks\n * const chunk = new ReadableStream(...);\n * const updated = yield* server.uploadChunk(upload.id, \"client123\", chunk);\n *\n * // 3. Read the uploaded file\n * const data = yield* server.read(upload.id, \"client123\");\n *\n * return upload;\n * });\n *\n * // Upload with WebSocket progress tracking\n * const uploadWithProgress = Effect.gen(function* () {\n * const server = yield* UploadServer;\n *\n * // Subscribe to progress events\n * yield* server.subscribeToUploadEvents(uploadId, websocket);\n *\n * // Upload (events will be emitted automatically)\n * const result = yield* server.upload(inputFile, clientId, stream);\n *\n * // Unsubscribe when done\n * yield* server.unsubscribeFromUploadEvents(uploadId);\n *\n * return result;\n * });\n *\n * // Upload from URL\n * const urlUpload = Effect.gen(function* () {\n * const server = yield* UploadServer;\n *\n * const inputFile: InputFile = {\n * storageId: \"s3-production\",\n * size: 0, // Unknown initially\n * type: \"image/png\",\n * fileName: \"remote-image.png\"\n * };\n *\n * const upload = yield* server.uploadFromUrl(\n * inputFile,\n * \"client123\",\n * \"https://example.com/image.png\"\n * );\n *\n * return upload;\n * });\n * ```\n */\nexport type UploadServerShape = {\n createUpload: (\n inputFile: InputFile,\n clientId: string | null,\n ) => Effect.Effect<UploadFile, UploadistaError>;\n uploadChunk: (\n uploadId: string,\n clientId: string | null,\n chunk: ReadableStream,\n ) => Effect.Effect<UploadFile, UploadistaError>;\n getCapabilities: (\n storageId: string,\n clientId: string | null,\n ) => Effect.Effect<DataStoreCapabilities, UploadistaError>;\n upload: (\n file: InputFile,\n clientId: string | null,\n stream: ReadableStream,\n ) => Effect.Effect<UploadFile, UploadistaError>;\n uploadFromUrl: (\n inputFile: InputFile,\n clientId: string | null,\n url: string,\n ) => Effect.Effect<UploadFile, UploadistaError>;\n getUpload: (uploadId: string) => Effect.Effect<UploadFile, UploadistaError>;\n read: (\n uploadId: string,\n clientId: string | null,\n ) => Effect.Effect<Uint8Array, UploadistaError>;\n delete: (\n uploadId: string,\n clientId: string | null,\n ) => Effect.Effect<void, UploadistaError>;\n subscribeToUploadEvents: (\n uploadId: string,\n connection: WebSocketConnection,\n ) => Effect.Effect<void, UploadistaError>;\n unsubscribeFromUploadEvents: (\n uploadId: string,\n ) => Effect.Effect<void, UploadistaError>;\n};\n\n/**\n * Effect-TS context tag for the UploadServer service.\n *\n * Use this tag to access the UploadServer in an Effect context.\n * The server must be provided via a Layer or dependency injection.\n *\n * @example\n * ```typescript\n * // Access UploadServer in an Effect\n * const uploadEffect = Effect.gen(function* () {\n * const server = yield* UploadServer;\n * const upload = yield* server.createUpload(inputFile, clientId);\n * return upload;\n * });\n *\n * // Provide UploadServer layer\n * const program = uploadEffect.pipe(\n * Effect.provide(uploadServer),\n * Effect.provide(uploadFileKvStore),\n * Effect.provide(dataStoreLayer),\n * Effect.provide(eventEmitterLayer)\n * );\n * ```\n */\nexport class UploadServer extends Context.Tag(\"UploadServer\")<\n UploadServer,\n UploadServerShape\n>() {}\n\n/**\n * Creates the UploadServer implementation.\n *\n * This function constructs the UploadServer service by composing all required\n * dependencies (KV store, data stores, event emitter, ID generator). It implements\n * all upload operations defined in UploadServerShape.\n *\n * The server automatically handles:\n * - Upload lifecycle management (create, resume, complete)\n * - Progress tracking and event emission\n * - Storage backend routing based on storageId\n * - Error handling with proper UploadistaError types\n *\n * @returns An Effect that yields the UploadServerShape implementation\n *\n * @example\n * ```typescript\n * // Create a custom UploadServer layer\n * const myUploadServer = Layer.effect(\n * UploadServer,\n * createUploadServer()\n * );\n *\n * // Use in a program\n * const program = Effect.gen(function* () {\n * const server = yield* UploadServer;\n * // Use server operations...\n * }).pipe(Effect.provide(myUploadServer));\n * ```\n */\nexport function createUploadServer() {\n return Effect.gen(function* () {\n const kvStore = yield* UploadFileKVStore;\n const eventEmitter = yield* UploadEventEmitter;\n const generateId = yield* GenerateId;\n const dataStoreService = yield* UploadFileDataStores;\n\n return {\n upload: (\n inputFile: InputFile,\n clientId: string | null,\n stream: ReadableStream,\n ) =>\n Effect.gen(function* () {\n const fileCreated = yield* createUpload(inputFile, clientId, {\n dataStoreService,\n kvStore,\n eventEmitter,\n generateId,\n });\n return yield* uploadChunk(fileCreated.id, clientId, stream, {\n dataStoreService,\n kvStore,\n eventEmitter,\n });\n }),\n uploadFromUrl: (\n inputFile: InputFile,\n clientId: string | null,\n url: string,\n ) =>\n Effect.gen(function* () {\n const response = yield* fetchFile(url);\n const buffer = yield* arrayBuffer(response);\n\n // Create a readable stream from the buffer\n const stream = new ReadableStream({\n start(controller) {\n controller.enqueue(new Uint8Array(buffer));\n controller.close();\n },\n });\n\n const fileCreated = yield* createUpload(\n { ...inputFile, size: buffer.byteLength },\n clientId,\n {\n dataStoreService,\n kvStore,\n eventEmitter,\n generateId,\n },\n );\n return yield* uploadChunk(fileCreated.id, clientId, stream, {\n dataStoreService,\n kvStore,\n eventEmitter,\n });\n }),\n createUpload: (inputFile: InputFile, clientId: string | null) =>\n Effect.gen(function* () {\n const fileCreated = yield* createUpload(inputFile, clientId, {\n dataStoreService,\n kvStore,\n eventEmitter,\n generateId,\n });\n return fileCreated;\n }),\n uploadChunk: (\n uploadId: string,\n clientId: string | null,\n chunk: ReadableStream,\n ) =>\n Effect.gen(function* () {\n const file = yield* uploadChunk(uploadId, clientId, chunk, {\n dataStoreService,\n kvStore,\n eventEmitter,\n });\n return file;\n }),\n getUpload: (uploadId: string) =>\n Effect.gen(function* () {\n const file = yield* kvStore.get(uploadId);\n return file;\n }),\n read: (uploadId: string, clientId: string | null) =>\n Effect.gen(function* () {\n const upload = yield* kvStore.get(uploadId);\n const dataStore = yield* dataStoreService.getDataStore(\n upload.storage.id,\n clientId,\n );\n return yield* dataStore.read(uploadId);\n }),\n delete: (uploadId: string, clientId: string | null) =>\n Effect.gen(function* () {\n const upload = yield* kvStore.get(uploadId);\n const dataStore = yield* dataStoreService.getDataStore(\n upload.storage.id,\n clientId,\n );\n yield* dataStore.remove(uploadId);\n yield* kvStore.delete(uploadId);\n return;\n }),\n getCapabilities: (storageId: string, clientId: string | null) =>\n Effect.gen(function* () {\n const dataStore = yield* dataStoreService.getDataStore(\n storageId,\n clientId,\n );\n return dataStore.getCapabilities();\n }),\n subscribeToUploadEvents: (\n uploadId: string,\n connection: WebSocketConnection,\n ) =>\n Effect.gen(function* () {\n yield* eventEmitter.subscribe(uploadId, connection);\n }),\n unsubscribeFromUploadEvents: (uploadId: string) =>\n Effect.gen(function* () {\n yield* eventEmitter.unsubscribe(uploadId);\n }),\n } satisfies UploadServerShape;\n });\n}\n\n/**\n * Pre-built UploadServer Effect Layer.\n *\n * This layer provides a ready-to-use UploadServer implementation that can be\n * composed with other layers to build a complete upload system.\n *\n * Required dependencies:\n * - UploadFileKVStore: For storing upload metadata\n * - UploadFileDataStores: For routing to storage backends\n * - UploadEventEmitter: For progress events\n * - GenerateId: For creating upload IDs\n *\n * @example\n * ```typescript\n * // Compose a complete upload system\n * const fullUploadSystem = Layer.mergeAll(\n * uploadServer,\n * uploadFileKvStore,\n * dataStoreLayer,\n * uploadEventEmitter,\n * generateIdLayer\n * );\n *\n * // Use in application\n * const app = Effect.gen(function* () {\n * const server = yield* UploadServer;\n * // Perform uploads...\n * }).pipe(Effect.provide(fullUploadSystem));\n * ```\n */\nexport const uploadServer = Layer.effect(UploadServer, createUploadServer());\n","import type { DataStoreCapabilities, UploadStrategy } from \"../types\";\n\n/**\n * Configuration options for upload strategy negotiation.\n *\n * @property fileSize - Size of the file to be uploaded in bytes\n * @property preferredStrategy - Preferred upload strategy (single, parallel, resumable)\n * @property preferredChunkSize - Preferred chunk size in bytes\n * @property parallelUploads - Number of parallel upload connections\n * @property minChunkSizeForParallel - Minimum file size to consider parallel uploads\n */\nexport type UploadStrategyOptions = {\n fileSize: number;\n preferredStrategy?: UploadStrategy;\n preferredChunkSize?: number;\n parallelUploads?: number;\n minChunkSizeForParallel?: number;\n};\n\n/**\n * Result of upload strategy negotiation.\n *\n * @property strategy - The negotiated upload strategy\n * @property chunkSize - The negotiated chunk size in bytes\n * @property parallelUploads - The negotiated number of parallel uploads\n * @property reasoning - Array of reasoning strings explaining the decisions\n * @property warnings - Array of warning messages about adjustments made\n */\nexport type NegotiatedStrategy = {\n strategy: UploadStrategy;\n chunkSize: number;\n parallelUploads: number;\n reasoning: string[];\n warnings: string[];\n};\n\n/**\n * Negotiates the optimal upload strategy based on data store capabilities and file characteristics.\n *\n * This class analyzes data store capabilities, file size, and user preferences to determine\n * the best upload strategy (single, parallel, resumable) and optimal parameters like chunk size\n * and parallel connection count.\n *\n * The negotiator considers:\n * - Data store capabilities (parallel uploads, resumable uploads, concatenation)\n * - File size and chunk size constraints\n * - User preferences and requirements\n * - Performance optimization opportunities\n *\n * @example\n * ```typescript\n * // Create negotiator for S3 data store\n * const negotiator = new UploadStrategyNegotiator(\n * s3Capabilities,\n * (strategy) => s3Capabilities.supportsStrategy(strategy)\n * );\n *\n * // Negotiate strategy for large file\n * const result = negotiator.negotiateStrategy({\n * fileSize: 100_000_000, // 100MB\n * preferredStrategy: \"parallel\",\n * preferredChunkSize: 5_000_000, // 5MB chunks\n * parallelUploads: 4\n * });\n *\n * console.log(result.strategy); // \"parallel\"\n * console.log(result.chunkSize); // 5_000_000\n * console.log(result.reasoning); // [\"Using preferred strategy: parallel\", ...]\n * ```\n */\nexport class UploadStrategyNegotiator {\n /**\n * Creates a new upload strategy negotiator.\n *\n * @param capabilities - Data store capabilities and constraints\n * @param validateUploadStrategy - Function to validate if a strategy is supported\n */\n constructor(\n private capabilities: DataStoreCapabilities,\n private validateUploadStrategy: (strategy: UploadStrategy) => boolean\n ) {}\n\n /**\n * Negotiates the optimal upload strategy based on options and data store capabilities.\n *\n * This method analyzes the provided options and data store capabilities to determine\n * the best upload strategy, chunk size, and parallel upload settings. It considers\n * user preferences, file size, and data store constraints to make optimal decisions.\n *\n * The negotiation process:\n * 1. Validates preferred strategy against data store capabilities\n * 2. Automatically selects strategy based on file size and capabilities\n * 3. Adjusts chunk size to fit within data store constraints\n * 4. Validates parallel upload settings\n * 5. Ensures final strategy is supported by the data store\n *\n * @param options - Upload strategy options including file size and preferences\n * @returns Negotiated strategy with reasoning and warnings\n *\n * @example\n * ```typescript\n * const result = negotiator.negotiateStrategy({\n * fileSize: 50_000_000, // 50MB\n * preferredStrategy: \"parallel\",\n * preferredChunkSize: 5_000_000, // 5MB\n * parallelUploads: 3\n * });\n *\n * console.log(result.strategy); // \"parallel\"\n * console.log(result.chunkSize); // 5_000_000\n * console.log(result.parallelUploads); // 3\n * console.log(result.reasoning); // [\"Using preferred strategy: parallel\", ...]\n * console.log(result.warnings); // [] (no warnings)\n * ```\n */\n negotiateStrategy(options: UploadStrategyOptions): NegotiatedStrategy {\n const reasoning: string[] = [];\n const warnings: string[] = [];\n\n let strategy: UploadStrategy = \"single\";\n let chunkSize =\n options.preferredChunkSize ??\n this.capabilities.optimalChunkSize ??\n 1024 * 1024;\n let parallelUploads = options.parallelUploads ?? 1;\n\n // Check if data store supports the preferred strategy\n if (options.preferredStrategy) {\n if (!this.validateUploadStrategy(options.preferredStrategy)) {\n warnings.push(\n `Preferred strategy '${options.preferredStrategy}' not supported by data store, falling back`\n );\n } else {\n strategy = options.preferredStrategy;\n reasoning.push(`Using preferred strategy: ${strategy}`);\n }\n }\n\n // Automatic strategy selection based on capabilities and file size\n if (\n !options.preferredStrategy ||\n !this.validateUploadStrategy(options.preferredStrategy)\n ) {\n if (\n this.capabilities.supportsParallelUploads &&\n options.fileSize > (options.minChunkSizeForParallel ?? 10 * 1024 * 1024)\n ) {\n strategy = \"parallel\";\n reasoning.push(\n `Selected parallel upload for large file (${options.fileSize} bytes)`\n );\n } else {\n strategy = \"single\";\n reasoning.push(\n this.capabilities.supportsParallelUploads\n ? `Selected single upload for small file (${options.fileSize} bytes)`\n : \"Selected single upload (parallel not supported by data store)\"\n );\n }\n }\n\n // Validate and adjust chunk size based on data store constraints\n if (\n this.capabilities.minChunkSize &&\n chunkSize < this.capabilities.minChunkSize\n ) {\n warnings.push(\n `Chunk size ${chunkSize} below minimum ${this.capabilities.minChunkSize}, adjusting`\n );\n chunkSize = this.capabilities.minChunkSize;\n }\n\n if (\n this.capabilities.maxChunkSize &&\n chunkSize > this.capabilities.maxChunkSize\n ) {\n warnings.push(\n `Chunk size ${chunkSize} above maximum ${this.capabilities.maxChunkSize}, adjusting`\n );\n chunkSize = this.capabilities.maxChunkSize;\n }\n\n // Validate parallel upload settings\n if (strategy === \"parallel\") {\n if (\n this.capabilities.maxConcurrentUploads &&\n parallelUploads > this.capabilities.maxConcurrentUploads\n ) {\n warnings.push(\n `Parallel uploads ${parallelUploads} exceeds maximum ${this.capabilities.maxConcurrentUploads}, adjusting`\n );\n parallelUploads = this.capabilities.maxConcurrentUploads;\n }\n\n // Check if file would exceed max parts limit\n if (this.capabilities.maxParts) {\n const estimatedParts = Math.ceil(options.fileSize / chunkSize);\n if (estimatedParts > this.capabilities.maxParts) {\n const minChunkForParts = Math.ceil(\n options.fileSize / this.capabilities.maxParts\n );\n warnings.push(\n `Estimated parts ${estimatedParts} exceeds maximum ${this.capabilities.maxParts}, increasing chunk size`\n );\n chunkSize = Math.max(chunkSize, minChunkForParts);\n }\n }\n }\n\n // Final validation - ensure strategy is still valid after adjustments\n if (!this.validateUploadStrategy(strategy)) {\n warnings.push(\n `Final strategy validation failed, falling back to single upload`\n );\n strategy = \"single\";\n parallelUploads = 1;\n }\n\n // Add capability information to reasoning\n reasoning.push(\n `Data store capabilities: parallel=${this.capabilities.supportsParallelUploads}, concatenation=${this.capabilities.supportsConcatenation}, resumable=${this.capabilities.supportsResumableUploads}`\n );\n\n return {\n strategy,\n chunkSize,\n parallelUploads: strategy === \"parallel\" ? parallelUploads : 1,\n reasoning,\n warnings,\n };\n }\n\n /**\n * Gets the data store capabilities used by this negotiator.\n *\n * @returns The data store capabilities and constraints\n */\n getDataStoreCapabilities(): DataStoreCapabilities {\n return this.capabilities;\n }\n\n /**\n * Validates upload strategy configuration against data store capabilities.\n *\n * This method checks if the provided configuration is valid for the current\n * data store capabilities without performing the actual negotiation. It's\n * useful for pre-validation before attempting to negotiate a strategy.\n *\n * @param options - Upload strategy options to validate\n * @returns Validation result with validity flag and error messages\n *\n * @example\n * ```typescript\n * const validation = negotiator.validateConfiguration({\n * fileSize: 10_000_000,\n * preferredStrategy: \"parallel\",\n * preferredChunkSize: 1_000_000,\n * parallelUploads: 5\n * });\n *\n * if (!validation.valid) {\n * console.log(\"Configuration errors:\", validation.errors);\n * // Handle validation errors\n * }\n * ```\n */\n validateConfiguration(options: UploadStrategyOptions): {\n valid: boolean;\n errors: string[];\n } {\n const errors: string[] = [];\n\n if (\n options.preferredStrategy &&\n !this.validateUploadStrategy(options.preferredStrategy)\n ) {\n errors.push(\n `Preferred strategy '${options.preferredStrategy}' not supported by data store`\n );\n }\n\n if (options.preferredChunkSize) {\n if (\n this.capabilities.minChunkSize &&\n options.preferredChunkSize < this.capabilities.minChunkSize\n ) {\n errors.push(\n `Chunk size ${options.preferredChunkSize} below data store minimum ${this.capabilities.minChunkSize}`\n );\n }\n if (\n this.capabilities.maxChunkSize &&\n options.preferredChunkSize > this.capabilities.maxChunkSize\n ) {\n errors.push(\n `Chunk size ${options.preferredChunkSize} above data store maximum ${this.capabilities.maxChunkSize}`\n );\n }\n }\n\n if (\n options.parallelUploads &&\n this.capabilities.maxConcurrentUploads &&\n options.parallelUploads > this.capabilities.maxConcurrentUploads\n ) {\n errors.push(\n `Parallel uploads ${options.parallelUploads} exceeds data store maximum ${this.capabilities.maxConcurrentUploads}`\n );\n }\n\n return {\n valid: errors.length === 0,\n errors,\n };\n }\n}\n"],"mappings":"6TAGA,SAAS,EACP,EACA,EACA,EAAS,EACA,CAET,OADI,EAAO,OAAS,EAAS,EAAQ,OAAe,GAC7C,EAAQ,OAAO,EAAM,IAAM,EAAO,EAAS,KAAO,EAAK,CAMhE,SAAS,EACP,EACA,EACA,EAAS,EACA,CACT,GAAI,EAAO,OAAS,EAAS,EAAI,OAAQ,MAAO,GAChD,IAAK,IAAI,EAAI,EAAG,EAAI,EAAI,OAAQ,IAC9B,GAAI,EAAO,EAAS,KAAO,EAAI,WAAW,EAAE,CAAE,MAAO,GAEvD,MAAO,GAWT,MAAa,GACX,EACA,IACW,CACX,GAAI,EAAO,SAAW,EACpB,MAAO,2BAMT,GAAI,EAAW,EAAQ,CAAC,IAAM,GAAM,GAAM,GAAM,GAAM,GAAM,GAAM,GAAK,CAAC,CACtE,MAAO,YAIT,GAAI,EAAW,EAAQ,CAAC,IAAM,IAAM,IAAK,CAAC,CACxC,MAAO,aAIT,GAAI,EAAY,EAAQ,SAAS,EAAI,EAAY,EAAQ,SAAS,CAChE,MAAO,YAIT,GACE,EAAW,EAAQ,CAAC,GAAM,GAAM,GAAM,GAAK,CAAC,EAC5C,EAAO,QAAU,IACjB,EAAY,EAAQ,OAAQ,EAAE,CAE9B,MAAO,aAIT,GACE,EAAO,QAAU,IACjB,EAAW,EAAQ,CAAC,EAAM,EAAM,EAAK,CAAE,EAAE,EACzC,EAAY,EAAQ,OAAQ,EAAE,GAC7B,EAAY,EAAQ,OAAQ,EAAE,EAAI,EAAY,EAAQ,OAAQ,EAAE,EAEjE,MAAO,aAIT,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,CACD,EAAY,KAAK,IAAI,EAAW,EAAiB,EAmBvD,OAbK,KAAK,uBAAuB,EAAS,GACxC,EAAS,KACP,kEACD,CACD,EAAW,SACX,EAAkB,GAIpB,EAAU,KACR,qCAAqC,KAAK,aAAa,wBAAwB,kBAAkB,KAAK,aAAa,sBAAsB,cAAc,KAAK,aAAa,2BAC1K,CAEM,CACL,WACA,YACA,gBAAiB,IAAa,WAAa,EAAkB,EAC7D,YACA,WACD,CAQH,0BAAkD,CAChD,OAAO,KAAK,aA4Bd,sBAAsB,EAGpB,CACA,IAAMC,EAAmB,EAAE,CAwC3B,OArCE,EAAQ,mBACR,CAAC,KAAK,uBAAuB,EAAQ,kBAAkB,EAEvD,EAAO,KACL,uBAAuB,EAAQ,kBAAkB,+BAClD,CAGC,EAAQ,qBAER,KAAK,aAAa,cAClB,EAAQ,mBAAqB,KAAK,aAAa,cAE/C,EAAO,KACL,cAAc,EAAQ,mBAAmB,4BAA4B,KAAK,aAAa,eACxF,CAGD,KAAK,aAAa,cAClB,EAAQ,mBAAqB,KAAK,aAAa,cAE/C,EAAO,KACL,cAAc,EAAQ,mBAAmB,4BAA4B,KAAK,aAAa,eACxF,EAKH,EAAQ,iBACR,KAAK,aAAa,sBAClB,EAAQ,gBAAkB,KAAK,aAAa,sBAE5C,EAAO,KACL,oBAAoB,EAAQ,gBAAgB,8BAA8B,KAAK,aAAa,uBAC7F,CAGI,CACL,MAAO,EAAO,SAAW,EACzB,SACD"}
@@ -0,0 +1 @@
1
+ const e=require(`./uploadista-error-DdTP-Rjx.cjs`),t=require(`./types-Dj9g8ocl.cjs`),n=require(`./checksum-wSBuXX84.cjs`),r=require(`./stream-limiter-DYGG4t9f.cjs`);let i=require(`effect`);i=e.a(i);function a(e,t,n=0){return e.length<n+t.length?!1:t.every((t,r)=>e[n+r]===t)}function o(e,t,n=0){if(e.length<n+t.length)return!1;for(let r=0;r<t.length;r++)if(e[n+r]!==t.charCodeAt(r))return!1;return!0}const s=(e,t)=>{if(e.length===0)return`application/octet-stream`;if(a(e,[137,80,78,71,13,10,26,10]))return`image/png`;if(a(e,[255,216,255]))return`image/jpeg`;if(o(e,`GIF87a`)||o(e,`GIF89a`))return`image/gif`;if(a(e,[82,73,70,70])&&e.length>=12&&o(e,`WEBP`,8))return`image/webp`;if(e.length>=12&&a(e,[0,0,0],0)&&o(e,`ftyp`,4)&&(o(e,`avif`,8)||o(e,`avis`,8)))return`image/avif`;if(e.length>=12&&o(e,`ftyp`,4)&&(o(e,`heic`,8)||o(e,`heif`,8)||o(e,`mif1`,8)))return`image/heic`;if(a(e,[66,77]))return`image/bmp`;if(a(e,[73,73,42,0])||a(e,[77,77,0,42]))return`image/tiff`;if(a(e,[0,0,1,0]))return`image/x-icon`;if(e.length>=5){let t=new TextDecoder(`utf-8`,{fatal:!1}).decode(e.slice(0,Math.min(1024,e.length)));if(t.includes(`<svg`)||t.includes(`<?xml`)&&t.includes(`<svg`))return`image/svg+xml`}if(e.length>=12&&o(e,`ftyp`,4)){let t=new TextDecoder().decode(e.slice(8,12));if(t.startsWith(`mp4`)||t.startsWith(`M4`)||t.startsWith(`isom`))return`video/mp4`}if(a(e,[26,69,223,163]))return`video/webm`;if(a(e,[82,73,70,70])&&e.length>=12&&o(e,`AVI `,8))return`video/x-msvideo`;if(e.length>=8&&(o(e,`moov`,4)||o(e,`mdat`,4)||o(e,`free`,4)))return`video/quicktime`;if(a(e,[26,69,223,163])&&e.length>=100&&new TextDecoder(`utf-8`,{fatal:!1}).decode(e.slice(0,100)).includes(`matroska`))return`video/x-matroska`;if(a(e,[255,251])||a(e,[255,243])||a(e,[255,242])||o(e,`ID3`))return`audio/mpeg`;if(a(e,[82,73,70,70])&&e.length>=12&&o(e,`WAVE`,8))return`audio/wav`;if(o(e,`fLaC`))return`audio/flac`;if(o(e,`OggS`))return`audio/ogg`;if(e.length>=12&&o(e,`ftyp`,4)&&o(e,`M4A`,8))return`audio/mp4`;if(o(e,`%PDF`))return`application/pdf`;if(a(e,[80,75,3,4])||a(e,[80,75,5,6])||a(e,[80,75,7,8])){if(e.length>=1024){let t=new TextDecoder(`utf-8`,{fatal:!1}).decode(e);if(t.includes(`word/`))return`application/vnd.openxmlformats-officedocument.wordprocessingml.document`;if(t.includes(`xl/`))return`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`;if(t.includes(`ppt/`))return`application/vnd.openxmlformats-officedocument.presentationml.presentation`}return`application/zip`}if(a(e,[82,97,114,33,26,7]))return`application/x-rar-compressed`;if(a(e,[55,122,188,175,39,28]))return`application/x-7z-compressed`;if(a(e,[31,139]))return`application/gzip`;if(e.length>=262&&o(e,`ustar`,257))return`application/x-tar`;if(o(e,`wOFF`))return`font/woff`;if(o(e,`wOF2`))return`font/woff2`;if(a(e,[0,1,0,0,0]))return`font/ttf`;if(o(e,`OTTO`))return`font/otf`;if(e.length>=1){let t=e[0];if(t===123||t===91)try{let t=new TextDecoder(`utf-8`).decode(e.slice(0,Math.min(1024,e.length)));return JSON.parse(t.trim()),`application/json`}catch{}}if(t)switch(t.split(`.`).pop()?.toLowerCase()){case`jpg`:case`jpeg`:return`image/jpeg`;case`png`:return`image/png`;case`gif`:return`image/gif`;case`webp`:return`image/webp`;case`avif`:return`image/avif`;case`heic`:case`heif`:return`image/heic`;case`bmp`:return`image/bmp`;case`tiff`:case`tif`:return`image/tiff`;case`ico`:return`image/x-icon`;case`svg`:return`image/svg+xml`;case`mp4`:case`m4v`:return`video/mp4`;case`webm`:return`video/webm`;case`avi`:return`video/x-msvideo`;case`mov`:return`video/quicktime`;case`mkv`:return`video/x-matroska`;case`mp3`:return`audio/mpeg`;case`wav`:return`audio/wav`;case`flac`:return`audio/flac`;case`ogg`:return`audio/ogg`;case`m4a`:return`audio/mp4`;case`pdf`:return`application/pdf`;case`docx`:return`application/vnd.openxmlformats-officedocument.wordprocessingml.document`;case`xlsx`:return`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`;case`pptx`:return`application/vnd.openxmlformats-officedocument.presentationml.presentation`;case`zip`:return`application/zip`;case`rar`:return`application/x-rar-compressed`;case`7z`:return`application/x-7z-compressed`;case`gz`:case`gzip`:return`application/gzip`;case`tar`:return`application/x-tar`;case`woff`:return`font/woff`;case`woff2`:return`font/woff2`;case`ttf`:return`font/ttf`;case`otf`:return`font/otf`;case`txt`:return`text/plain`;case`json`:return`application/json`;case`xml`:return`application/xml`;case`html`:case`htm`:return`text/html`;case`css`:return`text/css`;case`js`:return`application/javascript`;case`csv`:return`text/csv`;default:return`application/octet-stream`}return`application/octet-stream`};function c(e,t){return e===t?!0:e.split(`/`)[0]===t.split(`/`)[0]}const l=(e,n,{dataStoreService:r,kvStore:a,eventEmitter:o,generateId:s})=>i.Effect.gen(function*(){let i=yield*r.getDataStore(e.storageId,n),c=yield*s.generateId(),{size:l,type:u,fileName:d,lastModified:f,metadata:p,flow:m}=e,h={};if(p)try{h=JSON.parse(p)}catch{h={}}let g={...h,type:u,fileName:d??``};f&&(g.lastModified=f.toString());let _={id:c,size:l,metadata:g,offset:0,creationDate:new Date().toISOString(),storage:{id:e.storageId,type:u,path:``,bucket:i.bucket},flow:m},v=yield*i.create(_);return yield*a.set(c,v),yield*o.emit(c,{type:t.n.UPLOAD_STARTED,data:v,flow:v.flow}),v}).pipe(i.Effect.withSpan(`upload-create`,{attributes:{"upload.file_name":e.fileName??`unknown`,"upload.file_size":e.size?.toString()??`0`,"upload.storage_id":e.storageId,"upload.mime_type":e.type,"upload.has_flow":e.flow?`true`:`false`}}),i.Effect.tap(e=>i.Effect.gen(function*(){if(yield*i.Metric.increment(i.Metric.counter(`upload_created_total`,{description:`Total number of uploads created`})),e.size){let t=i.Metric.histogram(`upload_file_size_bytes`,i.MetricBoundaries.exponential({start:1024,factor:2,count:25}));yield*i.Metric.update(t,e.size)}let t=i.Metric.gauge(`active_uploads`);yield*i.Metric.increment(t)})),i.Effect.tap(t=>i.Effect.logInfo(`Upload created`).pipe(i.Effect.annotateLogs({"upload.id":t.id,"upload.file_name":e.fileName??`unknown`,"upload.file_size":e.size?.toString()??`0`,"upload.storage_id":e.storageId}))),i.Effect.tapError(t=>i.Effect.gen(function*(){yield*i.Effect.logError(`Upload creation failed`).pipe(i.Effect.annotateLogs({"upload.file_name":e.fileName??`unknown`,"upload.storage_id":e.storageId,error:String(t)})),yield*i.Metric.increment(i.Metric.counter(`upload_failed_total`,{description:`Total number of uploads that failed`}))})));function u(t){return i.Stream.fromReadableStream(()=>t,t=>new e.n({code:`UNKNOWN_ERROR`,status:500,body:String(t)}))}function d({data:n,upload:a,dataStore:o,maxFileSize:s,controller:c,eventEmitter:l,uploadProgressInterval:d=200}){return i.Effect.gen(function*(){let f=u(n);if(c.signal.aborted)return yield*i.Effect.fail(e.n.fromCode(`ABORTED`));let p=new AbortController,{signal:m}=p,h=()=>{p.abort()};return c.signal.addEventListener(`abort`,h,{once:!0}),yield*i.Effect.acquireUseRelease(i.Effect.sync(()=>({signal:m,onAbort:h})),({signal:n})=>i.Effect.gen(function*(){let e=yield*i.Ref.make(0),n=r.t.limit({maxSize:s})(f);return yield*o.write({stream:n,file_id:a.id,offset:a.offset},{onProgress:n=>{let r=Date.now();i.Ref.get(e).pipe(i.Effect.flatMap(o=>r-o>=d?i.Effect.gen(function*(){yield*i.Ref.set(e,r),yield*l.emit(a.id,{type:t.n.UPLOAD_PROGRESS,data:{id:a.id,progress:n,total:a.size??0},flow:a.flow})}):i.Effect.void),i.Effect.runPromise).catch(()=>{})}})}).pipe(i.Effect.catchAll(t=>t instanceof Error&&t.name===`AbortError`?i.Effect.fail(e.n.fromCode(`ABORTED`)):t instanceof e.n?i.Effect.fail(t):i.Effect.fail(e.n.fromCode(`FILE_WRITE_ERROR`,{cause:t})))),({onAbort:e})=>i.Effect.sync(()=>{c.signal.removeEventListener(`abort`,e)}))}).pipe(i.Effect.withSpan(`upload-write-to-store`,{attributes:{"upload.id":a.id,"upload.offset":a.offset.toString(),"upload.max_file_size":s.toString(),"upload.file_size":a.size?.toString()??`0`}}),i.Effect.tap(e=>i.Effect.logDebug(`Data written to store`).pipe(i.Effect.annotateLogs({"upload.id":a.id,"write.offset":e.toString(),"write.bytes_written":(e-a.offset).toString()}))),i.Effect.tapError(t=>i.Effect.logError(`Failed to write to store`).pipe(i.Effect.annotateLogs({"upload.id":a.id,"upload.offset":a.offset.toString(),error:t instanceof e.n?t.code:String(t)}))))}const f=(e,n,r,{dataStoreService:a,kvStore:o,eventEmitter:s})=>i.Effect.gen(function*(){let i=yield*o.get(e),c=yield*a.getDataStore(i.storage.id,n);return i.offset=yield*d({dataStore:c,data:r,upload:i,maxFileSize:1e8,controller:new AbortController,uploadProgressInterval:200,eventEmitter:s}),yield*o.set(e,i),yield*s.emit(i.id,{type:t.n.UPLOAD_PROGRESS,data:{id:i.id,progress:i.offset,total:i.size??0},flow:i.flow}),i.size&&i.offset===i.size&&(yield*p({file:i,dataStore:c,eventEmitter:s})),i}).pipe(i.Effect.withSpan(`upload-chunk`,{attributes:{"upload.id":e,"chunk.upload_id":e}}),i.Effect.tap(e=>i.Effect.gen(function*(){yield*i.Metric.increment(i.Metric.counter(`chunk_uploaded_total`,{description:`Total number of chunks uploaded`}));let t=e.offset,n=i.Metric.histogram(`chunk_size_bytes`,i.MetricBoundaries.linear({start:262144,width:262144,count:20}));if(yield*i.Metric.update(n,t),e.size&&e.size>0){let e=t,n=i.Metric.gauge(`upload_throughput_bytes_per_second`);yield*i.Metric.set(n,e)}})),i.Effect.tap(e=>i.Effect.logDebug(`Chunk uploaded`).pipe(i.Effect.annotateLogs({"upload.id":e.id,"chunk.size":e.offset.toString(),"chunk.progress":e.size&&e.size>0?(e.offset/e.size*100).toFixed(2):`0`,"upload.total_size":e.size?.toString()??`0`}))),i.Effect.tapError(t=>i.Effect.logError(`Chunk upload failed`).pipe(i.Effect.annotateLogs({"upload.id":e,error:String(t)})))),p=({file:r,dataStore:a,eventEmitter:o})=>i.Effect.gen(function*(){let i=a.getCapabilities();if(i.maxValidationSize&&r.size&&r.size>i.maxValidationSize){yield*o.emit(r.id,{type:t.n.UPLOAD_VALIDATION_WARNING,data:{id:r.id,message:`File size (${r.size} bytes) exceeds max validation size (${i.maxValidationSize} bytes). Validation skipped.`},flow:r.flow});return}let l=yield*a.read(r.id);if(r.checksum&&r.checksumAlgorithm){let i=yield*n.t(l,r.checksumAlgorithm);if(i!==r.checksum)return yield*o.emit(r.id,{type:t.n.UPLOAD_VALIDATION_FAILED,data:{id:r.id,reason:`checksum_mismatch`,expected:r.checksum,actual:i},flow:r.flow}),yield*a.remove(r.id),yield*e.n.fromCode(`CHECKSUM_MISMATCH`,{body:`Checksum validation failed. Expected: ${r.checksum}, Got: ${i}`,details:{uploadId:r.id,expected:r.checksum,actual:i,algorithm:r.checksumAlgorithm}}).toEffect();yield*o.emit(r.id,{type:t.n.UPLOAD_VALIDATION_SUCCESS,data:{id:r.id,validationType:`checksum`,algorithm:r.checksumAlgorithm},flow:r.flow})}if(i.requiresMimeTypeValidation){let n=s(l),i=r.metadata?.type;if(i&&!c(i,n))return yield*o.emit(r.id,{type:t.n.UPLOAD_VALIDATION_FAILED,data:{id:r.id,reason:`mimetype_mismatch`,expected:i,actual:n},flow:r.flow}),yield*a.remove(r.id),yield*e.n.fromCode(`MIMETYPE_MISMATCH`,{body:`MIME type validation failed. Expected: ${i}, Detected: ${n}`,details:{uploadId:r.id,expected:i,actual:n}}).toEffect();yield*o.emit(r.id,{type:t.n.UPLOAD_VALIDATION_SUCCESS,data:{id:r.id,validationType:`mimetype`},flow:r.flow})}}).pipe(i.Effect.withSpan(`validate-upload`,{attributes:{"upload.id":r.id,"validation.checksum_provided":r.checksum?`true`:`false`,"validation.mime_required":a.getCapabilities().requiresMimeTypeValidation?`true`:`false`}})),m=t=>i.Effect.tryPromise({try:async()=>await fetch(t),catch:t=>e.n.fromCode(`UNKNOWN_ERROR`,{cause:t})}).pipe(i.Effect.withSpan(`upload-fetch-url`,{attributes:{"upload.url":t,"upload.operation":`fetch`}}),i.Effect.tap(e=>i.Effect.gen(function*(){yield*i.Metric.increment(i.Metric.counter(`upload_from_url_total`,{description:`Total number of URL-based uploads`})),e.ok&&(yield*i.Metric.increment(i.Metric.counter(`upload_from_url_success_total`,{description:`Total number of successful URL-based uploads`})))})),i.Effect.tap(e=>i.Effect.logInfo(`URL fetch completed`).pipe(i.Effect.annotateLogs({"upload.url":t,"response.status":e.status.toString(),"response.ok":e.ok.toString(),"response.content_length":e.headers.get(`content-length`)??`unknown`}))),i.Effect.tapError(e=>i.Effect.gen(function*(){yield*i.Metric.increment(i.Metric.counter(`upload_from_url_failed_total`,{description:`Total number of failed URL-based uploads`})),yield*i.Effect.logError(`URL fetch failed`).pipe(i.Effect.annotateLogs({"upload.url":t,error:String(e)}))}))),h=t=>i.Effect.tryPromise({try:async()=>await t.arrayBuffer(),catch:t=>e.n.fromCode(`UNKNOWN_ERROR`,{cause:t})}).pipe(i.Effect.withSpan(`upload-convert-to-buffer`,{attributes:{"upload.operation":`arrayBuffer`}}),i.Effect.tap(e=>i.Effect.logDebug(`Response converted to array buffer`).pipe(i.Effect.annotateLogs({"buffer.size":e.byteLength.toString()}))),i.Effect.tapError(e=>i.Effect.logError(`Failed to convert response to array buffer`).pipe(i.Effect.annotateLogs({error:String(e)}))));var g=class extends i.Context.Tag(`UploadServer`)(){};function _(){return i.Effect.gen(function*(){let e=yield*t.u,r=yield*t.v,a=yield*n.r,o=yield*t.T;return{upload:(t,n,s)=>i.Effect.gen(function*(){return yield*f((yield*l(t,n,{dataStoreService:o,kvStore:e,eventEmitter:r,generateId:a})).id,n,s,{dataStoreService:o,kvStore:e,eventEmitter:r})}),uploadFromUrl:(t,n,s)=>i.Effect.gen(function*(){let i=yield*h(yield*m(s)),c=new ReadableStream({start(e){e.enqueue(new Uint8Array(i)),e.close()}});return yield*f((yield*l({...t,size:i.byteLength},n,{dataStoreService:o,kvStore:e,eventEmitter:r,generateId:a})).id,n,c,{dataStoreService:o,kvStore:e,eventEmitter:r})}),createUpload:(t,n)=>i.Effect.gen(function*(){return yield*l(t,n,{dataStoreService:o,kvStore:e,eventEmitter:r,generateId:a})}),uploadChunk:(t,n,a)=>i.Effect.gen(function*(){return yield*f(t,n,a,{dataStoreService:o,kvStore:e,eventEmitter:r})}),getUpload:t=>i.Effect.gen(function*(){return yield*e.get(t)}),read:(t,n)=>i.Effect.gen(function*(){let r=yield*e.get(t);return yield*(yield*o.getDataStore(r.storage.id,n)).read(t)}),delete:(t,n)=>i.Effect.gen(function*(){let r=yield*e.get(t);yield*(yield*o.getDataStore(r.storage.id,n)).remove(t),yield*e.delete(t)}),getCapabilities:(e,t)=>i.Effect.gen(function*(){return(yield*o.getDataStore(e,t)).getCapabilities()}),subscribeToUploadEvents:(e,t)=>i.Effect.gen(function*(){yield*r.subscribe(e,t)}),unsubscribeFromUploadEvents:e=>i.Effect.gen(function*(){yield*r.unsubscribe(e)})}})}const v=i.Layer.effect(g,_());var y=class{constructor(e,t){this.capabilities=e,this.validateUploadStrategy=t}negotiateStrategy(e){let t=[],n=[],r=`single`,i=e.preferredChunkSize??this.capabilities.optimalChunkSize??1024*1024,a=e.parallelUploads??1;if(e.preferredStrategy&&(this.validateUploadStrategy(e.preferredStrategy)?(r=e.preferredStrategy,t.push(`Using preferred strategy: ${r}`)):n.push(`Preferred strategy '${e.preferredStrategy}' not supported by data store, falling back`)),(!e.preferredStrategy||!this.validateUploadStrategy(e.preferredStrategy))&&(this.capabilities.supportsParallelUploads&&e.fileSize>(e.minChunkSizeForParallel??10*1024*1024)?(r=`parallel`,t.push(`Selected parallel upload for large file (${e.fileSize} bytes)`)):(r=`single`,t.push(this.capabilities.supportsParallelUploads?`Selected single upload for small file (${e.fileSize} bytes)`:`Selected single upload (parallel not supported by data store)`))),this.capabilities.minChunkSize&&i<this.capabilities.minChunkSize&&(n.push(`Chunk size ${i} below minimum ${this.capabilities.minChunkSize}, adjusting`),i=this.capabilities.minChunkSize),this.capabilities.maxChunkSize&&i>this.capabilities.maxChunkSize&&(n.push(`Chunk size ${i} above maximum ${this.capabilities.maxChunkSize}, adjusting`),i=this.capabilities.maxChunkSize),r===`parallel`&&(this.capabilities.maxConcurrentUploads&&a>this.capabilities.maxConcurrentUploads&&(n.push(`Parallel uploads ${a} exceeds maximum ${this.capabilities.maxConcurrentUploads}, adjusting`),a=this.capabilities.maxConcurrentUploads),this.capabilities.maxParts)){let t=Math.ceil(e.fileSize/i);if(t>this.capabilities.maxParts){let r=Math.ceil(e.fileSize/this.capabilities.maxParts);n.push(`Estimated parts ${t} exceeds maximum ${this.capabilities.maxParts}, increasing chunk size`),i=Math.max(i,r)}}return this.validateUploadStrategy(r)||(n.push(`Final strategy validation failed, falling back to single upload`),r=`single`,a=1),t.push(`Data store capabilities: parallel=${this.capabilities.supportsParallelUploads}, concatenation=${this.capabilities.supportsConcatenation}, resumable=${this.capabilities.supportsResumableUploads}`),{strategy:r,chunkSize:i,parallelUploads:r===`parallel`?a:1,reasoning:t,warnings:n}}getDataStoreCapabilities(){return this.capabilities}validateConfiguration(e){let t=[];return e.preferredStrategy&&!this.validateUploadStrategy(e.preferredStrategy)&&t.push(`Preferred strategy '${e.preferredStrategy}' not supported by data store`),e.preferredChunkSize&&(this.capabilities.minChunkSize&&e.preferredChunkSize<this.capabilities.minChunkSize&&t.push(`Chunk size ${e.preferredChunkSize} below data store minimum ${this.capabilities.minChunkSize}`),this.capabilities.maxChunkSize&&e.preferredChunkSize>this.capabilities.maxChunkSize&&t.push(`Chunk size ${e.preferredChunkSize} above data store maximum ${this.capabilities.maxChunkSize}`)),e.parallelUploads&&this.capabilities.maxConcurrentUploads&&e.parallelUploads>this.capabilities.maxConcurrentUploads&&t.push(`Parallel uploads ${e.parallelUploads} exceeds data store maximum ${this.capabilities.maxConcurrentUploads}`),{valid:t.length===0,errors:t}}};Object.defineProperty(exports,`a`,{enumerable:!0,get:function(){return h}}),Object.defineProperty(exports,`c`,{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,`i`,{enumerable:!0,get:function(){return v}}),Object.defineProperty(exports,`n`,{enumerable:!0,get:function(){return g}}),Object.defineProperty(exports,`o`,{enumerable:!0,get:function(){return m}}),Object.defineProperty(exports,`r`,{enumerable:!0,get:function(){return _}}),Object.defineProperty(exports,`s`,{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return y}});
@@ -0,0 +1,221 @@
1
+ import * as effect_Types0 from "effect/Types";
2
+ import * as effect_Cause0 from "effect/Cause";
3
+ import { Effect } from "effect";
4
+
5
+ //#region src/errors/uploadista-error.d.ts
6
+
7
+ /**
8
+ * Union type of all possible error codes in the Uploadista system.
9
+ *
10
+ * Each error code corresponds to a specific error condition with predefined
11
+ * HTTP status codes and messages in the ERROR_CATALOG.
12
+ */
13
+ type UploadistaErrorCode = "MISSING_OFFSET" | "ABORTED" | "INVALID_TERMINATION" | "ERR_LOCK_TIMEOUT" | "INVALID_CONTENT_TYPE" | "FLOW_STRUCTURE_ERROR" | "FLOW_CYCLE_ERROR" | "FLOW_NODE_NOT_FOUND" | "FLOW_NODE_ERROR" | "FLOW_NOT_AUTHORIZED" | "FLOW_NOT_FOUND" | "FILE_READ_ERROR" | "FLOW_JOB_NOT_FOUND" | "FLOW_JOB_ERROR" | "DATASTORE_NOT_FOUND" | "FILE_NOT_FOUND" | "INVALID_OFFSET" | "FILE_NO_LONGER_EXISTS" | "ERR_SIZE_EXCEEDED" | "ERR_MAX_SIZE_EXCEEDED" | "INVALID_LENGTH" | "INVALID_METADATA" | "VALIDATION_ERROR" | "STORAGE_NOT_AUTHORIZED" | "UNKNOWN_ERROR" | "FILE_WRITE_ERROR" | "UPLOAD_ID_NOT_FOUND" | "FLOW_OUTPUT_VALIDATION_ERROR" | "FLOW_INPUT_VALIDATION_ERROR" | "CHECKSUM_MISMATCH" | "MIMETYPE_MISMATCH" | "UNSUPPORTED_CHECKSUM_ALGORITHM";
14
+ /**
15
+ * Catalog of all predefined errors in the Uploadista system.
16
+ *
17
+ * Maps error codes to their HTTP status codes and default error messages.
18
+ * This centralized catalog ensures consistent error handling across all
19
+ * Uploadista packages and adapters.
20
+ *
21
+ * Each error entry contains:
22
+ * - `status`: HTTP status code (400-500 range)
23
+ * - `body`: Human-readable error message
24
+ *
25
+ * @example
26
+ * ```typescript
27
+ * // Access a specific error definition
28
+ * const fileNotFound = ERROR_CATALOG.FILE_NOT_FOUND;
29
+ * console.log(fileNotFound.status); // 404
30
+ * console.log(fileNotFound.body); // "The file for this url was not found\n"
31
+ *
32
+ * // Use with UploadistaError
33
+ * const error = UploadistaError.fromCode("FILE_NOT_FOUND");
34
+ * ```
35
+ */
36
+ declare const ERROR_CATALOG: Readonly<Record<UploadistaErrorCode, {
37
+ status: number;
38
+ body: string;
39
+ }>>;
40
+ declare const UploadistaError_base: new <A extends Record<string, any> = {}>(args: effect_Types0.Equals<A, {}> extends true ? void : { readonly [P in keyof A as P extends "_tag" ? never : P]: A[P] }) => effect_Cause0.YieldableError & {
41
+ readonly _tag: "UploadistaError";
42
+ } & Readonly<A>;
43
+ /**
44
+ * Standard error class for all Uploadista operations.
45
+ *
46
+ * UploadistaError provides a consistent error handling approach across the entire
47
+ * Uploadista ecosystem. Each error has:
48
+ * - A typed error code from the ERROR_CATALOG
49
+ * - An HTTP-compatible status code
50
+ * - A human-readable error message (body)
51
+ * - Optional additional details and cause information
52
+ *
53
+ * This class integrates with Effect-TS for functional error handling and can be
54
+ * easily converted to an Effect that fails.
55
+ *
56
+ * @example
57
+ * ```typescript
58
+ * // Create from error code
59
+ * const error = UploadistaError.fromCode("FILE_NOT_FOUND");
60
+ *
61
+ * // Create with custom details
62
+ * const customError = UploadistaError.fromCode("FLOW_NODE_ERROR", {
63
+ * body: "Failed to process image",
64
+ * cause: originalError,
65
+ * details: { nodeId: "resize-1", fileId: "abc123" }
66
+ * });
67
+ *
68
+ * // Use with Effect
69
+ * const effect = customError.toEffect<void>();
70
+ *
71
+ * // In an Effect pipeline
72
+ * return Effect.gen(function* () {
73
+ * const file = yield* getFile(id);
74
+ * if (!file) {
75
+ * return yield* UploadistaError.fromCode("FILE_NOT_FOUND").toEffect();
76
+ * }
77
+ * return file;
78
+ * });
79
+ * ```
80
+ */
81
+ declare class UploadistaError extends UploadistaError_base {
82
+ readonly code: string;
83
+ readonly status: number;
84
+ readonly status_code: number;
85
+ readonly body: string;
86
+ readonly details?: unknown;
87
+ constructor({
88
+ code,
89
+ status,
90
+ body,
91
+ cause,
92
+ details
93
+ }: {
94
+ code: UploadistaErrorCode | string;
95
+ status: number;
96
+ body: string;
97
+ cause?: unknown;
98
+ details?: unknown;
99
+ });
100
+ /**
101
+ * Creates an UploadistaError from a predefined error code.
102
+ *
103
+ * This is the primary way to create errors in the Uploadista system. Each error code
104
+ * has a default status and message defined in ERROR_CATALOG, but these can be overridden
105
+ * for specific use cases.
106
+ *
107
+ * @param code - One of the predefined error codes from UploadistaErrorCode
108
+ * @param overrides - Optional overrides for the default error properties
109
+ * @param overrides.status - Custom HTTP status code (overrides the default)
110
+ * @param overrides.body - Custom error message (overrides the default)
111
+ * @param overrides.details - Additional structured data about the error
112
+ * @param overrides.cause - The underlying error that caused this error (for error chaining)
113
+ *
114
+ * @returns A new UploadistaError instance
115
+ *
116
+ * @example
117
+ * ```typescript
118
+ * // Use default error
119
+ * const error = UploadistaError.fromCode("FILE_NOT_FOUND");
120
+ *
121
+ * // Override message
122
+ * const customError = UploadistaError.fromCode("FILE_NOT_FOUND", {
123
+ * body: `File with ID ${fileId} was not found in storage`
124
+ * });
125
+ *
126
+ * // Include cause and details
127
+ * const detailedError = UploadistaError.fromCode("DATASTORE_NOT_FOUND", {
128
+ * cause: storageException,
129
+ * details: { storageId: "s3-prod", region: "us-east-1" }
130
+ * });
131
+ * ```
132
+ */
133
+ static fromCode(code: UploadistaErrorCode, overrides?: Partial<Pick<UploadistaError, "status" | "body">> & {
134
+ details?: unknown;
135
+ cause?: unknown;
136
+ }): UploadistaError;
137
+ /**
138
+ * Converts this error to an Effect that immediately fails.
139
+ *
140
+ * This method integrates UploadistaError with Effect-TS's error handling system,
141
+ * allowing errors to be used in Effect pipelines with proper type checking.
142
+ *
143
+ * @template T - The success type of the Effect (defaults to never since it always fails)
144
+ * @returns An Effect that fails with this UploadistaError
145
+ *
146
+ * @example
147
+ * ```typescript
148
+ * const error = UploadistaError.fromCode("FILE_NOT_FOUND");
149
+ *
150
+ * // Use in an Effect pipeline
151
+ * return Effect.gen(function* () {
152
+ * const file = yield* kvStore.get(fileId);
153
+ * if (!file) {
154
+ * return yield* error.toEffect();
155
+ * }
156
+ * return file;
157
+ * });
158
+ * ```
159
+ */
160
+ toEffect<T = never>(): Effect.Effect<T, UploadistaError>;
161
+ }
162
+ /**
163
+ * Type guard to check if an unknown value is an UploadistaError.
164
+ *
165
+ * Useful for error handling when catching errors that might be from
166
+ * different sources or libraries.
167
+ *
168
+ * @param error - The value to check
169
+ * @returns True if the value is an UploadistaError instance
170
+ *
171
+ * @example
172
+ * ```typescript
173
+ * try {
174
+ * await someOperation();
175
+ * } catch (error) {
176
+ * if (isUploadistaError(error)) {
177
+ * console.log(`Uploadista error: ${error.code} (${error.status})`);
178
+ * console.log(error.body);
179
+ * } else {
180
+ * console.error("Unknown error:", error);
181
+ * }
182
+ * }
183
+ * ```
184
+ */
185
+ declare function isUploadistaError(error: unknown): error is UploadistaError;
186
+ /**
187
+ * Creates an Effect that immediately fails with an UploadistaError.
188
+ *
189
+ * This is a convenience function that combines error creation with Effect conversion.
190
+ * It's equivalent to calling `UploadistaError.fromCode(code, overrides).toEffect()`.
191
+ *
192
+ * @param code - One of the predefined error codes from UploadistaErrorCode
193
+ * @param overrides - Optional overrides for the default error properties
194
+ * @param overrides.status - Custom HTTP status code
195
+ * @param overrides.body - Custom error message
196
+ * @param overrides.details - Additional structured data about the error
197
+ * @param overrides.cause - The underlying error that caused this error
198
+ *
199
+ * @returns An Effect that immediately fails with the created UploadistaError
200
+ *
201
+ * @example
202
+ * ```typescript
203
+ * // In an Effect pipeline
204
+ * return Effect.gen(function* () {
205
+ * const file = yield* kvStore.get(fileId);
206
+ * if (!file) {
207
+ * return yield* httpFailure("FILE_NOT_FOUND", {
208
+ * details: { fileId }
209
+ * });
210
+ * }
211
+ * return file;
212
+ * });
213
+ * ```
214
+ */
215
+ declare function httpFailure(code: UploadistaErrorCode, overrides?: Partial<Pick<UploadistaError, "status" | "body">> & {
216
+ details?: unknown;
217
+ cause?: unknown;
218
+ }): Effect.Effect<never, UploadistaError>;
219
+ //#endregion
220
+ export { isUploadistaError as a, httpFailure as i, UploadistaError as n, UploadistaErrorCode as r, ERROR_CATALOG as t };
221
+ //# sourceMappingURL=uploadista-error-CAtkQiAv.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"uploadista-error-CAtkQiAv.d.cts","names":[],"sources":["../src/errors/uploadista-error.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;AAQA;AAwDA;AACS,KAzDG,mBAAA,GAyDH,gBAAA,GAAA,SAAA,GAAA,qBAAA,GAAA,kBAAA,GAAA,sBAAA,GAAA,sBAAA,GAAA,kBAAA,GAAA,qBAAA,GAAA,iBAAA,GAAA,qBAAA,GAAA,gBAAA,GAAA,iBAAA,GAAA,oBAAA,GAAA,gBAAA,GAAA,qBAAA,GAAA,gBAAA,GAAA,gBAAA,GAAA,uBAAA,GAAA,mBAAA,GAAA,uBAAA,GAAA,gBAAA,GAAA,kBAAA,GAAA,kBAAA,GAAA,wBAAA,GAAA,eAAA,GAAA,kBAAA,GAAA,qBAAA,GAAA,8BAAA,GAAA,6BAAA,GAAA,mBAAA,GAAA,mBAAA,GAAA,gCAAA;;;;AAmHE;;;;;;;;;;;;;AAwCX;;;;;;AAeU,cA3KG,aA2KH,EA3KkB,QA2KlB,CA1KR,MA0KQ,CA1KD,mBA0KC,EAAA;EAkDA,MAAA,EAAA,MAAA;EACmB,IAAA,EAAA,MAAA;CAAL,CAAA,CAAA;cA1Gb,oBA0GK,EAAA,IAAA,CAAA,gBAAA,CAAA,MAAA,EAAA,GAAA,CAAA,GAAA,CAAA,CAAA,CAAA,CAAA,IAAA,sBAAA,EAAA,EAAA,CAAA,CAAA,CAAA,SAAA,IAAA,GAAA,IAAA,GAAA,iBAAA,OAAA,KAAA,SAAA,MAAA,GAAA,KAAA,IAAA,IAAA,EAAA,CAAA,EAAA,EAAA,kCAAA;EAIX,SAAA,IAAA,EAAA,iBAAA;CAkCkC,WAAA,EAAA,CAAA;;;;;AA4BvC;AAiCA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cArKa,eAAA,SAAwB,oBAAA;;;;;;;;;;;;;UAe3B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;wBAkDA,iCACM,QAAQ,KAAK;;;MAIxB;;;;;;;;;;;;;;;;;;;;;;;;yBAkCoB,MAAA,CAAO,OAAO,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;iBA4B1B,iBAAA,2BAA4C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAiC5C,WAAA,OACR,iCACM,QAAQ,KAAK;;;IAIxB,MAAA,CAAO,cAAc"}
@@ -3,6 +3,8 @@ import{Data as e,Effect as t}from"effect";const n={MISSING_OFFSET:{status:403,bo
3
3
  `},DATASTORE_NOT_FOUND:{status:500,body:`The datastore was not found
4
4
  `},UPLOAD_ID_NOT_FOUND:{status:500,body:`The upload id was not found
5
5
  `},FILE_NOT_FOUND:{status:404,body:`The file for this url was not found
6
+ `},FLOW_NOT_AUTHORIZED:{status:401,body:`The flow is not authorized
7
+ `},FLOW_NOT_FOUND:{status:404,body:`The flow was not found
6
8
  `},FLOW_STRUCTURE_ERROR:{status:500,body:`The flow structure is invalid
7
9
  `},FLOW_CYCLE_ERROR:{status:500,body:`The flow contains a cycle
8
10
  `},FLOW_NODE_NOT_FOUND:{status:500,body:`The flow node was not found
@@ -13,11 +15,16 @@ import{Data as e,Effect as t}from"effect";const n={MISSING_OFFSET:{status:403,bo
13
15
  `},FLOW_OUTPUT_VALIDATION_ERROR:{status:500,body:`The flow output validation failed
14
16
  `},INVALID_OFFSET:{status:409,body:`Upload-Offset conflict
15
17
  `},FILE_NO_LONGER_EXISTS:{status:410,body:`The file for this url no longer exists
18
+ `},FILE_READ_ERROR:{status:500,body:`Something went wrong reading the file
16
19
  `},ERR_SIZE_EXCEEDED:{status:413,body:`upload's size exceeded
17
20
  `},ERR_MAX_SIZE_EXCEEDED:{status:413,body:`Maximum size exceeded
18
21
  `},INVALID_LENGTH:{status:400,body:`Upload-Length or Upload-Defer-Length header required
19
22
  `},INVALID_METADATA:{status:400,body:`Upload-Metadata is invalid. It MUST consist of one or more comma-separated key-value pairs. The key and value MUST be separated by a space. The key MUST NOT contain spaces and commas and MUST NOT be empty. The key SHOULD be ASCII encoded and the value MUST be Base64 encoded. All keys MUST be unique`},VALIDATION_ERROR:{status:400,body:`Validation failed
23
+ `},STORAGE_NOT_AUTHORIZED:{status:401,body:`The storage is not authorized
20
24
  `},UNKNOWN_ERROR:{status:500,body:`Something went wrong with that request
21
25
  `},FILE_WRITE_ERROR:{status:500,body:`Something went wrong receiving the file
22
- `}};var r=class r extends e.TaggedError(`UploadistaError`){code;status;status_code;body;details;constructor({code:e,status:t,body:n,cause:r,details:i}){super(),this.name=`UploadistaError`,this.code=e,this.status=t,this.status_code=t,this.body=n,this.details=i,r&&(this.cause=r)}static fromCode(e,t){let i=n[e];return new r({code:e,status:t?.status??i.status,body:t?.body??i.body,details:t?.details,cause:t?.cause})}toEffect(){return t.fail(this)}};function i(e){return e instanceof r}function a(e,t){return r.fromCode(e,t).toEffect()}export{n as ERROR_CATALOG,r as UploadistaError,a as httpFailureEffect,i as isUploadistaError};
23
- //# sourceMappingURL=uploadista-error-BVsVxqvz.js.map
26
+ `},CHECKSUM_MISMATCH:{status:400,body:`The file checksum does not match the provided checksum
27
+ `},MIMETYPE_MISMATCH:{status:400,body:`The file MIME type does not match the declared type
28
+ `},UNSUPPORTED_CHECKSUM_ALGORITHM:{status:400,body:`The specified checksum algorithm is not supported
29
+ `}};var r=class r extends e.TaggedError(`UploadistaError`){code;status;status_code;body;details;constructor({code:e,status:t,body:n,cause:r,details:i}){super(),this.name=`UploadistaError`,this.code=e,this.status=t,this.status_code=t,this.body=n,this.details=i,r&&(this.cause=r)}static fromCode(e,t){let i=n[e];return new r({code:e,status:t?.status??i.status,body:t?.body??i.body,details:t?.details,cause:t?.cause})}toEffect(){return t.fail(this)}};function i(e){return e instanceof r}function a(e,t){return r.fromCode(e,t).toEffect()}export{i,r as n,a as r,n as t};
30
+ //# sourceMappingURL=uploadista-error-CjfcFnVa.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"uploadista-error-CjfcFnVa.js","names":["ERROR_CATALOG: Readonly<\n Record<UploadistaErrorCode, { status: number; body: string }>\n>"],"sources":["../src/errors/uploadista-error.ts"],"sourcesContent":["import { Data, Effect } from \"effect\";\n\n/**\n * Union type of all possible error codes in the Uploadista system.\n *\n * Each error code corresponds to a specific error condition with predefined\n * HTTP status codes and messages in the ERROR_CATALOG.\n */\nexport type UploadistaErrorCode =\n | \"MISSING_OFFSET\"\n | \"ABORTED\"\n | \"INVALID_TERMINATION\"\n | \"ERR_LOCK_TIMEOUT\"\n | \"INVALID_CONTENT_TYPE\"\n | \"FLOW_STRUCTURE_ERROR\"\n | \"FLOW_CYCLE_ERROR\"\n | \"FLOW_NODE_NOT_FOUND\"\n | \"FLOW_NODE_ERROR\"\n | \"FLOW_NOT_AUTHORIZED\"\n | \"FLOW_NOT_FOUND\"\n | \"FILE_READ_ERROR\"\n | \"FLOW_JOB_NOT_FOUND\"\n | \"FLOW_JOB_ERROR\"\n | \"DATASTORE_NOT_FOUND\"\n | \"FILE_NOT_FOUND\"\n | \"INVALID_OFFSET\"\n | \"FILE_NO_LONGER_EXISTS\"\n | \"ERR_SIZE_EXCEEDED\"\n | \"ERR_MAX_SIZE_EXCEEDED\"\n | \"INVALID_LENGTH\"\n | \"INVALID_METADATA\"\n | \"VALIDATION_ERROR\"\n | \"STORAGE_NOT_AUTHORIZED\"\n | \"UNKNOWN_ERROR\"\n | \"FILE_WRITE_ERROR\"\n | \"UPLOAD_ID_NOT_FOUND\"\n | \"FLOW_OUTPUT_VALIDATION_ERROR\"\n | \"FLOW_INPUT_VALIDATION_ERROR\"\n | \"CHECKSUM_MISMATCH\"\n | \"MIMETYPE_MISMATCH\"\n | \"UNSUPPORTED_CHECKSUM_ALGORITHM\";\n\n/**\n * Catalog of all predefined errors in the Uploadista system.\n *\n * Maps error codes to their HTTP status codes and default error messages.\n * This centralized catalog ensures consistent error handling across all\n * Uploadista packages and adapters.\n *\n * Each error entry contains:\n * - `status`: HTTP status code (400-500 range)\n * - `body`: Human-readable error message\n *\n * @example\n * ```typescript\n * // Access a specific error definition\n * const fileNotFound = ERROR_CATALOG.FILE_NOT_FOUND;\n * console.log(fileNotFound.status); // 404\n * console.log(fileNotFound.body); // \"The file for this url was not found\\n\"\n *\n * // Use with UploadistaError\n * const error = UploadistaError.fromCode(\"FILE_NOT_FOUND\");\n * ```\n */\nexport const ERROR_CATALOG: Readonly<\n Record<UploadistaErrorCode, { status: number; body: string }>\n> = {\n MISSING_OFFSET: { status: 403, body: \"Upload-Offset header required\\n\" },\n ABORTED: { status: 400, body: \"Request aborted due to lock acquired\" },\n INVALID_TERMINATION: {\n status: 400,\n body: \"Cannot terminate an already completed upload\",\n },\n ERR_LOCK_TIMEOUT: {\n status: 500,\n body: \"failed to acquire lock before timeout\",\n },\n INVALID_CONTENT_TYPE: {\n status: 403,\n body: \"Content-Type header required\\n\",\n },\n DATASTORE_NOT_FOUND: {\n status: 500,\n body: \"The datastore was not found\\n\",\n },\n UPLOAD_ID_NOT_FOUND: {\n status: 500,\n body: \"The upload id was not found\\n\",\n },\n FILE_NOT_FOUND: {\n status: 404,\n body: \"The file for this url was not found\\n\",\n },\n FLOW_NOT_AUTHORIZED: {\n status: 401,\n body: \"The flow is not authorized\\n\",\n },\n FLOW_NOT_FOUND: {\n status: 404,\n body: \"The flow was not found\\n\",\n },\n FLOW_STRUCTURE_ERROR: {\n status: 500,\n body: \"The flow structure is invalid\\n\",\n },\n FLOW_CYCLE_ERROR: {\n status: 500,\n body: \"The flow contains a cycle\\n\",\n },\n FLOW_NODE_NOT_FOUND: {\n status: 500,\n body: \"The flow node was not found\\n\",\n },\n FLOW_NODE_ERROR: {\n status: 500,\n body: \"The flow node failed\\n\",\n },\n FLOW_JOB_NOT_FOUND: {\n status: 404,\n body: \"The flow job was not found\\n\",\n },\n FLOW_JOB_ERROR: {\n status: 500,\n body: \"The flow job failed\\n\",\n },\n FLOW_INPUT_VALIDATION_ERROR: {\n status: 500,\n body: \"The flow input validation failed\\n\",\n },\n FLOW_OUTPUT_VALIDATION_ERROR: {\n status: 500,\n body: \"The flow output validation failed\\n\",\n },\n INVALID_OFFSET: { status: 409, body: \"Upload-Offset conflict\\n\" },\n FILE_NO_LONGER_EXISTS: {\n status: 410,\n body: \"The file for this url no longer exists\\n\",\n },\n FILE_READ_ERROR: {\n status: 500,\n body: \"Something went wrong reading the file\\n\",\n },\n ERR_SIZE_EXCEEDED: { status: 413, body: \"upload's size exceeded\\n\" },\n ERR_MAX_SIZE_EXCEEDED: { status: 413, body: \"Maximum size exceeded\\n\" },\n INVALID_LENGTH: {\n status: 400,\n body: \"Upload-Length or Upload-Defer-Length header required\\n\",\n },\n INVALID_METADATA: {\n status: 400,\n body: \"Upload-Metadata is invalid. It MUST consist of one or more comma-separated key-value pairs. The key and value MUST be separated by a space. The key MUST NOT contain spaces and commas and MUST NOT be empty. The key SHOULD be ASCII encoded and the value MUST be Base64 encoded. All keys MUST be unique\",\n },\n VALIDATION_ERROR: {\n status: 400,\n body: \"Validation failed\\n\",\n },\n STORAGE_NOT_AUTHORIZED: {\n status: 401,\n body: \"The storage is not authorized\\n\",\n },\n UNKNOWN_ERROR: {\n status: 500,\n body: \"Something went wrong with that request\\n\",\n },\n FILE_WRITE_ERROR: {\n status: 500,\n body: \"Something went wrong receiving the file\\n\",\n },\n CHECKSUM_MISMATCH: {\n status: 400,\n body: \"The file checksum does not match the provided checksum\\n\",\n },\n MIMETYPE_MISMATCH: {\n status: 400,\n body: \"The file MIME type does not match the declared type\\n\",\n },\n UNSUPPORTED_CHECKSUM_ALGORITHM: {\n status: 400,\n body: \"The specified checksum algorithm is not supported\\n\",\n },\n} as const;\n\n/**\n * Standard error class for all Uploadista operations.\n *\n * UploadistaError provides a consistent error handling approach across the entire\n * Uploadista ecosystem. Each error has:\n * - A typed error code from the ERROR_CATALOG\n * - An HTTP-compatible status code\n * - A human-readable error message (body)\n * - Optional additional details and cause information\n *\n * This class integrates with Effect-TS for functional error handling and can be\n * easily converted to an Effect that fails.\n *\n * @example\n * ```typescript\n * // Create from error code\n * const error = UploadistaError.fromCode(\"FILE_NOT_FOUND\");\n *\n * // Create with custom details\n * const customError = UploadistaError.fromCode(\"FLOW_NODE_ERROR\", {\n * body: \"Failed to process image\",\n * cause: originalError,\n * details: { nodeId: \"resize-1\", fileId: \"abc123\" }\n * });\n *\n * // Use with Effect\n * const effect = customError.toEffect<void>();\n *\n * // In an Effect pipeline\n * return Effect.gen(function* () {\n * const file = yield* getFile(id);\n * if (!file) {\n * return yield* UploadistaError.fromCode(\"FILE_NOT_FOUND\").toEffect();\n * }\n * return file;\n * });\n * ```\n */\nexport class UploadistaError extends Data.TaggedError(\"UploadistaError\") {\n readonly code: string;\n readonly status: number;\n // Keep legacy property names for backward compatibility\n readonly status_code: number;\n readonly body: string;\n readonly details?: unknown;\n\n constructor({\n code,\n status,\n body,\n cause,\n details,\n }: {\n code: UploadistaErrorCode | string;\n status: number;\n body: string;\n cause?: unknown;\n details?: unknown;\n }) {\n super();\n this.name = \"UploadistaError\";\n this.code = code;\n this.status = status;\n this.status_code = status; // legacy alias\n this.body = body;\n this.details = details;\n if (cause) (this as unknown as { cause?: unknown }).cause = cause;\n }\n\n /**\n * Creates an UploadistaError from a predefined error code.\n *\n * This is the primary way to create errors in the Uploadista system. Each error code\n * has a default status and message defined in ERROR_CATALOG, but these can be overridden\n * for specific use cases.\n *\n * @param code - One of the predefined error codes from UploadistaErrorCode\n * @param overrides - Optional overrides for the default error properties\n * @param overrides.status - Custom HTTP status code (overrides the default)\n * @param overrides.body - Custom error message (overrides the default)\n * @param overrides.details - Additional structured data about the error\n * @param overrides.cause - The underlying error that caused this error (for error chaining)\n *\n * @returns A new UploadistaError instance\n *\n * @example\n * ```typescript\n * // Use default error\n * const error = UploadistaError.fromCode(\"FILE_NOT_FOUND\");\n *\n * // Override message\n * const customError = UploadistaError.fromCode(\"FILE_NOT_FOUND\", {\n * body: `File with ID ${fileId} was not found in storage`\n * });\n *\n * // Include cause and details\n * const detailedError = UploadistaError.fromCode(\"DATASTORE_NOT_FOUND\", {\n * cause: storageException,\n * details: { storageId: \"s3-prod\", region: \"us-east-1\" }\n * });\n * ```\n */\n static fromCode(\n code: UploadistaErrorCode,\n overrides?: Partial<Pick<UploadistaError, \"status\" | \"body\">> & {\n details?: unknown;\n cause?: unknown;\n }\n ): UploadistaError {\n const base = ERROR_CATALOG[code];\n return new UploadistaError({\n code,\n status: overrides?.status ?? base.status,\n body: overrides?.body ?? base.body,\n details: overrides?.details,\n cause: overrides?.cause,\n });\n }\n\n /**\n * Converts this error to an Effect that immediately fails.\n *\n * This method integrates UploadistaError with Effect-TS's error handling system,\n * allowing errors to be used in Effect pipelines with proper type checking.\n *\n * @template T - The success type of the Effect (defaults to never since it always fails)\n * @returns An Effect that fails with this UploadistaError\n *\n * @example\n * ```typescript\n * const error = UploadistaError.fromCode(\"FILE_NOT_FOUND\");\n *\n * // Use in an Effect pipeline\n * return Effect.gen(function* () {\n * const file = yield* kvStore.get(fileId);\n * if (!file) {\n * return yield* error.toEffect();\n * }\n * return file;\n * });\n * ```\n */\n toEffect<T = never>(): Effect.Effect<T, UploadistaError> {\n return Effect.fail(this);\n }\n}\n\n/**\n * Type guard to check if an unknown value is an UploadistaError.\n *\n * Useful for error handling when catching errors that might be from\n * different sources or libraries.\n *\n * @param error - The value to check\n * @returns True if the value is an UploadistaError instance\n *\n * @example\n * ```typescript\n * try {\n * await someOperation();\n * } catch (error) {\n * if (isUploadistaError(error)) {\n * console.log(`Uploadista error: ${error.code} (${error.status})`);\n * console.log(error.body);\n * } else {\n * console.error(\"Unknown error:\", error);\n * }\n * }\n * ```\n */\nexport function isUploadistaError(error: unknown): error is UploadistaError {\n return error instanceof UploadistaError;\n}\n\n/**\n * Creates an Effect that immediately fails with an UploadistaError.\n *\n * This is a convenience function that combines error creation with Effect conversion.\n * It's equivalent to calling `UploadistaError.fromCode(code, overrides).toEffect()`.\n *\n * @param code - One of the predefined error codes from UploadistaErrorCode\n * @param overrides - Optional overrides for the default error properties\n * @param overrides.status - Custom HTTP status code\n * @param overrides.body - Custom error message\n * @param overrides.details - Additional structured data about the error\n * @param overrides.cause - The underlying error that caused this error\n *\n * @returns An Effect that immediately fails with the created UploadistaError\n *\n * @example\n * ```typescript\n * // In an Effect pipeline\n * return Effect.gen(function* () {\n * const file = yield* kvStore.get(fileId);\n * if (!file) {\n * return yield* httpFailure(\"FILE_NOT_FOUND\", {\n * details: { fileId }\n * });\n * }\n * return file;\n * });\n * ```\n */\nexport function httpFailure(\n code: UploadistaErrorCode,\n overrides?: Partial<Pick<UploadistaError, \"status\" | \"body\">> & {\n details?: unknown;\n cause?: unknown;\n }\n): Effect.Effect<never, UploadistaError> {\n return UploadistaError.fromCode(code, overrides).toEffect();\n}\n"],"mappings":"0CAgEA,MAAaA,EAET,CACF,eAAgB,CAAE,OAAQ,IAAK,KAAM;EAAmC,CACxE,QAAS,CAAE,OAAQ,IAAK,KAAM,uCAAwC,CACtE,oBAAqB,CACnB,OAAQ,IACR,KAAM,+CACP,CACD,iBAAkB,CAChB,OAAQ,IACR,KAAM,wCACP,CACD,qBAAsB,CACpB,OAAQ,IACR,KAAM;EACP,CACD,oBAAqB,CACnB,OAAQ,IACR,KAAM;EACP,CACD,oBAAqB,CACnB,OAAQ,IACR,KAAM;EACP,CACD,eAAgB,CACd,OAAQ,IACR,KAAM;EACP,CACD,oBAAqB,CACnB,OAAQ,IACR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