@uploadista/core 0.0.20 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/dist/{checksum-DVPe3Db4.cjs → checksum-CTpNXWEL.cjs} +1 -1
  2. package/dist/errors/index.cjs +1 -1
  3. package/dist/errors/index.d.mts +2 -2
  4. package/dist/flow/index.cjs +1 -1
  5. package/dist/flow/index.d.cts +2 -2
  6. package/dist/flow/index.d.mts +6 -6
  7. package/dist/flow/index.mjs +1 -1
  8. package/dist/flow-CA8xO6wP.mjs +2 -0
  9. package/dist/flow-CA8xO6wP.mjs.map +1 -0
  10. package/dist/flow-DKJaCPxL.cjs +1 -0
  11. package/dist/index-9gyMMEIB.d.cts.map +1 -1
  12. package/dist/{index-RuQUCROH.d.mts → index-BKY0VjsL.d.mts} +230 -169
  13. package/dist/index-BKY0VjsL.d.mts.map +1 -0
  14. package/dist/{index-B9V5SSxl.d.mts → index-D8MZ6P3o.d.mts} +2 -2
  15. package/dist/{index-B9V5SSxl.d.mts.map → index-D8MZ6P3o.d.mts.map} +1 -1
  16. package/dist/{index-BFSHumky.d.mts → index-DQuMQssI.d.mts} +2 -2
  17. package/dist/{index-BFSHumky.d.mts.map → index-DQuMQssI.d.mts.map} +1 -1
  18. package/dist/{index-DMqaf28W.d.cts → index-j_n72QK0.d.cts} +228 -167
  19. package/dist/index-j_n72QK0.d.cts.map +1 -0
  20. package/dist/index.cjs +1 -1
  21. package/dist/index.d.cts +2 -2
  22. package/dist/index.d.mts +6 -6
  23. package/dist/index.mjs +1 -1
  24. package/dist/{stream-limiter-BvkaZXcz.cjs → stream-limiter-DH0vv46_.cjs} +1 -1
  25. package/dist/streams/index.cjs +1 -1
  26. package/dist/streams/index.d.mts +2 -2
  27. package/dist/streams/index.mjs +1 -1
  28. package/dist/testing/index.cjs +2 -2
  29. package/dist/testing/index.d.cts +1 -1
  30. package/dist/testing/index.d.cts.map +1 -1
  31. package/dist/testing/index.d.mts +5 -5
  32. package/dist/testing/index.d.mts.map +1 -1
  33. package/dist/testing/index.mjs +2 -2
  34. package/dist/testing/index.mjs.map +1 -1
  35. package/dist/types/index.cjs +1 -1
  36. package/dist/types/index.d.cts +2 -2
  37. package/dist/types/index.d.mts +6 -6
  38. package/dist/types/index.mjs +1 -1
  39. package/dist/types-BF_tvkRh.cjs +1 -0
  40. package/dist/types-BRnwrJDg.mjs +2 -0
  41. package/dist/types-BRnwrJDg.mjs.map +1 -0
  42. package/dist/upload/index.cjs +1 -1
  43. package/dist/upload/index.d.cts +1 -1
  44. package/dist/upload/index.d.mts +5 -5
  45. package/dist/upload/index.mjs +1 -1
  46. package/dist/upload-CLHJ1SFS.cjs +1 -0
  47. package/dist/upload-CpsShjP3.mjs +2 -0
  48. package/dist/upload-CpsShjP3.mjs.map +1 -0
  49. package/dist/{uploadista-error-DR0XimpE.d.mts → uploadista-error-B1qbOy9N.d.mts} +1 -1
  50. package/dist/{uploadista-error-DR0XimpE.d.mts.map → uploadista-error-B1qbOy9N.d.mts.map} +1 -1
  51. package/dist/{uploadista-error-BgQU45we.cjs → uploadista-error-CLWoRAAr.cjs} +1 -1
  52. package/dist/uploadista-error-CkSxSyNo.mjs.map +1 -1
  53. package/dist/utils/index.cjs +1 -1
  54. package/dist/utils/index.d.mts +2 -2
  55. package/dist/utils/index.mjs +1 -1
  56. package/dist/{utils-UUJt8ILJ.cjs → utils-CvZJUNEo.cjs} +1 -1
  57. package/dist/{utils-B-ZhQ6b0.mjs → utils-DVwfrVBJ.mjs} +1 -1
  58. package/dist/utils-DVwfrVBJ.mjs.map +1 -0
  59. package/package.json +8 -8
  60. package/src/flow/circuit-breaker-store.ts +7 -8
  61. package/src/flow/flow.ts +6 -5
  62. package/src/flow/nodes/transform-node.ts +15 -1
  63. package/src/flow/plugins/image-plugin.ts +12 -3
  64. package/src/flow/plugins/video-plugin.ts +12 -3
  65. package/src/flow/types/flow-types.ts +75 -6
  66. package/src/flow/types/retry-policy.ts +5 -2
  67. package/src/flow/types/type-utils.ts +4 -6
  68. package/src/flow/utils/file-naming.ts +36 -11
  69. package/src/testing/mock-upload-engine.ts +18 -1
  70. package/src/types/circuit-breaker-store.ts +2 -2
  71. package/src/types/data-store.ts +4 -1
  72. package/src/types/kv-store.ts +13 -12
  73. package/src/types/upload-file.ts +29 -4
  74. package/src/upload/upload-chunk.ts +1 -1
  75. package/dist/flow-BHVkk_6W.cjs +0 -1
  76. package/dist/flow-DlhHOlMk.mjs +0 -2
  77. package/dist/flow-DlhHOlMk.mjs.map +0 -1
  78. package/dist/index-DMqaf28W.d.cts.map +0 -1
  79. package/dist/index-RuQUCROH.d.mts.map +0 -1
  80. package/dist/streams-BiD_pOPH.cjs +0 -0
  81. package/dist/streams-Cqjxk2rI.mjs +0 -1
  82. package/dist/types-Cws60JHC.cjs +0 -1
  83. package/dist/types-DKGQJIEr.mjs +0 -2
  84. package/dist/types-DKGQJIEr.mjs.map +0 -1
  85. package/dist/upload-C-C7hn1-.mjs +0 -2
  86. package/dist/upload-C-C7hn1-.mjs.map +0 -1
  87. package/dist/upload-DWBlRXHh.cjs +0 -1
  88. package/dist/utils-B-ZhQ6b0.mjs.map +0 -1
  89. /package/dist/{index-C-svZlpj.d.mts → index-DWe68pTi.d.mts} +0 -0
@@ -1,4 +1,4 @@
1
- import"../uploadista-error-CkSxSyNo.mjs";import"../errors-CtPUOWNd.mjs";import{A as e,M as t,a as n,i as r,j as i,k as a,r as o}from"../flow-DlhHOlMk.mjs";import{b as s}from"../types-DKGQJIEr.mjs";import{n as c}from"../upload-C-C7hn1-.mjs";import"../checksum-COoD-F1l.mjs";import"../stream-limiter-B9nsn2gb.mjs";import{Effect as l,Layer as u,Stream as d}from"effect";const f=u.succeed(t,t.of({performOCR:(e,t,n)=>l.sync(()=>({extractedText:t.taskType===`convertToMarkdown`?`# Document Title
1
+ import"../uploadista-error-CkSxSyNo.mjs";import"../errors-CtPUOWNd.mjs";import{A as e,M as t,a as n,i as r,j as i,k as a,r as o}from"../flow-CA8xO6wP.mjs";import{b as s}from"../types-BRnwrJDg.mjs";import{n as c}from"../upload-CpsShjP3.mjs";import"../checksum-COoD-F1l.mjs";import"../stream-limiter-B9nsn2gb.mjs";import{Effect as l,Layer as u,Stream as d}from"effect";const f=u.succeed(t,t.of({performOCR:(e,t,n)=>l.sync(()=>({extractedText:t.taskType===`convertToMarkdown`?`# Document Title
2
2
 
3
3
  This is a paragraph with **bold** text.
4
4
 
@@ -6,5 +6,5 @@ This is a paragraph with **bold** text.
6
6
 
7
7
  - List item 1
8
8
  - List item 2`:`Plain text extracted from document without formatting.`,format:t.taskType===`convertToMarkdown`?`markdown`:`plain`,confidence:.95}))})),p=u.succeed(i,i.of({extractText:e=>l.sync(()=>`This is extracted text from a PDF document.
9
- Page 1 content.`),splitPdf:(e,t)=>l.sync(()=>t.mode===`range`?{mode:`range`,pdf:new Uint8Array(500).fill(80)}:{mode:`individual`,pdfs:[new Uint8Array(200).fill(81),new Uint8Array(200).fill(82),new Uint8Array(200).fill(83)]}),mergePdfs:e=>l.sync(()=>{let t=e.pdfs.reduce((e,t)=>e+t.byteLength,0);return new Uint8Array(t).fill(90)}),getMetadata:e=>l.sync(()=>({pageCount:5,format:`pdf`,author:`Test Author`,title:`Test Document`,subject:`Test Subject`,creator:`Test Creator`,creationDate:`2024-01-01T00:00:00Z`,modifiedDate:`2024-01-02T00:00:00Z`,fileSize:e.byteLength}))})),m=u.succeed(e,e.of({removeBackground:(e,t)=>l.sync(()=>({outputUrl:e.replace(`.jpg`,`-no-bg.png`)})),describeImage:(e,t)=>l.sync(()=>({description:`A test image from ${e}`}))})),h=u.succeed(a,a.of({optimize:(e,t)=>l.sync(()=>{let n=t.quality/100,r=Math.floor(e.byteLength*n);return new Uint8Array(r).fill(128)}),resize:(e,t)=>l.sync(()=>{let e=t.width||800,n=t.height||600,r=Math.floor(e*n/10);return new Uint8Array(r).fill(100)}),transform:(e,t)=>l.sync(()=>t.type===`rotate`&&t.angle===90?new Uint8Array(e.byteLength+10).fill(150):t.type===`blur`?new Uint8Array(e.byteLength).fill(180):t.type===`grayscale`?new Uint8Array(e.byteLength).fill(128):new Uint8Array(e.byteLength).fill(200))})),g=u.succeed(c,c.of({read:(e,t)=>l.sync(()=>{let t=`Content of file ${e}`;return new TextEncoder().encode(t)}),readStream:(e,t,n)=>l.sync(()=>{let t={...s,...n},r=`Content of file ${e}`,i=new TextEncoder().encode(r),a=t.chunkSize,o=[];for(let e=0;e<i.length;e+=a)o.push(i.slice(e,e+a));return d.fromIterable(o)}),uploadStream:(e,t,n)=>l.gen(function*(){let t=[];yield*d.runForEach(n,e=>l.sync(()=>{t.push(e)}));let r=t.reduce((e,t)=>e+t.length,0),i=typeof e.metadata==`string`?JSON.parse(e.metadata):e.metadata||{},a=e.fileName?e.fileName.split(`.`).pop():i.extension,o=`stream-uploaded-${Date.now()}-${Math.random().toString(36).substring(7)}`;return{id:o,offset:r,size:r,storage:{id:e.storageId,type:`memory`},metadata:{...i,mimeType:e.type,type:e.type,"content-type":e.type,fileName:e.fileName,originalName:e.fileName,name:e.fileName,extension:a},url:`http://test-storage/${o}`,creationDate:new Date().toISOString()}}),upload:(e,t,n)=>l.gen(function*(){let t=n.getReader(),r=0,i=[];for(;;){let{done:e,value:n}=yield*l.promise(()=>t.read());if(e)break;n&&(i.push(n),r+=n.byteLength)}let a=typeof e.metadata==`string`?JSON.parse(e.metadata):e.metadata||{},o=e.fileName?e.fileName.split(`.`).pop():a.extension;return{id:`uploaded-${Date.now()}-${Math.random().toString(36).substring(7)}`,offset:r,size:r,storage:{id:e.storageId,type:`memory`},metadata:{...a,mimeType:e.type,type:e.type,"content-type":e.type,fileName:e.fileName,originalName:e.fileName,name:e.fileName,extension:o},creationDate:new Date().toISOString()}}),delete:(e,t)=>l.void,createUpload:(e,t)=>l.succeed({id:`uploaded-${Date.now()}-${Math.random().toString(36).substring(7)}`,offset:0,size:0,storage:{id:e.storageId,type:`memory`},metadata:typeof e.metadata==`string`?JSON.parse(e.metadata):e.metadata}),uploadChunk:(e,t,n)=>l.gen(function*(){let t=n.getReader(),r=0,i=[];for(;;){let{done:e,value:n}=yield*l.promise(()=>t.read());if(e)break;n&&(i.push(n),r+=n.byteLength)}return{id:e,offset:r,size:r,storage:{id:`test-storage`,type:`memory`},metadata:{mimeType:`application/octet-stream`,extension:`bin`},creationDate:new Date().toISOString()}}),getCapabilities:(e,t)=>l.succeed({supportsParallelUploads:!0,supportsConcatenation:!0,supportsDeferredLength:!0,supportsResumableUploads:!0,supportsTransactionalUploads:!1,supportsStreamingRead:!0,supportsStreamingWrite:!0,maxConcurrentUploads:10,minChunkSize:5*1024*1024,maxChunkSize:100*1024*1024,maxParts:1e4,optimalChunkSize:10*1024*1024,requiresOrderedChunks:!1,requiresMimeTypeValidation:!1}),uploadFromUrl:(e,t,n)=>l.succeed({id:`uploaded-from-url-${Date.now()}-${Math.random().toString(36).substring(7)}`,offset:0,size:0,storage:{id:e.storageId,type:`memory`},metadata:typeof e.metadata==`string`?JSON.parse(e.metadata):e.metadata,url:n,creationDate:new Date().toISOString()}),getUpload:e=>l.succeed({id:e,offset:0,size:1024,storage:{id:`test-storage`,type:`memory`},metadata:{mimeType:`text/plain`,originalName:`file-${e}.txt`,extension:`txt`},creationDate:new Date().toISOString()}),subscribeToUploadEvents:(e,t)=>l.void,unsubscribeFromUploadEvents:e=>l.void})),_=u.succeed(n,n.of({describe:e=>l.sync(()=>({duration:120,width:1920,height:1080,codec:`h264`,format:`mp4`,bitrate:5e6,frameRate:30,aspectRatio:`16:9`,hasAudio:!0,audioCodec:`aac`,audioBitrate:128e3,size:e.byteLength})),transcode:(e,t)=>l.sync(()=>{let n=1;t.codec===`vp9`?n=.8:t.codec===`h265`&&(n=.7);let r=Math.floor(e.byteLength*n);return new Uint8Array(r).fill(42)}),resize:(e,t)=>l.sync(()=>{let e=t.width||1280,n=t.height||720,r=Math.floor(e*n/50);return new Uint8Array(r).fill(84)}),trim:(e,t)=>l.sync(()=>{let n;n=t.duration===void 0?t.endTime===void 0?120-t.startTime:t.endTime-t.startTime:t.duration;let r=n/120,i=Math.floor(e.byteLength*r);return new Uint8Array(i).fill(63)}),extractFrame:(e,t)=>l.sync(()=>{let e=(t.format||`jpeg`)===`png`?5e4:3e4;return new Uint8Array(e).fill(255)})})),v=u.succeed(r,r.of({scan:e=>l.sync(()=>new TextDecoder().decode(e).includes(`X5O!P%@AP[4\\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*`)?{isClean:!1,detectedViruses:[`EICAR-Test-File`]}:{isClean:!0,detectedViruses:[]}),getVersion:()=>l.sync(()=>`TestVirusScanPlugin 1.0.0`)})),y=u.succeed(o,o.of({zip:(e,t)=>l.gen(function*(){let n=e.map(e=>({id:e.id,size:e.data.byteLength})),r=JSON.stringify({zipName:t.zipName,includeMetadata:t.includeMetadata,files:n});return new TextEncoder().encode(r)})}));export{f as TestDocumentAiPlugin,p as TestDocumentPlugin,m as TestImageAiPlugin,h as TestImagePlugin,g as TestUploadEngine,_ as TestVideoPlugin,v as TestVirusScanPlugin,y as TestZipPlugin};
9
+ Page 1 content.`),splitPdf:(e,t)=>l.sync(()=>t.mode===`range`?{mode:`range`,pdf:new Uint8Array(500).fill(80)}:{mode:`individual`,pdfs:[new Uint8Array(200).fill(81),new Uint8Array(200).fill(82),new Uint8Array(200).fill(83)]}),mergePdfs:e=>l.sync(()=>{let t=e.pdfs.reduce((e,t)=>e+t.byteLength,0);return new Uint8Array(t).fill(90)}),getMetadata:e=>l.sync(()=>({pageCount:5,format:`pdf`,author:`Test Author`,title:`Test Document`,subject:`Test Subject`,creator:`Test Creator`,creationDate:`2024-01-01T00:00:00Z`,modifiedDate:`2024-01-02T00:00:00Z`,fileSize:e.byteLength}))})),m=u.succeed(e,e.of({removeBackground:(e,t)=>l.sync(()=>({outputUrl:e.replace(`.jpg`,`-no-bg.png`)})),describeImage:(e,t)=>l.sync(()=>({description:`A test image from ${e}`}))})),h=u.succeed(a,a.of({optimize:(e,t)=>l.sync(()=>{let n=t.quality/100,r=Math.floor(e.byteLength*n);return new Uint8Array(r).fill(128)}),resize:(e,t)=>l.sync(()=>{let e=t.width||800,n=t.height||600,r=Math.floor(e*n/10);return new Uint8Array(r).fill(100)}),transform:(e,t)=>l.sync(()=>t.type===`rotate`&&t.angle===90?new Uint8Array(e.byteLength+10).fill(150):t.type===`blur`?new Uint8Array(e.byteLength).fill(180):t.type===`grayscale`?new Uint8Array(e.byteLength).fill(128):new Uint8Array(e.byteLength).fill(200))})),g=u.succeed(c,c.of({read:(e,t)=>l.sync(()=>{if(e.toLowerCase().includes(`infected`)||e.toLowerCase().includes(`virus`)||e.toLowerCase().includes(`malware`)||e.toLowerCase().includes(`eicar`))return new TextEncoder().encode(`X5O!P%@AP[4\\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*`);let t=`Content of file ${e}`;return new TextEncoder().encode(t)}),readStream:(e,t,n)=>l.sync(()=>{let t={...s,...n},r=`Content of file ${e}`,i=new TextEncoder().encode(r),a=t.chunkSize,o=[];for(let e=0;e<i.length;e+=a)o.push(i.slice(e,e+a));return d.fromIterable(o)}),uploadStream:(e,t,n)=>l.gen(function*(){let t=[];yield*d.runForEach(n,e=>l.sync(()=>{t.push(e)}));let r=t.reduce((e,t)=>e+t.length,0),i=typeof e.metadata==`string`?JSON.parse(e.metadata):e.metadata||{},a=e.fileName?e.fileName.split(`.`).pop():i.extension,o=`stream-uploaded-${Date.now()}-${Math.random().toString(36).substring(7)}`;return{id:o,offset:r,size:r,storage:{id:e.storageId,type:`memory`},metadata:{...i,mimeType:e.type,type:e.type,"content-type":e.type,fileName:e.fileName,originalName:e.fileName,name:e.fileName,extension:a},url:`http://test-storage/${o}`,creationDate:new Date().toISOString()}}),upload:(e,t,n)=>l.gen(function*(){let t=n.getReader(),r=0,i=[];for(;;){let{done:e,value:n}=yield*l.promise(()=>t.read());if(e)break;n&&(i.push(n),r+=n.byteLength)}let a=typeof e.metadata==`string`?JSON.parse(e.metadata):e.metadata||{},o=e.fileName?e.fileName.split(`.`).pop():a.extension;return{id:`uploaded-${Date.now()}-${Math.random().toString(36).substring(7)}`,offset:r,size:r,storage:{id:e.storageId,type:`memory`},metadata:{...a,mimeType:e.type,type:e.type,"content-type":e.type,fileName:e.fileName,originalName:e.fileName,name:e.fileName,extension:o},creationDate:new Date().toISOString()}}),delete:(e,t)=>l.void,createUpload:(e,t)=>l.succeed({id:`uploaded-${Date.now()}-${Math.random().toString(36).substring(7)}`,offset:0,size:0,storage:{id:e.storageId,type:`memory`},metadata:typeof e.metadata==`string`?JSON.parse(e.metadata):e.metadata}),uploadChunk:(e,t,n)=>l.gen(function*(){let t=n.getReader(),r=0,i=[];for(;;){let{done:e,value:n}=yield*l.promise(()=>t.read());if(e)break;n&&(i.push(n),r+=n.byteLength)}return{id:e,offset:r,size:r,storage:{id:`test-storage`,type:`memory`},metadata:{mimeType:`application/octet-stream`,extension:`bin`},creationDate:new Date().toISOString()}}),getCapabilities:(e,t)=>l.succeed({supportsParallelUploads:!0,supportsConcatenation:!0,supportsDeferredLength:!0,supportsResumableUploads:!0,supportsTransactionalUploads:!1,supportsStreamingRead:!0,supportsStreamingWrite:!0,maxConcurrentUploads:10,minChunkSize:5*1024*1024,maxChunkSize:100*1024*1024,maxParts:1e4,optimalChunkSize:10*1024*1024,requiresOrderedChunks:!1,requiresMimeTypeValidation:!1}),uploadFromUrl:(e,t,n)=>l.succeed({id:`uploaded-from-url-${Date.now()}-${Math.random().toString(36).substring(7)}`,offset:0,size:0,storage:{id:e.storageId,type:`memory`},metadata:typeof e.metadata==`string`?JSON.parse(e.metadata):e.metadata,url:n,creationDate:new Date().toISOString()}),getUpload:e=>l.succeed({id:e,offset:0,size:1024,storage:{id:`test-storage`,type:`memory`},metadata:{mimeType:`text/plain`,originalName:`file-${e}.txt`,extension:`txt`},creationDate:new Date().toISOString()}),subscribeToUploadEvents:(e,t)=>l.void,unsubscribeFromUploadEvents:e=>l.void})),_=u.succeed(n,n.of({describe:e=>l.sync(()=>({duration:120,width:1920,height:1080,codec:`h264`,format:`mp4`,bitrate:5e6,frameRate:30,aspectRatio:`16:9`,hasAudio:!0,audioCodec:`aac`,audioBitrate:128e3,size:e.byteLength})),transcode:(e,t)=>l.sync(()=>{let n=1;t.codec===`vp9`?n=.8:t.codec===`h265`&&(n=.7);let r=Math.floor(e.byteLength*n);return new Uint8Array(r).fill(42)}),resize:(e,t)=>l.sync(()=>{let e=t.width||1280,n=t.height||720,r=Math.floor(e*n/50);return new Uint8Array(r).fill(84)}),trim:(e,t)=>l.sync(()=>{let n;n=t.duration===void 0?t.endTime===void 0?120-t.startTime:t.endTime-t.startTime:t.duration;let r=n/120,i=Math.floor(e.byteLength*r);return new Uint8Array(i).fill(63)}),extractFrame:(e,t)=>l.sync(()=>{let e=(t.format||`jpeg`)===`png`?5e4:3e4;return new Uint8Array(e).fill(255)})})),v=u.succeed(r,r.of({scan:e=>l.sync(()=>new TextDecoder().decode(e).includes(`X5O!P%@AP[4\\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*`)?{isClean:!1,detectedViruses:[`EICAR-Test-File`]}:{isClean:!0,detectedViruses:[]}),getVersion:()=>l.sync(()=>`TestVirusScanPlugin 1.0.0`)})),y=u.succeed(o,o.of({zip:(e,t)=>l.gen(function*(){let n=e.map(e=>({id:e.id,size:e.data.byteLength})),r=JSON.stringify({zipName:t.zipName,includeMetadata:t.includeMetadata,files:n});return new TextEncoder().encode(r)})}));export{f as TestDocumentAiPlugin,p as TestDocumentPlugin,m as TestImageAiPlugin,h as TestImagePlugin,g as TestUploadEngine,_ as TestVideoPlugin,v as TestVirusScanPlugin,y as TestZipPlugin};
10
10
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["chunks: Uint8Array[]","duration: number"],"sources":["../../src/testing/mock-document-ai-plugin.ts","../../src/testing/mock-document-plugin.ts","../../src/testing/mock-image-ai-plugin.ts","../../src/testing/mock-image-plugin.ts","../../src/testing/mock-upload-engine.ts","../../src/testing/mock-video-plugin.ts","../../src/testing/mock-virus-scan-plugin.ts","../../src/testing/mock-zip-plugin.ts"],"sourcesContent":["import { Effect, Layer } from \"effect\";\nimport type { OcrResult } from \"../flow\";\nimport { DocumentAiPlugin } from \"../flow\";\n\n/**\n * Mock DocumentAiPlugin implementation for testing.\n *\n * Provides simple mock implementations of AI document operations.\n *\n * @example\n * ```typescript\n * import { TestDocumentAiPlugin } from \"@uploadista/core/testing\";\n *\n * const program = Effect.gen(function* () {\n * const plugin = yield* DocumentAiPlugin;\n * const result = yield* plugin.performOCR(\n * \"https://example.com/doc.pdf\",\n * { taskType: \"convertToMarkdown\", resolution: \"gundam\" },\n * { clientId: \"test-client\" }\n * );\n * return result;\n * }).pipe(Effect.provide(TestDocumentAiPlugin));\n * ```\n */\nexport const TestDocumentAiPlugin = Layer.succeed(\n DocumentAiPlugin,\n DocumentAiPlugin.of({\n performOCR: (inputUrl: string, params, context) =>\n Effect.sync(() => {\n const result: OcrResult = {\n extractedText:\n params.taskType === \"convertToMarkdown\"\n ? \"# Document Title\\n\\nThis is a paragraph with **bold** text.\\n\\n## Section 2\\n\\n- List item 1\\n- List item 2\"\n : \"Plain text extracted from document without formatting.\",\n format:\n params.taskType === \"convertToMarkdown\" ? \"markdown\" : \"plain\",\n confidence: 0.95,\n };\n return result;\n }),\n }),\n);\n","import { Effect, Layer } from \"effect\";\nimport type { DocumentMetadata, SplitPdfResult } from \"../flow\";\nimport { DocumentPlugin } from \"../flow\";\n\n/**\n * Mock DocumentPlugin implementation for testing.\n *\n * Provides simple mock implementations of PDF operations that return mock data.\n *\n * @example\n * ```typescript\n * import { TestDocumentPlugin } from \"@uploadista/core/testing\";\n *\n * const program = Effect.gen(function* () {\n * const plugin = yield* DocumentPlugin;\n * const text = yield* plugin.extractText(pdfBytes);\n * return text;\n * }).pipe(Effect.provide(TestDocumentPlugin));\n * ```\n */\nexport const TestDocumentPlugin = Layer.succeed(\n DocumentPlugin,\n DocumentPlugin.of({\n extractText: (input: Uint8Array) =>\n Effect.sync(() => {\n // Mock text extraction\n return \"This is extracted text from a PDF document.\\nPage 1 content.\";\n }),\n splitPdf: (input: Uint8Array, options) =>\n Effect.sync(() => {\n if (options.mode === \"range\") {\n // Mock range split\n const mockPdf = new Uint8Array(500).fill(80);\n return {\n mode: \"range\" as const,\n pdf: mockPdf,\n } satisfies SplitPdfResult;\n }\n // Mock individual split\n const mockPdfs = [\n new Uint8Array(200).fill(81),\n new Uint8Array(200).fill(82),\n new Uint8Array(200).fill(83),\n ];\n return {\n mode: \"individual\" as const,\n pdfs: mockPdfs,\n } satisfies SplitPdfResult;\n }),\n mergePdfs: (options) =>\n Effect.sync(() => {\n // Mock merge: combine sizes\n const totalSize = options.pdfs.reduce(\n (sum, pdf) => sum + pdf.byteLength,\n 0,\n );\n return new Uint8Array(totalSize).fill(90);\n }),\n getMetadata: (input: Uint8Array) =>\n Effect.sync(() => {\n const metadata: DocumentMetadata = {\n pageCount: 5,\n format: \"pdf\",\n author: \"Test Author\",\n title: \"Test Document\",\n subject: \"Test Subject\",\n creator: \"Test Creator\",\n creationDate: \"2024-01-01T00:00:00Z\",\n modifiedDate: \"2024-01-02T00:00:00Z\",\n fileSize: input.byteLength,\n };\n return metadata;\n }),\n }),\n);\n","import { Effect, Layer } from \"effect\";\nimport { ImageAiPlugin } from \"../flow\";\n\n/**\n * Mock ImageAiPlugin implementation for testing.\n *\n * Provides simple mock implementations of AI-powered image operations\n * like background removal and image description.\n *\n * @example\n * ```typescript\n * import { TestImageAiPlugin } from \"@uploadista/core/testing\";\n *\n * const program = Effect.gen(function* () {\n * const plugin = yield* ImageAiPlugin;\n * const result = yield* plugin.removeBackground(imageUrl, context);\n * return result;\n * }).pipe(Effect.provide(TestImageAiPlugin));\n * ```\n */\nexport const TestImageAiPlugin = Layer.succeed(\n ImageAiPlugin,\n ImageAiPlugin.of({\n removeBackground: (inputUrl: string, _context) =>\n Effect.sync(() => ({\n outputUrl: inputUrl.replace(\".jpg\", \"-no-bg.png\"),\n })),\n describeImage: (inputUrl: string, _context) =>\n Effect.sync(() => ({\n description: `A test image from ${inputUrl}`,\n })),\n }),\n);\n","import { Effect, Layer } from \"effect\";\nimport { ImagePlugin } from \"../flow\";\n\n/**\n * Mock ImagePlugin implementation for testing.\n *\n * Provides simple mock implementations of image optimization, resizing,\n * and transformation operations that return mock Uint8Array data.\n *\n * @example\n * ```typescript\n * import { TestImagePlugin } from \"@uploadista/core/testing\";\n *\n * const program = Effect.gen(function* () {\n * const plugin = yield* ImagePlugin;\n * const optimized = yield* plugin.optimize(imageBytes, { quality: 80, format: \"webp\" });\n * return optimized;\n * }).pipe(Effect.provide(TestImagePlugin));\n * ```\n */\nexport const TestImagePlugin = Layer.succeed(\n ImagePlugin,\n ImagePlugin.of({\n optimize: (input: Uint8Array, options) =>\n Effect.sync(() => {\n // Mock optimize: return smaller array for lower quality\n const sizeMultiplier = options.quality / 100;\n const newSize = Math.floor(input.byteLength * sizeMultiplier);\n return new Uint8Array(newSize).fill(128);\n }),\n resize: (input: Uint8Array, options) =>\n Effect.sync(() => {\n // Mock resize: return array with size based on dimensions\n const width = options.width || 800;\n const height = options.height || 600;\n const mockSize = Math.floor((width * height) / 10);\n return new Uint8Array(mockSize).fill(100);\n }),\n transform: (input: Uint8Array, transformation) =>\n Effect.sync(() => {\n // Mock transform: modify array based on transformation type\n if (transformation.type === \"rotate\" && transformation.angle === 90) {\n // For 90° rotation, swap dimensions (mock behavior)\n return new Uint8Array(input.byteLength + 10).fill(150);\n }\n if (transformation.type === \"blur\") {\n return new Uint8Array(input.byteLength).fill(180);\n }\n if (transformation.type === \"grayscale\") {\n return new Uint8Array(input.byteLength).fill(128);\n }\n // Default: return modified copy\n return new Uint8Array(input.byteLength).fill(200);\n }),\n }),\n);\n","import { Effect, Layer, Stream } from \"effect\";\nimport type { UploadistaError } from \"../errors\";\nimport type { InputFile, UploadFile, WebSocketConnection } from \"../types\";\nimport {\n type DataStoreCapabilities,\n DEFAULT_STREAMING_CONFIG,\n type StreamingConfig,\n} from \"../types/data-store\";\nimport { UploadEngine } from \"../upload\";\n\n/**\n * Mock UploadEngine implementation for testing.\n *\n * Provides a complete in-memory implementation of all UploadEngine methods\n * suitable for unit and integration tests.\n *\n * @example\n * ```typescript\n * import { TestUploadEngine } from \"@uploadista/core/testing\";\n *\n * const program = Effect.gen(function* () {\n * const server = yield* UploadEngine;\n * const upload = yield* server.createUpload(inputFile, \"client-123\");\n * return upload;\n * }).pipe(Effect.provide(TestUploadEngine));\n * ```\n */\nexport const TestUploadEngine = Layer.succeed(\n UploadEngine,\n UploadEngine.of({\n read: (fileId: string, _clientId: string | null) =>\n Effect.sync(() => {\n // Generate mock file data based on fileId\n const text = `Content of file ${fileId}`;\n return new TextEncoder().encode(text);\n }),\n readStream: (\n fileId: string,\n _clientId: string | null,\n config?: StreamingConfig,\n ) =>\n Effect.sync(() => {\n const effectiveConfig = { ...DEFAULT_STREAMING_CONFIG, ...config };\n // Generate mock file data based on fileId\n const text = `Content of file ${fileId}`;\n const fullData = new TextEncoder().encode(text);\n\n // Split data into chunks based on chunkSize\n const chunkSize = effectiveConfig.chunkSize;\n const chunks: Uint8Array[] = [];\n for (let i = 0; i < fullData.length; i += chunkSize) {\n chunks.push(fullData.slice(i, i + chunkSize));\n }\n\n // Return as a stream of chunks\n return Stream.fromIterable(chunks);\n }),\n uploadStream: (\n file: Omit<InputFile, \"size\"> & { size?: number; sizeHint?: number },\n _clientId: string | null,\n stream: Stream.Stream<Uint8Array, UploadistaError>,\n ) =>\n Effect.gen(function* () {\n // Collect stream to calculate total size\n const chunks: Uint8Array[] = [];\n yield* Stream.runForEach(stream, (chunk) =>\n Effect.sync(() => {\n chunks.push(chunk);\n }),\n );\n\n const totalSize = chunks.reduce((acc, chunk) => acc + chunk.length, 0);\n\n // Parse existing metadata\n const existingMetadata =\n typeof file.metadata === \"string\"\n ? JSON.parse(file.metadata)\n : file.metadata || {};\n\n // Extract extension from fileName\n const extension = file.fileName\n ? file.fileName.split(\".\").pop()\n : existingMetadata.extension;\n\n // Create new UploadFile with final size\n const uploadId = `stream-uploaded-${Date.now()}-${Math.random().toString(36).substring(7)}`;\n return {\n id: uploadId,\n offset: totalSize,\n size: totalSize,\n storage: {\n id: file.storageId,\n type: \"memory\",\n },\n metadata: {\n ...existingMetadata,\n mimeType: file.type,\n type: file.type,\n \"content-type\": file.type,\n fileName: file.fileName,\n originalName: file.fileName,\n name: file.fileName,\n extension,\n },\n url: `http://test-storage/${uploadId}`,\n creationDate: new Date().toISOString(),\n } satisfies UploadFile;\n }),\n upload: (file, _clientId, stream) =>\n Effect.gen(function* () {\n // Read stream to completion\n const reader = stream.getReader();\n let totalSize = 0;\n const chunks: Uint8Array[] = [];\n\n while (true) {\n const { done, value } = yield* Effect.promise(() => reader.read());\n if (done) break;\n if (value) {\n chunks.push(value);\n totalSize += value.byteLength;\n }\n }\n\n // Parse existing metadata\n const existingMetadata =\n typeof file.metadata === \"string\"\n ? JSON.parse(file.metadata)\n : file.metadata || {};\n\n // Extract extension from fileName\n const extension = file.fileName\n ? file.fileName.split(\".\").pop()\n : existingMetadata.extension;\n\n // Create new UploadFile with merged metadata\n return {\n id: `uploaded-${Date.now()}-${Math.random().toString(36).substring(7)}`,\n offset: totalSize,\n size: totalSize,\n storage: {\n id: file.storageId,\n type: \"memory\",\n },\n metadata: {\n ...existingMetadata,\n // Update with InputFile type and fileName\n mimeType: file.type,\n type: file.type,\n \"content-type\": file.type,\n fileName: file.fileName,\n originalName: file.fileName,\n name: file.fileName,\n extension,\n },\n creationDate: new Date().toISOString(),\n } satisfies UploadFile;\n }),\n delete: (_fileId: string, _clientId: string | null) => Effect.void,\n createUpload: (file: InputFile, _clientId: string | null) =>\n Effect.succeed({\n id: `uploaded-${Date.now()}-${Math.random().toString(36).substring(7)}`,\n offset: 0,\n size: 0,\n storage: { id: file.storageId, type: \"memory\" },\n metadata:\n typeof file.metadata === \"string\"\n ? JSON.parse(file.metadata)\n : file.metadata,\n } satisfies UploadFile),\n uploadChunk: (\n uploadId: string,\n _clientId: string | null,\n chunk: ReadableStream,\n ) =>\n Effect.gen(function* () {\n // Read stream to completion\n const reader = chunk.getReader();\n let totalSize = 0;\n const chunks: Uint8Array[] = [];\n\n while (true) {\n const { done, value } = yield* Effect.promise(() => reader.read());\n if (done) break;\n if (value) {\n chunks.push(value);\n totalSize += value.byteLength;\n }\n }\n return {\n id: uploadId,\n offset: totalSize,\n size: totalSize,\n storage: { id: \"test-storage\", type: \"memory\" },\n metadata: { mimeType: \"application/octet-stream\", extension: \"bin\" },\n creationDate: new Date().toISOString(),\n } satisfies UploadFile;\n }),\n getCapabilities: (_storageId: string, _clientId: string | null) =>\n Effect.succeed({\n supportsParallelUploads: true,\n supportsConcatenation: true,\n supportsDeferredLength: true,\n supportsResumableUploads: true,\n supportsTransactionalUploads: false,\n supportsStreamingRead: true,\n supportsStreamingWrite: true,\n maxConcurrentUploads: 10,\n minChunkSize: 5 * 1024 * 1024, // 5MB\n maxChunkSize: 100 * 1024 * 1024, // 100MB\n maxParts: 10000,\n optimalChunkSize: 10 * 1024 * 1024, // 10MB\n requiresOrderedChunks: false,\n requiresMimeTypeValidation: false,\n } satisfies DataStoreCapabilities),\n uploadFromUrl: (\n inputFile: InputFile,\n _clientId: string | null,\n url: string,\n ) =>\n Effect.succeed({\n id: `uploaded-from-url-${Date.now()}-${Math.random().toString(36).substring(7)}`,\n offset: 0,\n size: 0,\n storage: { id: inputFile.storageId, type: \"memory\" },\n metadata:\n typeof inputFile.metadata === \"string\"\n ? JSON.parse(inputFile.metadata)\n : inputFile.metadata,\n url,\n creationDate: new Date().toISOString(),\n } satisfies UploadFile),\n getUpload: (uploadId: string) =>\n Effect.succeed({\n id: uploadId,\n offset: 0,\n size: 1024,\n storage: {\n id: \"test-storage\",\n type: \"memory\",\n },\n metadata: {\n mimeType: \"text/plain\",\n originalName: `file-${uploadId}.txt`,\n extension: \"txt\",\n },\n creationDate: new Date().toISOString(),\n } satisfies UploadFile),\n subscribeToUploadEvents: (\n _uploadId: string,\n _connection: WebSocketConnection,\n ) => Effect.void,\n unsubscribeFromUploadEvents: (_uploadId: string) => Effect.void,\n }),\n);\n","import { Effect, Layer } from \"effect\";\nimport { VideoPlugin } from \"../flow\";\nimport type { DescribeVideoMetadata } from \"../flow/plugins/types/describe-video-node\";\n\n/**\n * Mock VideoPlugin implementation for testing.\n *\n * Provides simple mock implementations of video processing operations\n * that return mock Uint8Array data without requiring FFmpeg or node-av.\n *\n * @example\n * ```typescript\n * import { TestVideoPlugin } from \"@uploadista/core/testing\";\n *\n * const program = Effect.gen(function* () {\n * const plugin = yield* VideoPlugin;\n * const transcoded = yield* plugin.transcode(videoBytes, { format: \"webm\", codec: \"vp9\" });\n * return transcoded;\n * }).pipe(Effect.provide(TestVideoPlugin));\n * ```\n */\nexport const TestVideoPlugin = Layer.succeed(\n VideoPlugin,\n VideoPlugin.of({\n describe: (input: Uint8Array) =>\n Effect.sync(() => {\n // Mock describe: return fake metadata based on input size\n const metadata: DescribeVideoMetadata = {\n duration: 120, // 2 minutes\n width: 1920,\n height: 1080,\n codec: \"h264\",\n format: \"mp4\",\n bitrate: 5000000, // 5 Mbps\n frameRate: 30,\n aspectRatio: \"16:9\",\n hasAudio: true,\n audioCodec: \"aac\",\n audioBitrate: 128000, // 128 kbps\n size: input.byteLength,\n };\n return metadata;\n }),\n transcode: (_input: Uint8Array, options) =>\n Effect.sync(() => {\n // Mock transcode: return modified array\n // Simulate different file sizes for different codecs\n let sizeMultiplier = 1.0;\n if (options.codec === \"vp9\") {\n sizeMultiplier = 0.8; // VP9 is more efficient\n } else if (options.codec === \"h265\") {\n sizeMultiplier = 0.7; // H265 is even more efficient\n }\n\n const newSize = Math.floor(_input.byteLength * sizeMultiplier);\n return new Uint8Array(newSize).fill(42);\n }),\n resize: (input: Uint8Array, options) =>\n Effect.sync(() => {\n // Mock resize: return array with size based on dimensions\n const width = options.width || 1280;\n const height = options.height || 720;\n // Simulate file size roughly proportional to resolution\n const mockSize = Math.floor((width * height) / 50);\n return new Uint8Array(mockSize).fill(84);\n }),\n trim: (_input: Uint8Array, options) =>\n Effect.sync(() => {\n // Mock trim: return smaller array based on duration\n let duration: number;\n if (options.duration !== undefined) {\n duration = options.duration;\n } else if (options.endTime !== undefined) {\n duration = options.endTime - options.startTime;\n } else {\n // Assume 120s total duration\n duration = 120 - options.startTime;\n }\n\n // Simulate proportional file size based on duration\n const ratio = duration / 120; // Assuming 120s original\n const newSize = Math.floor(_input.byteLength * ratio);\n return new Uint8Array(newSize).fill(63);\n }),\n extractFrame: (input: Uint8Array, options) =>\n Effect.sync(() => {\n // Mock extractFrame: return image bytes (smaller than video)\n const format = options.format || \"jpeg\";\n // JPEG typically smaller than PNG\n const mockSize = format === \"png\" ? 50000 : 30000;\n return new Uint8Array(mockSize).fill(255);\n }),\n }),\n);\n","import { Effect, Layer } from \"effect\";\nimport { VirusScanPlugin } from \"../flow\";\n\n/**\n * EICAR test file signature (standard antivirus test file)\n * This is a safe, non-malicious string used to test antivirus software\n */\nconst EICAR_SIGNATURE =\n \"X5O!P%@AP[4\\\\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*\";\n\n/**\n * Mock VirusScanPlugin implementation for testing.\n *\n * Provides a simple mock implementation that:\n * - Detects the EICAR test signature as infected\n * - Treats all other files as clean\n * - Returns mock version information\n *\n * @example\n * ```typescript\n * import { TestVirusScanPlugin } from \"@uploadista/core/testing\";\n *\n * const program = Effect.gen(function* () {\n * const plugin = yield* VirusScanPlugin;\n * const result = yield* plugin.scan(fileBytes);\n * console.log(result.isClean ? \"Clean\" : \"Infected\");\n * }).pipe(Effect.provide(TestVirusScanPlugin));\n * ```\n */\nexport const TestVirusScanPlugin = Layer.succeed(\n VirusScanPlugin,\n VirusScanPlugin.of({\n scan: (input: Uint8Array) =>\n Effect.sync(() => {\n // Convert bytes to string to check for EICAR signature\n const textDecoder = new TextDecoder();\n const content = textDecoder.decode(input);\n\n // Check if file contains EICAR test signature\n if (content.includes(EICAR_SIGNATURE)) {\n return {\n isClean: false,\n detectedViruses: [\"EICAR-Test-File\"],\n };\n }\n\n // All other files are considered clean\n return {\n isClean: true,\n detectedViruses: [],\n };\n }),\n getVersion: () =>\n Effect.sync(() => {\n return \"TestVirusScanPlugin 1.0.0\";\n }),\n }),\n);\n","import { Effect, Layer } from \"effect\";\nimport { ZipPlugin } from \"../flow\";\n\n/**\n * Mock ZipPlugin implementation for testing.\n *\n * Provides a simple in-memory implementation that creates mock zip data\n * by serializing file metadata as JSON.\n *\n * @example\n * ```typescript\n * import { TestZipPlugin } from \"@uploadista/core/testing\";\n *\n * const program = Effect.gen(function* () {\n * const zipPlugin = yield* ZipPlugin;\n * const zipData = yield* zipPlugin.zip(inputs, options);\n * return zipData;\n * }).pipe(Effect.provide(TestZipPlugin));\n * ```\n */\nexport const TestZipPlugin = Layer.succeed(\n ZipPlugin,\n ZipPlugin.of({\n zip: (inputs, options) =>\n Effect.gen(function* () {\n // Create mock zip data\n const files = inputs.map((input) => ({\n id: input.id,\n size: input.data.byteLength,\n }));\n\n const zipContent = JSON.stringify({\n zipName: options.zipName,\n includeMetadata: options.includeMetadata,\n files,\n });\n\n return new TextEncoder().encode(zipContent);\n }),\n }),\n);\n"],"mappings":"+WAwBA,MAAa,EAAuB,EAAM,QACxC,EACA,EAAiB,GAAG,CAClB,YAAa,EAAkB,EAAQ,IACrC,EAAO,UACqB,CACxB,cACE,EAAO,WAAa,oBAChB;;;;;;;eACA,yDACN,OACE,EAAO,WAAa,oBAAsB,WAAa,QACzD,WAAY,IACb,EAED,CACL,CAAC,CACH,CCrBY,EAAqB,EAAM,QACtC,EACA,EAAe,GAAG,CAChB,YAAc,GACZ,EAAO,SAEE;iBACP,CACJ,UAAW,EAAmB,IAC5B,EAAO,SACD,EAAQ,OAAS,QAGZ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K,GAAG,EACvC,CACJ,cAAe,EAAmB,IAChC,EAAO,SAAW,CAIhB,IAAM,GAFS,EAAQ,QAAU,UAEL,MAAQ,IAAQ,IAC5C,OAAO,IAAI,WAAW,EAAS,CAAC,KAAK,IAAI,EACzC,CACL,CAAC,CACH,CChEY,EAAsB,EAAM,QACvC,EACA,EAAgB,GAAG,CACjB,KAAO,GACL,EAAO,SAEe,IAAI,aAAa,CACT,OAAO,EAAM,CAG7B,SAAS,wEAAgB,CAC5B,CACL,QAAS,GACT,gBAAiB,CAAC,kBAAkB,CACrC,CAII,CACL,QAAS,GACT,gBAAiB,EAAE,CACpB,CACD,CACJ,eACE,EAAO,SACE,4BACP,CACL,CAAC,CACH,CCrCY,EAAgB,EAAM,QACjC,EACA,EAAU,GAAG,CACX,KAAM,EAAQ,IACZ,EAAO,IAAI,WAAa,CAEtB,IAAM,EAAQ,EAAO,IAAK,IAAW,CACnC,GAAI,EAAM,GACV,KAAM,EAAM,KAAK,WAClB,EAAE,CAEG,EAAa,KAAK,UAAU,CAChC,QAAS,EAAQ,QACjB,gBAAiB,EAAQ,gBACzB,QACD,CAAC,CAEF,OAAO,IAAI,aAAa,CAAC,OAAO,EAAW,EAC3C,CACL,CAAC,CACH"}
1
+ {"version":3,"file":"index.mjs","names":["EICAR_SIGNATURE"],"sources":["../../src/testing/mock-document-ai-plugin.ts","../../src/testing/mock-document-plugin.ts","../../src/testing/mock-image-ai-plugin.ts","../../src/testing/mock-image-plugin.ts","../../src/testing/mock-upload-engine.ts","../../src/testing/mock-video-plugin.ts","../../src/testing/mock-virus-scan-plugin.ts","../../src/testing/mock-zip-plugin.ts"],"sourcesContent":["import { Effect, Layer } from \"effect\";\nimport type { OcrResult } from \"../flow\";\nimport { DocumentAiPlugin } from \"../flow\";\n\n/**\n * Mock DocumentAiPlugin implementation for testing.\n *\n * Provides simple mock implementations of AI document operations.\n *\n * @example\n * ```typescript\n * import { TestDocumentAiPlugin } from \"@uploadista/core/testing\";\n *\n * const program = Effect.gen(function* () {\n * const plugin = yield* DocumentAiPlugin;\n * const result = yield* plugin.performOCR(\n * \"https://example.com/doc.pdf\",\n * { taskType: \"convertToMarkdown\", resolution: \"gundam\" },\n * { clientId: \"test-client\" }\n * );\n * return result;\n * }).pipe(Effect.provide(TestDocumentAiPlugin));\n * ```\n */\nexport const TestDocumentAiPlugin = Layer.succeed(\n DocumentAiPlugin,\n DocumentAiPlugin.of({\n performOCR: (inputUrl: string, params, context) =>\n Effect.sync(() => {\n const result: OcrResult = {\n extractedText:\n params.taskType === \"convertToMarkdown\"\n ? \"# Document Title\\n\\nThis is a paragraph with **bold** text.\\n\\n## Section 2\\n\\n- List item 1\\n- List item 2\"\n : \"Plain text extracted from document without formatting.\",\n format:\n params.taskType === \"convertToMarkdown\" ? \"markdown\" : \"plain\",\n confidence: 0.95,\n };\n return result;\n }),\n }),\n);\n","import { Effect, Layer } from \"effect\";\nimport type { DocumentMetadata, SplitPdfResult } from \"../flow\";\nimport { DocumentPlugin } from \"../flow\";\n\n/**\n * Mock DocumentPlugin implementation for testing.\n *\n * Provides simple mock implementations of PDF operations that return mock data.\n *\n * @example\n * ```typescript\n * import { TestDocumentPlugin } from \"@uploadista/core/testing\";\n *\n * const program = Effect.gen(function* () {\n * const plugin = yield* DocumentPlugin;\n * const text = yield* plugin.extractText(pdfBytes);\n * return text;\n * }).pipe(Effect.provide(TestDocumentPlugin));\n * ```\n */\nexport const TestDocumentPlugin = Layer.succeed(\n DocumentPlugin,\n DocumentPlugin.of({\n extractText: (input: Uint8Array) =>\n Effect.sync(() => {\n // Mock text extraction\n return \"This is extracted text from a PDF document.\\nPage 1 content.\";\n }),\n splitPdf: (input: Uint8Array, options) =>\n Effect.sync(() => {\n if (options.mode === \"range\") {\n // Mock range split\n const mockPdf = new Uint8Array(500).fill(80);\n return {\n mode: \"range\" as const,\n pdf: mockPdf,\n } satisfies SplitPdfResult;\n }\n // Mock individual split\n const mockPdfs = [\n new Uint8Array(200).fill(81),\n new Uint8Array(200).fill(82),\n new Uint8Array(200).fill(83),\n ];\n return {\n mode: \"individual\" as const,\n pdfs: mockPdfs,\n } satisfies SplitPdfResult;\n }),\n mergePdfs: (options) =>\n Effect.sync(() => {\n // Mock merge: combine sizes\n const totalSize = options.pdfs.reduce(\n (sum, pdf) => sum + pdf.byteLength,\n 0,\n );\n return new Uint8Array(totalSize).fill(90);\n }),\n getMetadata: (input: Uint8Array) =>\n Effect.sync(() => {\n const metadata: DocumentMetadata = {\n pageCount: 5,\n format: \"pdf\",\n author: \"Test Author\",\n title: \"Test Document\",\n subject: \"Test Subject\",\n creator: \"Test Creator\",\n creationDate: \"2024-01-01T00:00:00Z\",\n modifiedDate: \"2024-01-02T00:00:00Z\",\n fileSize: input.byteLength,\n };\n return metadata;\n }),\n }),\n);\n","import { Effect, Layer } from \"effect\";\nimport { ImageAiPlugin } from \"../flow\";\n\n/**\n * Mock ImageAiPlugin implementation for testing.\n *\n * Provides simple mock implementations of AI-powered image operations\n * like background removal and image description.\n *\n * @example\n * ```typescript\n * import { TestImageAiPlugin } from \"@uploadista/core/testing\";\n *\n * const program = Effect.gen(function* () {\n * const plugin = yield* ImageAiPlugin;\n * const result = yield* plugin.removeBackground(imageUrl, context);\n * return result;\n * }).pipe(Effect.provide(TestImageAiPlugin));\n * ```\n */\nexport const TestImageAiPlugin = Layer.succeed(\n ImageAiPlugin,\n ImageAiPlugin.of({\n removeBackground: (inputUrl: string, _context) =>\n Effect.sync(() => ({\n outputUrl: inputUrl.replace(\".jpg\", \"-no-bg.png\"),\n })),\n describeImage: (inputUrl: string, _context) =>\n Effect.sync(() => ({\n description: `A test image from ${inputUrl}`,\n })),\n }),\n);\n","import { Effect, Layer } from \"effect\";\nimport { ImagePlugin } from \"../flow\";\n\n/**\n * Mock ImagePlugin implementation for testing.\n *\n * Provides simple mock implementations of image optimization, resizing,\n * and transformation operations that return mock Uint8Array data.\n *\n * @example\n * ```typescript\n * import { TestImagePlugin } from \"@uploadista/core/testing\";\n *\n * const program = Effect.gen(function* () {\n * const plugin = yield* ImagePlugin;\n * const optimized = yield* plugin.optimize(imageBytes, { quality: 80, format: \"webp\" });\n * return optimized;\n * }).pipe(Effect.provide(TestImagePlugin));\n * ```\n */\nexport const TestImagePlugin = Layer.succeed(\n ImagePlugin,\n ImagePlugin.of({\n optimize: (input: Uint8Array, options) =>\n Effect.sync(() => {\n // Mock optimize: return smaller array for lower quality\n const sizeMultiplier = options.quality / 100;\n const newSize = Math.floor(input.byteLength * sizeMultiplier);\n return new Uint8Array(newSize).fill(128);\n }),\n resize: (input: Uint8Array, options) =>\n Effect.sync(() => {\n // Mock resize: return array with size based on dimensions\n const width = options.width || 800;\n const height = options.height || 600;\n const mockSize = Math.floor((width * height) / 10);\n return new Uint8Array(mockSize).fill(100);\n }),\n transform: (input: Uint8Array, transformation) =>\n Effect.sync(() => {\n // Mock transform: modify array based on transformation type\n if (transformation.type === \"rotate\" && transformation.angle === 90) {\n // For 90° rotation, swap dimensions (mock behavior)\n return new Uint8Array(input.byteLength + 10).fill(150);\n }\n if (transformation.type === \"blur\") {\n return new Uint8Array(input.byteLength).fill(180);\n }\n if (transformation.type === \"grayscale\") {\n return new Uint8Array(input.byteLength).fill(128);\n }\n // Default: return modified copy\n return new Uint8Array(input.byteLength).fill(200);\n }),\n }),\n);\n","import { Effect, Layer, Stream } from \"effect\";\nimport type { UploadistaError } from \"../errors\";\nimport type { InputFile, UploadFile, WebSocketConnection } from \"../types\";\nimport {\n type DataStoreCapabilities,\n DEFAULT_STREAMING_CONFIG,\n type StreamingConfig,\n} from \"../types/data-store\";\nimport { UploadEngine } from \"../upload\";\n\n/**\n * EICAR test file signature (standard antivirus test file)\n * This is a safe, non-malicious string used to test antivirus software\n */\nconst EICAR_SIGNATURE =\n \"X5O!P%@AP[4\\\\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*\";\n\n/**\n * Mock UploadEngine implementation for testing.\n *\n * Provides a complete in-memory implementation of all UploadEngine methods\n * suitable for unit and integration tests.\n *\n * @example\n * ```typescript\n * import { TestUploadEngine } from \"@uploadista/core/testing\";\n *\n * const program = Effect.gen(function* () {\n * const server = yield* UploadEngine;\n * const upload = yield* server.createUpload(inputFile, \"client-123\");\n * return upload;\n * }).pipe(Effect.provide(TestUploadEngine));\n * ```\n */\nexport const TestUploadEngine = Layer.succeed(\n UploadEngine,\n UploadEngine.of({\n read: (fileId: string, _clientId: string | null) =>\n Effect.sync(() => {\n // Return infected content for files that should trigger virus detection\n // This allows tests to verify virus scanning behavior\n if (\n fileId.toLowerCase().includes(\"infected\") ||\n fileId.toLowerCase().includes(\"virus\") ||\n fileId.toLowerCase().includes(\"malware\") ||\n fileId.toLowerCase().includes(\"eicar\")\n ) {\n return new TextEncoder().encode(EICAR_SIGNATURE);\n }\n // Generate clean mock file data for other files\n const text = `Content of file ${fileId}`;\n return new TextEncoder().encode(text);\n }),\n readStream: (\n fileId: string,\n _clientId: string | null,\n config?: StreamingConfig,\n ) =>\n Effect.sync(() => {\n const effectiveConfig = { ...DEFAULT_STREAMING_CONFIG, ...config };\n // Generate mock file data based on fileId\n const text = `Content of file ${fileId}`;\n const fullData = new TextEncoder().encode(text);\n\n // Split data into chunks based on chunkSize\n const chunkSize = effectiveConfig.chunkSize;\n const chunks: Uint8Array[] = [];\n for (let i = 0; i < fullData.length; i += chunkSize) {\n chunks.push(fullData.slice(i, i + chunkSize));\n }\n\n // Return as a stream of chunks\n return Stream.fromIterable(chunks);\n }),\n uploadStream: (\n file: Omit<InputFile, \"size\"> & { size?: number; sizeHint?: number },\n _clientId: string | null,\n stream: Stream.Stream<Uint8Array, UploadistaError>,\n ) =>\n Effect.gen(function* () {\n // Collect stream to calculate total size\n const chunks: Uint8Array[] = [];\n yield* Stream.runForEach(stream, (chunk) =>\n Effect.sync(() => {\n chunks.push(chunk);\n }),\n );\n\n const totalSize = chunks.reduce((acc, chunk) => acc + chunk.length, 0);\n\n // Parse existing metadata\n const existingMetadata =\n typeof file.metadata === \"string\"\n ? JSON.parse(file.metadata)\n : file.metadata || {};\n\n // Extract extension from fileName\n const extension = file.fileName\n ? file.fileName.split(\".\").pop()\n : existingMetadata.extension;\n\n // Create new UploadFile with final size\n const uploadId = `stream-uploaded-${Date.now()}-${Math.random().toString(36).substring(7)}`;\n return {\n id: uploadId,\n offset: totalSize,\n size: totalSize,\n storage: {\n id: file.storageId,\n type: \"memory\",\n },\n metadata: {\n ...existingMetadata,\n mimeType: file.type,\n type: file.type,\n \"content-type\": file.type,\n fileName: file.fileName,\n originalName: file.fileName,\n name: file.fileName,\n extension,\n },\n url: `http://test-storage/${uploadId}`,\n creationDate: new Date().toISOString(),\n } satisfies UploadFile;\n }),\n upload: (file, _clientId, stream) =>\n Effect.gen(function* () {\n // Read stream to completion\n const reader = stream.getReader();\n let totalSize = 0;\n const chunks: Uint8Array[] = [];\n\n while (true) {\n const { done, value } = yield* Effect.promise(() => reader.read());\n if (done) break;\n if (value) {\n chunks.push(value);\n totalSize += value.byteLength;\n }\n }\n\n // Parse existing metadata\n const existingMetadata =\n typeof file.metadata === \"string\"\n ? JSON.parse(file.metadata)\n : file.metadata || {};\n\n // Extract extension from fileName\n const extension = file.fileName\n ? file.fileName.split(\".\").pop()\n : existingMetadata.extension;\n\n // Create new UploadFile with merged metadata\n return {\n id: `uploaded-${Date.now()}-${Math.random().toString(36).substring(7)}`,\n offset: totalSize,\n size: totalSize,\n storage: {\n id: file.storageId,\n type: \"memory\",\n },\n metadata: {\n ...existingMetadata,\n // Update with InputFile type and fileName\n mimeType: file.type,\n type: file.type,\n \"content-type\": file.type,\n fileName: file.fileName,\n originalName: file.fileName,\n name: file.fileName,\n extension,\n },\n creationDate: new Date().toISOString(),\n } satisfies UploadFile;\n }),\n delete: (_fileId: string, _clientId: string | null) => Effect.void,\n createUpload: (file: InputFile, _clientId: string | null) =>\n Effect.succeed({\n id: `uploaded-${Date.now()}-${Math.random().toString(36).substring(7)}`,\n offset: 0,\n size: 0,\n storage: { id: file.storageId, type: \"memory\" },\n metadata:\n typeof file.metadata === \"string\"\n ? JSON.parse(file.metadata)\n : file.metadata,\n } satisfies UploadFile),\n uploadChunk: (\n uploadId: string,\n _clientId: string | null,\n chunk: ReadableStream,\n ) =>\n Effect.gen(function* () {\n // Read stream to completion\n const reader = chunk.getReader();\n let totalSize = 0;\n const chunks: Uint8Array[] = [];\n\n while (true) {\n const { done, value } = yield* Effect.promise(() => reader.read());\n if (done) break;\n if (value) {\n chunks.push(value);\n totalSize += value.byteLength;\n }\n }\n return {\n id: uploadId,\n offset: totalSize,\n size: totalSize,\n storage: { id: \"test-storage\", type: \"memory\" },\n metadata: { mimeType: \"application/octet-stream\", extension: \"bin\" },\n creationDate: new Date().toISOString(),\n } satisfies UploadFile;\n }),\n getCapabilities: (_storageId: string, _clientId: string | null) =>\n Effect.succeed({\n supportsParallelUploads: true,\n supportsConcatenation: true,\n supportsDeferredLength: true,\n supportsResumableUploads: true,\n supportsTransactionalUploads: false,\n supportsStreamingRead: true,\n supportsStreamingWrite: true,\n maxConcurrentUploads: 10,\n minChunkSize: 5 * 1024 * 1024, // 5MB\n maxChunkSize: 100 * 1024 * 1024, // 100MB\n maxParts: 10000,\n optimalChunkSize: 10 * 1024 * 1024, // 10MB\n requiresOrderedChunks: false,\n requiresMimeTypeValidation: false,\n } satisfies DataStoreCapabilities),\n uploadFromUrl: (\n inputFile: InputFile,\n _clientId: string | null,\n url: string,\n ) =>\n Effect.succeed({\n id: `uploaded-from-url-${Date.now()}-${Math.random().toString(36).substring(7)}`,\n offset: 0,\n size: 0,\n storage: { id: inputFile.storageId, type: \"memory\" },\n metadata:\n typeof inputFile.metadata === \"string\"\n ? JSON.parse(inputFile.metadata)\n : inputFile.metadata,\n url,\n creationDate: new Date().toISOString(),\n } satisfies UploadFile),\n getUpload: (uploadId: string) =>\n Effect.succeed({\n id: uploadId,\n offset: 0,\n size: 1024,\n storage: {\n id: \"test-storage\",\n type: \"memory\",\n },\n metadata: {\n mimeType: \"text/plain\",\n originalName: `file-${uploadId}.txt`,\n extension: \"txt\",\n },\n creationDate: new Date().toISOString(),\n } satisfies UploadFile),\n subscribeToUploadEvents: (\n _uploadId: string,\n _connection: WebSocketConnection,\n ) => Effect.void,\n unsubscribeFromUploadEvents: (_uploadId: string) => Effect.void,\n }),\n);\n","import { Effect, Layer } from \"effect\";\nimport { VideoPlugin } from \"../flow\";\nimport type { DescribeVideoMetadata } from \"../flow/plugins/types/describe-video-node\";\n\n/**\n * Mock VideoPlugin implementation for testing.\n *\n * Provides simple mock implementations of video processing operations\n * that return mock Uint8Array data without requiring FFmpeg or node-av.\n *\n * @example\n * ```typescript\n * import { TestVideoPlugin } from \"@uploadista/core/testing\";\n *\n * const program = Effect.gen(function* () {\n * const plugin = yield* VideoPlugin;\n * const transcoded = yield* plugin.transcode(videoBytes, { format: \"webm\", codec: \"vp9\" });\n * return transcoded;\n * }).pipe(Effect.provide(TestVideoPlugin));\n * ```\n */\nexport const TestVideoPlugin = Layer.succeed(\n VideoPlugin,\n VideoPlugin.of({\n describe: (input: Uint8Array) =>\n Effect.sync(() => {\n // Mock describe: return fake metadata based on input size\n const metadata: DescribeVideoMetadata = {\n duration: 120, // 2 minutes\n width: 1920,\n height: 1080,\n codec: \"h264\",\n format: \"mp4\",\n bitrate: 5000000, // 5 Mbps\n frameRate: 30,\n aspectRatio: \"16:9\",\n hasAudio: true,\n audioCodec: \"aac\",\n audioBitrate: 128000, // 128 kbps\n size: input.byteLength,\n };\n return metadata;\n }),\n transcode: (_input: Uint8Array, options) =>\n Effect.sync(() => {\n // Mock transcode: return modified array\n // Simulate different file sizes for different codecs\n let sizeMultiplier = 1.0;\n if (options.codec === \"vp9\") {\n sizeMultiplier = 0.8; // VP9 is more efficient\n } else if (options.codec === \"h265\") {\n sizeMultiplier = 0.7; // H265 is even more efficient\n }\n\n const newSize = Math.floor(_input.byteLength * sizeMultiplier);\n return new Uint8Array(newSize).fill(42);\n }),\n resize: (input: Uint8Array, options) =>\n Effect.sync(() => {\n // Mock resize: return array with size based on dimensions\n const width = options.width || 1280;\n const height = options.height || 720;\n // Simulate file size roughly proportional to resolution\n const mockSize = Math.floor((width * height) / 50);\n return new Uint8Array(mockSize).fill(84);\n }),\n trim: (_input: Uint8Array, options) =>\n Effect.sync(() => {\n // Mock trim: return smaller array based on duration\n let duration: number;\n if (options.duration !== undefined) {\n duration = options.duration;\n } else if (options.endTime !== undefined) {\n duration = options.endTime - options.startTime;\n } else {\n // Assume 120s total duration\n duration = 120 - options.startTime;\n }\n\n // Simulate proportional file size based on duration\n const ratio = duration / 120; // Assuming 120s original\n const newSize = Math.floor(_input.byteLength * ratio);\n return new Uint8Array(newSize).fill(63);\n }),\n extractFrame: (input: Uint8Array, options) =>\n Effect.sync(() => {\n // Mock extractFrame: return image bytes (smaller than video)\n const format = options.format || \"jpeg\";\n // JPEG typically smaller than PNG\n const mockSize = format === \"png\" ? 50000 : 30000;\n return new Uint8Array(mockSize).fill(255);\n }),\n }),\n);\n","import { Effect, Layer } from \"effect\";\nimport { VirusScanPlugin } from \"../flow\";\n\n/**\n * EICAR test file signature (standard antivirus test file)\n * This is a safe, non-malicious string used to test antivirus software\n */\nconst EICAR_SIGNATURE =\n \"X5O!P%@AP[4\\\\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*\";\n\n/**\n * Mock VirusScanPlugin implementation for testing.\n *\n * Provides a simple mock implementation that:\n * - Detects the EICAR test signature as infected\n * - Treats all other files as clean\n * - Returns mock version information\n *\n * @example\n * ```typescript\n * import { TestVirusScanPlugin } from \"@uploadista/core/testing\";\n *\n * const program = Effect.gen(function* () {\n * const plugin = yield* VirusScanPlugin;\n * const result = yield* plugin.scan(fileBytes);\n * console.log(result.isClean ? \"Clean\" : \"Infected\");\n * }).pipe(Effect.provide(TestVirusScanPlugin));\n * ```\n */\nexport const TestVirusScanPlugin = Layer.succeed(\n VirusScanPlugin,\n VirusScanPlugin.of({\n scan: (input: Uint8Array) =>\n Effect.sync(() => {\n // Convert bytes to string to check for EICAR signature\n const textDecoder = new TextDecoder();\n const content = textDecoder.decode(input);\n\n // Check if file contains EICAR test signature\n if (content.includes(EICAR_SIGNATURE)) {\n return {\n isClean: false,\n detectedViruses: [\"EICAR-Test-File\"],\n };\n }\n\n // All other files are considered clean\n return {\n isClean: true,\n detectedViruses: [],\n };\n }),\n getVersion: () =>\n Effect.sync(() => {\n return \"TestVirusScanPlugin 1.0.0\";\n }),\n }),\n);\n","import { Effect, Layer } from \"effect\";\nimport { ZipPlugin } from \"../flow\";\n\n/**\n * Mock ZipPlugin implementation for testing.\n *\n * Provides a simple in-memory implementation that creates mock zip data\n * by serializing file metadata as JSON.\n *\n * @example\n * ```typescript\n * import { TestZipPlugin } from \"@uploadista/core/testing\";\n *\n * const program = Effect.gen(function* () {\n * const zipPlugin = yield* ZipPlugin;\n * const zipData = yield* zipPlugin.zip(inputs, options);\n * return zipData;\n * }).pipe(Effect.provide(TestZipPlugin));\n * ```\n */\nexport const TestZipPlugin = Layer.succeed(\n ZipPlugin,\n ZipPlugin.of({\n zip: (inputs, options) =>\n Effect.gen(function* () {\n // Create mock zip data\n const files = inputs.map((input) => ({\n id: input.id,\n size: input.data.byteLength,\n }));\n\n const zipContent = JSON.stringify({\n zipName: options.zipName,\n includeMetadata: options.includeMetadata,\n files,\n });\n\n return new TextEncoder().encode(zipContent);\n }),\n }),\n);\n"],"mappings":"+WAwBA,MAAa,EAAuB,EAAM,QACxC,EACA,EAAiB,GAAG,CAClB,YAAa,EAAkB,EAAQ,IACrC,EAAO,UACqB,CACxB,cACE,EAAO,WAAa,oBAChB;;;;;;;eACA,yDACN,OACE,EAAO,WAAa,oBAAsB,WAAa,QACzD,WAAY,IACb,EAED,CACL,CAAC,CACH,CCrBY,EAAqB,EAAM,QACtC,EACA,EAAe,GAAG,CAChB,YAAc,GACZ,EAAO,SAEE;iBACP,CACJ,UAAW,EAAmB,IAC5B,EAAO,SACD,EAAQ,OAAS,QAGZ,CACL,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AAQ,UAAY,IAAA,GAIlB,IAAM,EAAQ,UAHd,EAAQ,QAAU,EAAQ,UAF1B,EAAQ,SASrB,IAAM,EAAQ,EAAW,IACnB,EAAU,KAAK,MAAM,EAAO,WAAa,EAAM,CACrD,OAAO,IAAI,WAAW,EAAQ,CAAC,KAAK,GAAG,EACvC,CACJ,cAAe,EAAmB,IAChC,EAAO,SAAW,CAIhB,IAAM,GAFS,EAAQ,QAAU,UAEL,MAAQ,IAAQ,IAC5C,OAAO,IAAI,WAAW,EAAS,CAAC,KAAK,IAAI,EACzC,CACL,CAAC,CACH,CChEY,EAAsB,EAAM,QACvC,EACA,EAAgB,GAAG,CACjB,KAAO,GACL,EAAO,SAEe,IAAI,aAAa,CACT,OAAO,EAAM,CAG7B,SAAS,wEAAgB,CAC5B,CACL,QAAS,GACT,gBAAiB,CAAC,kBAAkB,CACrC,CAII,CACL,QAAS,GACT,gBAAiB,EAAE,CACpB,CACD,CACJ,eACE,EAAO,SACE,4BACP,CACL,CAAC,CACH,CCrCY,EAAgB,EAAM,QACjC,EACA,EAAU,GAAG,CACX,KAAM,EAAQ,IACZ,EAAO,IAAI,WAAa,CAEtB,IAAM,EAAQ,EAAO,IAAK,IAAW,CACnC,GAAI,EAAM,GACV,KAAM,EAAM,KAAK,WAClB,EAAE,CAEG,EAAa,KAAK,UAAU,CAChC,QAAS,EAAQ,QACjB,gBAAiB,EAAQ,gBACzB,QACD,CAAC,CAEF,OAAO,IAAI,aAAa,CAAC,OAAO,EAAW,EAC3C,CACL,CAAC,CACH"}
@@ -1 +1 @@
1
- const e=require(`../types-Cws60JHC.cjs`);require(`../uploadista-error-BgQU45we.cjs`),require(`../errors-CRm1FHHT.cjs`),exports.BaseEventEmitterService=e.u,exports.BaseKvStoreService=e.k,exports.BufferedUploadFileDataStore=e.v,exports.CircuitBreakerStoreService=e.D,exports.DEFAULT_HEALTH_CHECK_CONFIG=e.s,exports.DEFAULT_MULTIPART_PART_SIZE=e.y,exports.DEFAULT_STREAMING_CONFIG=e.b,exports.DeadLetterQueueKVStore=e.A,exports.EventBroadcasterService=e._,exports.FlowEventEmitter=e.d,exports.FlowJobKVStore=e.j,exports.MiddlewareService=e.i,exports.MiddlewareServiceLive=e.a,exports.TypedEventEmitter=e.f,exports.TypedKvStore=e.M,exports.UploadEventEmitter=e.p,exports.UploadEventType=e.n,exports.UploadFileDataStore=e.x,exports.UploadFileDataStores=e.S,exports.UploadFileKVStore=e.N,exports.createDataStoreLayer=e.C,exports.createInitialCircuitBreakerState=e.O,exports.deadLetterQueueKvStore=e.P,exports.eventToMessageSerializer=e.m,exports.flowEventEmitter=e.h,exports.flowJobKvStore=e.F,exports.formatHealthAsText=e.c,exports.getHealthResponseFormat=e.l,exports.inputFileSchema=e.o,exports.isDataStore=e.w,exports.jsonSerializer=e.I,exports.traceContextSchema=e.T,exports.uploadEventEmitter=e.g,exports.uploadEventSchema=e.r,exports.uploadFileKvStore=e.L,exports.uploadFileSchema=e.E,exports.webSocketMessageSchema=e.t;
1
+ const e=require(`../types-BF_tvkRh.cjs`);require(`../uploadista-error-CLWoRAAr.cjs`),require(`../errors-CRm1FHHT.cjs`),exports.BaseEventEmitterService=e.u,exports.BaseKvStoreService=e.D,exports.BufferedUploadFileDataStore=e.v,exports.CircuitBreakerStoreService=e.I,exports.DEFAULT_HEALTH_CHECK_CONFIG=e.s,exports.DEFAULT_MULTIPART_PART_SIZE=e.y,exports.DEFAULT_STREAMING_CONFIG=e.b,exports.DeadLetterQueueKVStore=e.O,exports.EventBroadcasterService=e._,exports.FlowEventEmitter=e.d,exports.FlowJobKVStore=e.k,exports.MiddlewareService=e.i,exports.MiddlewareServiceLive=e.a,exports.TypedEventEmitter=e.f,exports.TypedKvStore=e.A,exports.UploadEventEmitter=e.p,exports.UploadEventType=e.n,exports.UploadFileDataStore=e.x,exports.UploadFileDataStores=e.S,exports.UploadFileKVStore=e.j,exports.createDataStoreLayer=e.C,exports.createInitialCircuitBreakerState=e.L,exports.deadLetterQueueKvStore=e.M,exports.eventToMessageSerializer=e.m,exports.flowEventEmitter=e.h,exports.flowJobKvStore=e.N,exports.formatHealthAsText=e.c,exports.getHealthResponseFormat=e.l,exports.inputFileSchema=e.o,exports.isDataStore=e.w,exports.jsonSerializer=e.P,exports.traceContextSchema=e.T,exports.uploadEventEmitter=e.g,exports.uploadEventSchema=e.r,exports.uploadFileKvStore=e.F,exports.uploadFileSchema=e.E,exports.webSocketMessageSchema=e.t;
@@ -1,2 +1,2 @@
1
- import { Ai as DataStore, Ar as uploadEventEmitter, Bi as UploadStrategy, Cr as BaseEventEmitterService, Di as BufferedUploadFileDataStore, Dr as UploadEventEmitter, Er as TypedEventEmitter, Fi as StreamWriteResult, Fr as UploadEventType, Hi as isDataStore, Ii as StreamingConfig, Ir as uploadEventSchema, Li as UploadFileDataStore, Lr as EventBroadcaster, Mi as DataStoreConfig, Mr as WebSocketMessage, Ni as DataStoreWriteOptions, Nr as webSocketMessageSchema, Oi as DEFAULT_MULTIPART_PART_SIZE, Or as eventToMessageSerializer, Pi as StreamWriteOptions, Pr as UploadEvent, Ri as UploadFileDataStores, Rr as EventBroadcasterService, Sr as BaseEventEmitter, Tr as FlowEventEmitter, Vi as createDataStoreLayer, _o as UploadFile, _r as HealthResponse, ao as createInitialCircuitBreakerState, ar as MiddlewareContext, bo as uploadFileSchema, br as formatHealthAsText, co as DeadLetterQueueKVStore, cr as MiddlewareServiceLive, do as TypedKvStore, dr as CircuitBreakerHealthSummary, eo as CircuitBreakerStateData, fo as UploadFileKVStore, fr as ComponentHealth, go as uploadFileKvStore, gr as HealthComponents, ho as jsonSerializer, hr as HealthCheckConfig, io as CircuitBreakerStoreService, ir as Middleware, ji as DataStoreCapabilities, jr as WebSocketConnection, ki as DEFAULT_STREAMING_CONFIG, kr as flowEventEmitter, lo as FlowJobKVStore, lr as InputFile, mo as flowJobKvStore, mr as DlqHealthSummary, no as CircuitBreakerStats, oo as BaseKvStore, or as MiddlewareNext, po as deadLetterQueueKvStore, pr as DEFAULT_HEALTH_CHECK_CONFIG, ro as CircuitBreakerStore, so as BaseKvStoreService, sr as MiddlewareService, to as CircuitBreakerStateValue, uo as KvStore, ur as inputFileSchema, vo as UploadFileTraceContext, vr as HealthResponseFormat, wr as EventEmitter, xr as getHealthResponseFormat, yo as traceContextSchema, yr as HealthStatus, zi as UploadFileDataStoresShape } from "../index-DMqaf28W.cjs";
2
- export { BaseEventEmitter, BaseEventEmitterService, BaseKvStore, BaseKvStoreService, BufferedUploadFileDataStore, CircuitBreakerHealthSummary, CircuitBreakerStateData, CircuitBreakerStateValue, CircuitBreakerStats, CircuitBreakerStore, CircuitBreakerStoreService, ComponentHealth, DEFAULT_HEALTH_CHECK_CONFIG, DEFAULT_MULTIPART_PART_SIZE, DEFAULT_STREAMING_CONFIG, DataStore, DataStoreCapabilities, DataStoreConfig, DataStoreWriteOptions, DeadLetterQueueKVStore, DlqHealthSummary, EventBroadcaster, EventBroadcasterService, EventEmitter, FlowEventEmitter, FlowJobKVStore, HealthCheckConfig, HealthComponents, HealthResponse, HealthResponseFormat, HealthStatus, InputFile, KvStore, Middleware, MiddlewareContext, MiddlewareNext, MiddlewareService, MiddlewareServiceLive, StreamWriteOptions, StreamWriteResult, StreamingConfig, TypedEventEmitter, TypedKvStore, UploadEvent, UploadEventEmitter, UploadEventType, UploadFile, UploadFileDataStore, UploadFileDataStores, UploadFileDataStoresShape, UploadFileKVStore, UploadFileTraceContext, UploadStrategy, WebSocketConnection, WebSocketMessage, createDataStoreLayer, createInitialCircuitBreakerState, deadLetterQueueKvStore, eventToMessageSerializer, flowEventEmitter, flowJobKvStore, formatHealthAsText, getHealthResponseFormat, inputFileSchema, isDataStore, jsonSerializer, traceContextSchema, uploadEventEmitter, uploadEventSchema, uploadFileKvStore, uploadFileSchema, webSocketMessageSchema };
1
+ import { Ai as DataStore, Ar as uploadEventEmitter, Bi as UploadStrategy, Co as CircuitBreakerStateValue, Cr as BaseEventEmitterService, Di as BufferedUploadFileDataStore, Do as createInitialCircuitBreakerState, Dr as UploadEventEmitter, Eo as CircuitBreakerStoreService, Er as TypedEventEmitter, Fi as StreamWriteResult, Fr as UploadEventType, Hi as isDataStore, Ii as StreamingConfig, Ir as uploadEventSchema, Li as UploadFileDataStore, Lr as EventBroadcaster, Mi as DataStoreConfig, Mr as WebSocketMessage, Ni as DataStoreWriteOptions, Nr as webSocketMessageSchema, Oi as DEFAULT_MULTIPART_PART_SIZE, Or as eventToMessageSerializer, Pi as StreamWriteOptions, Pr as UploadEvent, Ri as UploadFileDataStores, Rr as EventBroadcasterService, So as CircuitBreakerStateData, Sr as BaseEventEmitter, To as CircuitBreakerStore, Tr as FlowEventEmitter, Vi as createDataStoreLayer, _o as JsonValue, _r as HealthResponse, ar as MiddlewareContext, bo as traceContextSchema, br as formatHealthAsText, co as DeadLetterQueueKVStore, cr as MiddlewareServiceLive, do as TypedKvStore, dr as CircuitBreakerHealthSummary, fo as UploadFileKVStore, fr as ComponentHealth, go as uploadFileKvStore, gr as HealthComponents, ho as jsonSerializer, hr as HealthCheckConfig, ir as Middleware, ji as DataStoreCapabilities, jr as WebSocketConnection, ki as DEFAULT_STREAMING_CONFIG, kr as flowEventEmitter, lo as FlowJobKVStore, lr as InputFile, mo as flowJobKvStore, mr as DlqHealthSummary, oo as BaseKvStore, or as MiddlewareNext, po as deadLetterQueueKvStore, pr as DEFAULT_HEALTH_CHECK_CONFIG, so as BaseKvStoreService, sr as MiddlewareService, uo as KvStore, ur as inputFileSchema, vo as UploadFile, vr as HealthResponseFormat, wo as CircuitBreakerStats, wr as EventEmitter, xo as uploadFileSchema, xr as getHealthResponseFormat, yo as UploadFileTraceContext, yr as HealthStatus, zi as UploadFileDataStoresShape } from "../index-j_n72QK0.cjs";
2
+ export { BaseEventEmitter, BaseEventEmitterService, BaseKvStore, BaseKvStoreService, BufferedUploadFileDataStore, CircuitBreakerHealthSummary, CircuitBreakerStateData, CircuitBreakerStateValue, CircuitBreakerStats, CircuitBreakerStore, CircuitBreakerStoreService, ComponentHealth, DEFAULT_HEALTH_CHECK_CONFIG, DEFAULT_MULTIPART_PART_SIZE, DEFAULT_STREAMING_CONFIG, DataStore, DataStoreCapabilities, DataStoreConfig, DataStoreWriteOptions, DeadLetterQueueKVStore, DlqHealthSummary, EventBroadcaster, EventBroadcasterService, EventEmitter, FlowEventEmitter, FlowJobKVStore, HealthCheckConfig, HealthComponents, HealthResponse, HealthResponseFormat, HealthStatus, InputFile, JsonValue, KvStore, Middleware, MiddlewareContext, MiddlewareNext, MiddlewareService, MiddlewareServiceLive, StreamWriteOptions, StreamWriteResult, StreamingConfig, TypedEventEmitter, TypedKvStore, UploadEvent, UploadEventEmitter, UploadEventType, UploadFile, UploadFileDataStore, UploadFileDataStores, UploadFileDataStoresShape, UploadFileKVStore, UploadFileTraceContext, UploadStrategy, WebSocketConnection, WebSocketMessage, createDataStoreLayer, createInitialCircuitBreakerState, deadLetterQueueKvStore, eventToMessageSerializer, flowEventEmitter, flowJobKvStore, formatHealthAsText, getHealthResponseFormat, inputFileSchema, isDataStore, jsonSerializer, traceContextSchema, uploadEventEmitter, uploadEventSchema, uploadFileKvStore, uploadFileSchema, webSocketMessageSchema };
@@ -1,6 +1,6 @@
1
- import "../uploadista-error-DR0XimpE.mjs";
2
- import "../index-C-svZlpj.mjs";
3
- import { Ai as DataStore, Ar as uploadEventEmitter, Bi as UploadStrategy, Cr as BaseEventEmitterService, Di as BufferedUploadFileDataStore, Dr as UploadEventEmitter, Er as TypedEventEmitter, Fi as StreamWriteResult, Fr as UploadEventType, Hi as isDataStore, Ii as StreamingConfig, Ir as uploadEventSchema, Li as UploadFileDataStore, Lr as EventBroadcaster, Mi as DataStoreConfig, Mr as WebSocketMessage, Ni as DataStoreWriteOptions, Nr as webSocketMessageSchema, Oi as DEFAULT_MULTIPART_PART_SIZE, Or as eventToMessageSerializer, Pi as StreamWriteOptions, Pr as UploadEvent, Ri as UploadFileDataStores, Rr as EventBroadcasterService, Sr as BaseEventEmitter, Tr as FlowEventEmitter, Vi as createDataStoreLayer, _o as UploadFile, _r as HealthResponse, ao as createInitialCircuitBreakerState, ar as MiddlewareContext, bo as uploadFileSchema, br as formatHealthAsText, co as DeadLetterQueueKVStore, cr as MiddlewareServiceLive, do as TypedKvStore, dr as CircuitBreakerHealthSummary, eo as CircuitBreakerStateData, fo as UploadFileKVStore, fr as ComponentHealth, go as uploadFileKvStore, gr as HealthComponents, ho as jsonSerializer, hr as HealthCheckConfig, io as CircuitBreakerStoreService, ir as Middleware, ji as DataStoreCapabilities, jr as WebSocketConnection, ki as DEFAULT_STREAMING_CONFIG, kr as flowEventEmitter, lo as FlowJobKVStore, lr as InputFile, mo as flowJobKvStore, mr as DlqHealthSummary, no as CircuitBreakerStats, oo as BaseKvStore, or as MiddlewareNext, po as deadLetterQueueKvStore, pr as DEFAULT_HEALTH_CHECK_CONFIG, ro as CircuitBreakerStore, so as BaseKvStoreService, sr as MiddlewareService, to as CircuitBreakerStateValue, uo as KvStore, ur as inputFileSchema, vo as UploadFileTraceContext, vr as HealthResponseFormat, wr as EventEmitter, xr as getHealthResponseFormat, yo as traceContextSchema, yr as HealthStatus, zi as UploadFileDataStoresShape } from "../index-RuQUCROH.mjs";
4
- import "../index-B9V5SSxl.mjs";
5
- import "../index-BFSHumky.mjs";
6
- export { BaseEventEmitter, BaseEventEmitterService, BaseKvStore, BaseKvStoreService, BufferedUploadFileDataStore, CircuitBreakerHealthSummary, CircuitBreakerStateData, CircuitBreakerStateValue, CircuitBreakerStats, CircuitBreakerStore, CircuitBreakerStoreService, ComponentHealth, DEFAULT_HEALTH_CHECK_CONFIG, DEFAULT_MULTIPART_PART_SIZE, DEFAULT_STREAMING_CONFIG, DataStore, DataStoreCapabilities, DataStoreConfig, DataStoreWriteOptions, DeadLetterQueueKVStore, DlqHealthSummary, EventBroadcaster, EventBroadcasterService, EventEmitter, FlowEventEmitter, FlowJobKVStore, HealthCheckConfig, HealthComponents, HealthResponse, HealthResponseFormat, HealthStatus, InputFile, KvStore, Middleware, MiddlewareContext, MiddlewareNext, MiddlewareService, MiddlewareServiceLive, StreamWriteOptions, StreamWriteResult, StreamingConfig, TypedEventEmitter, TypedKvStore, UploadEvent, UploadEventEmitter, UploadEventType, UploadFile, UploadFileDataStore, UploadFileDataStores, UploadFileDataStoresShape, UploadFileKVStore, UploadFileTraceContext, UploadStrategy, WebSocketConnection, WebSocketMessage, createDataStoreLayer, createInitialCircuitBreakerState, deadLetterQueueKvStore, eventToMessageSerializer, flowEventEmitter, flowJobKvStore, formatHealthAsText, getHealthResponseFormat, inputFileSchema, isDataStore, jsonSerializer, traceContextSchema, uploadEventEmitter, uploadEventSchema, uploadFileKvStore, uploadFileSchema, webSocketMessageSchema };
1
+ import "../uploadista-error-B1qbOy9N.mjs";
2
+ import "../index-DWe68pTi.mjs";
3
+ import { Ai as DataStore, Ar as uploadEventEmitter, Bi as UploadStrategy, Co as CircuitBreakerStateValue, Cr as BaseEventEmitterService, Di as BufferedUploadFileDataStore, Do as createInitialCircuitBreakerState, Dr as UploadEventEmitter, Eo as CircuitBreakerStoreService, Er as TypedEventEmitter, Fi as StreamWriteResult, Fr as UploadEventType, Hi as isDataStore, Ii as StreamingConfig, Ir as uploadEventSchema, Li as UploadFileDataStore, Lr as EventBroadcaster, Mi as DataStoreConfig, Mr as WebSocketMessage, Ni as DataStoreWriteOptions, Nr as webSocketMessageSchema, Oi as DEFAULT_MULTIPART_PART_SIZE, Or as eventToMessageSerializer, Pi as StreamWriteOptions, Pr as UploadEvent, Ri as UploadFileDataStores, Rr as EventBroadcasterService, So as CircuitBreakerStateData, Sr as BaseEventEmitter, To as CircuitBreakerStore, Tr as FlowEventEmitter, Vi as createDataStoreLayer, _o as JsonValue, _r as HealthResponse, ar as MiddlewareContext, bo as traceContextSchema, br as formatHealthAsText, co as DeadLetterQueueKVStore, cr as MiddlewareServiceLive, do as TypedKvStore, dr as CircuitBreakerHealthSummary, fo as UploadFileKVStore, fr as ComponentHealth, go as uploadFileKvStore, gr as HealthComponents, ho as jsonSerializer, hr as HealthCheckConfig, ir as Middleware, ji as DataStoreCapabilities, jr as WebSocketConnection, ki as DEFAULT_STREAMING_CONFIG, kr as flowEventEmitter, lo as FlowJobKVStore, lr as InputFile, mo as flowJobKvStore, mr as DlqHealthSummary, oo as BaseKvStore, or as MiddlewareNext, po as deadLetterQueueKvStore, pr as DEFAULT_HEALTH_CHECK_CONFIG, so as BaseKvStoreService, sr as MiddlewareService, uo as KvStore, ur as inputFileSchema, vo as UploadFile, vr as HealthResponseFormat, wo as CircuitBreakerStats, wr as EventEmitter, xo as uploadFileSchema, xr as getHealthResponseFormat, yo as UploadFileTraceContext, yr as HealthStatus, zi as UploadFileDataStoresShape } from "../index-BKY0VjsL.mjs";
4
+ import "../index-D8MZ6P3o.mjs";
5
+ import "../index-DQuMQssI.mjs";
6
+ export { BaseEventEmitter, BaseEventEmitterService, BaseKvStore, BaseKvStoreService, BufferedUploadFileDataStore, CircuitBreakerHealthSummary, CircuitBreakerStateData, CircuitBreakerStateValue, CircuitBreakerStats, CircuitBreakerStore, CircuitBreakerStoreService, ComponentHealth, DEFAULT_HEALTH_CHECK_CONFIG, DEFAULT_MULTIPART_PART_SIZE, DEFAULT_STREAMING_CONFIG, DataStore, DataStoreCapabilities, DataStoreConfig, DataStoreWriteOptions, DeadLetterQueueKVStore, DlqHealthSummary, EventBroadcaster, EventBroadcasterService, EventEmitter, FlowEventEmitter, FlowJobKVStore, HealthCheckConfig, HealthComponents, HealthResponse, HealthResponseFormat, HealthStatus, InputFile, JsonValue, KvStore, Middleware, MiddlewareContext, MiddlewareNext, MiddlewareService, MiddlewareServiceLive, StreamWriteOptions, StreamWriteResult, StreamingConfig, TypedEventEmitter, TypedKvStore, UploadEvent, UploadEventEmitter, UploadEventType, UploadFile, UploadFileDataStore, UploadFileDataStores, UploadFileDataStoresShape, UploadFileKVStore, UploadFileTraceContext, UploadStrategy, WebSocketConnection, WebSocketMessage, createDataStoreLayer, createInitialCircuitBreakerState, deadLetterQueueKvStore, eventToMessageSerializer, flowEventEmitter, flowJobKvStore, formatHealthAsText, getHealthResponseFormat, inputFileSchema, isDataStore, jsonSerializer, traceContextSchema, uploadEventEmitter, uploadEventSchema, uploadFileKvStore, uploadFileSchema, webSocketMessageSchema };
@@ -1 +1 @@
1
- import"../uploadista-error-CkSxSyNo.mjs";import"../errors-CtPUOWNd.mjs";import{A as e,C as t,D as n,E as r,F as i,I as a,L as o,M as s,N as c,O as l,P as u,S as d,T as f,_ as p,a as m,b as h,c as g,d as _,f as v,g as y,h as b,i as x,j as S,k as C,l as w,m as T,n as E,o as D,p as O,r as k,s as A,t as j,u as M,v as N,w as P,x as F,y as I}from"../types-DKGQJIEr.mjs";export{M as BaseEventEmitterService,C as BaseKvStoreService,N as BufferedUploadFileDataStore,n as CircuitBreakerStoreService,A as DEFAULT_HEALTH_CHECK_CONFIG,I as DEFAULT_MULTIPART_PART_SIZE,h as DEFAULT_STREAMING_CONFIG,e as DeadLetterQueueKVStore,p as EventBroadcasterService,_ as FlowEventEmitter,S as FlowJobKVStore,x as MiddlewareService,m as MiddlewareServiceLive,v as TypedEventEmitter,s as TypedKvStore,O as UploadEventEmitter,E as UploadEventType,F as UploadFileDataStore,d as UploadFileDataStores,c as UploadFileKVStore,t as createDataStoreLayer,l as createInitialCircuitBreakerState,u as deadLetterQueueKvStore,T as eventToMessageSerializer,b as flowEventEmitter,i as flowJobKvStore,g as formatHealthAsText,w as getHealthResponseFormat,D as inputFileSchema,P as isDataStore,a as jsonSerializer,f as traceContextSchema,y as uploadEventEmitter,k as uploadEventSchema,o as uploadFileKvStore,r as uploadFileSchema,j as webSocketMessageSchema};
1
+ import"../uploadista-error-CkSxSyNo.mjs";import"../errors-CtPUOWNd.mjs";import{A as e,C as t,D as n,E as r,F as i,I as a,L as o,M as s,N as c,O as l,P as u,S as d,T as f,_ as p,a as m,b as h,c as g,d as _,f as v,g as y,h as b,i as x,j as S,k as C,l as w,m as T,n as E,o as D,p as O,r as k,s as A,t as j,u as M,v as N,w as P,x as F,y as I}from"../types-BRnwrJDg.mjs";export{M as BaseEventEmitterService,n as BaseKvStoreService,N as BufferedUploadFileDataStore,a as CircuitBreakerStoreService,A as DEFAULT_HEALTH_CHECK_CONFIG,I as DEFAULT_MULTIPART_PART_SIZE,h as DEFAULT_STREAMING_CONFIG,l as DeadLetterQueueKVStore,p as EventBroadcasterService,_ as FlowEventEmitter,C as FlowJobKVStore,x as MiddlewareService,m as MiddlewareServiceLive,v as TypedEventEmitter,e as TypedKvStore,O as UploadEventEmitter,E as UploadEventType,F as UploadFileDataStore,d as UploadFileDataStores,S as UploadFileKVStore,t as createDataStoreLayer,o as createInitialCircuitBreakerState,s as deadLetterQueueKvStore,T as eventToMessageSerializer,b as flowEventEmitter,c as flowJobKvStore,g as formatHealthAsText,w as getHealthResponseFormat,D as inputFileSchema,P as isDataStore,u as jsonSerializer,f as traceContextSchema,y as uploadEventEmitter,k as uploadEventSchema,i as uploadFileKvStore,r as uploadFileSchema,j as webSocketMessageSchema};
@@ -0,0 +1 @@
1
+ var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));const c=require(`./uploadista-error-CLWoRAAr.cjs`);let l=require(`effect`),u=require(`zod`);u=s(u);var d=class extends l.Context.Tag(`CircuitBreakerStoreService`)(){};function f(e){let t=Date.now();return{state:`closed`,failureCount:0,lastStateChange:t,halfOpenSuccesses:0,windowStart:t,config:e}}var p=class{constructor(e,t,n,r){this.baseStore=e,this.keyPrefix=t,this.serialize=n,this.deserialize=r}get=e=>this.baseStore.get(this.keyPrefix+e).pipe(l.Effect.flatMap(t=>{if(t===null)return l.Effect.fail(c.n.fromCode(`FILE_NOT_FOUND`,{cause:`Key "${e}" not found`}));try{return l.Effect.succeed(this.deserialize(t))}catch(t){return l.Effect.fail(new c.n({code:`VALIDATION_ERROR`,status:400,body:`Failed to deserialize value for key "${e}"`,cause:t}))}}));set=(e,t)=>{try{let n=this.serialize(t);return this.baseStore.set(this.keyPrefix+e,n)}catch(t){return l.Effect.fail(new c.n({code:`VALIDATION_ERROR`,status:400,body:`Failed to serialize value for key "${e}"`,cause:t}))}};delete=e=>this.baseStore.delete(this.keyPrefix+e);list=()=>this.baseStore.list?this.baseStore.list(this.keyPrefix).pipe(l.Effect.map(e=>e.map(e=>e.startsWith(this.keyPrefix)?e.slice(this.keyPrefix.length):e))):l.Effect.fail(new c.n({code:`UNKNOWN_ERROR`,status:501,body:`List operation not supported by this store`}))};const m={serialize:e=>JSON.stringify(e),deserialize:e=>JSON.parse(e)};var h=class extends l.Context.Tag(`BaseKvStore`)(){},g=class extends l.Context.Tag(`UploadFileKVStore`)(){};const _=l.Layer.effect(g,l.Effect.gen(function*(){return new p(yield*h,`uploadista:upload-file:`,m.serialize,m.deserialize)}));var v=class extends l.Context.Tag(`FlowJobKVStore`)(){};const y=l.Layer.effect(v,l.Effect.gen(function*(){return new p(yield*h,`uploadista:flow-job:`,m.serialize,m.deserialize)}));var b=class extends l.Context.Tag(`DeadLetterQueueKVStore`)(){};const x=l.Layer.effect(b,l.Effect.gen(function*(){return new p(yield*h,`uploadista:dlq:`,m.serialize,m.deserialize)})),S=u.z.object({traceId:u.z.string(),spanId:u.z.string(),traceFlags:u.z.number()}),C=u.z.lazy(()=>u.z.union([u.z.string(),u.z.number(),u.z.boolean(),u.z.null(),u.z.array(C),u.z.record(u.z.string(),C)])),w=u.z.object({id:u.z.string(),size:u.z.number().optional(),offset:u.z.number(),metadata:u.z.record(u.z.string(),C).optional(),creationDate:u.z.string().optional(),url:u.z.string().optional(),sizeIsDeferred:u.z.boolean().optional(),checksum:u.z.string().optional(),checksumAlgorithm:u.z.string().optional(),storage:u.z.object({id:u.z.string(),type:u.z.string(),path:u.z.string().optional(),uploadId:u.z.string().optional(),bucket:u.z.string().optional(),parts:u.z.array(u.z.object({partNumber:u.z.number(),etag:u.z.string(),size:u.z.number()})).optional()}),flow:u.z.object({flowId:u.z.string(),nodeId:u.z.string(),jobId:u.z.string()}).optional(),traceContext:S.optional()}),T={fileSizeThreshold:1048576,chunkSize:65536},E=5*1024*1024;var D=class extends l.Context.Tag(`UploadFileDataStore`)(){},O=class extends l.Context.Tag(`BufferedUploadFileDataStore`)(){},k=class extends l.Context.Tag(`UploadFileDataStores`)(){};const A=e=>`create`in e&&`write`in e,j=async e=>{if(l.Layer.isLayer(e))return e;if(l.Effect.isEffect(e))return l.Layer.effect(k,l.Effect.gen(function*(){let t=yield*e;return{getDataStore:e=>l.Effect.succeed(t),bufferedDataStore:l.Effect.succeed(void 0)}}));if(A(e)){let t=e;return l.Layer.succeed(k,{getDataStore:e=>l.Effect.succeed(t),bufferedDataStore:l.Effect.succeed(void 0)})}let t=e,n=t.default||Object.keys(t.stores)[0],r={};for(let[e,n]of Object.entries(t.stores))`pipe`in n&&!(`create`in n)?r[e]=await l.Effect.runPromise(n):r[e]=n;return l.Layer.succeed(k,{getDataStore:e=>{let t=r[e]||(n?r[n]:void 0);return t?l.Effect.succeed(t):l.Effect.fail(c.n.fromCode(`FILE_NOT_FOUND`))},bufferedDataStore:l.Effect.succeed(void 0)})};var M=class extends l.Context.Tag(`EventBroadcaster`)(){},N=class{constructor(e,t){this.baseEmitter=e,this.eventToMessage=t}subscribe=(e,t)=>this.baseEmitter.subscribe(e,t);unsubscribe=e=>this.baseEmitter.unsubscribe(e);emit=(e,t)=>{let n=this.eventToMessage(t);return this.baseEmitter.emit(e,n)}};const P=e=>({eventToMessage:t=>JSON.stringify({type:e,payload:t,timestamp:new Date().toISOString()})});var F=class extends l.Context.Tag(`BaseEventEmitter`)(){},I=class extends l.Context.Tag(`UploadEventEmitter`)(){};const L=l.Layer.effect(I,l.Effect.gen(function*(){return new N(yield*F,P(`upload_event`).eventToMessage)}));var R=class extends l.Context.Tag(`FlowEventEmitter`)(){};const z=l.Layer.effect(R,l.Effect.gen(function*(){return new N(yield*F,P(`flow_event`).eventToMessage)})),B={timeout:5e3,checkStorage:!0,checkKvStore:!0,checkEventBroadcaster:!0};function V(e){return e?.includes(`text/plain`)?`text`:`json`}function H(e){switch(e){case`healthy`:return`OK`;case`degraded`:return`OK`;case`unhealthy`:return`Service Unavailable`}}const U=u.z.object({uploadLengthDeferred:u.z.boolean().optional(),storageId:u.z.string(),size:u.z.number().optional(),sizeHint:u.z.number().optional(),type:u.z.string(),fileName:u.z.string().optional(),lastModified:u.z.number().optional(),metadata:u.z.string().optional(),checksum:u.z.string().optional(),checksumAlgorithm:u.z.string().optional(),flow:u.z.object({flowId:u.z.string(),nodeId:u.z.string(),jobId:u.z.string()}).optional()}).refine(e=>e.uploadLengthDeferred===!0?!0:e.size!==void 0&&e.size>=0,{message:`size is required when uploadLengthDeferred is not true`,path:[`size`]});var W=class extends l.Context.Tag(`MiddlewareService`)(){};const G=l.Layer.succeed(W,W.of({execute:(e,t,n)=>l.Effect.gen(function*(){if(e.length===0)return yield*l.Effect.tryPromise({try:()=>n(),catch:e=>e});let r=e.reduceRight((e,n)=>()=>n(t,e),n);return yield*l.Effect.tryPromise({try:()=>r(),catch:e=>e})})}));let K=function(e){return e.UPLOAD_STARTED=`upload-started`,e.UPLOAD_PROGRESS=`upload-progress`,e.UPLOAD_COMPLETE=`upload-complete`,e.UPLOAD_FAILED=`upload-failed`,e.UPLOAD_VALIDATION_SUCCESS=`upload-validation-success`,e.UPLOAD_VALIDATION_FAILED=`upload-validation-failed`,e.UPLOAD_VALIDATION_WARNING=`upload-validation-warning`,e}({});const q=u.z.object({flowId:u.z.string(),nodeId:u.z.string(),jobId:u.z.string()}).optional(),J=u.z.union([u.z.object({type:u.z.union([u.z.literal(K.UPLOAD_STARTED),u.z.literal(K.UPLOAD_COMPLETE)]),data:w,flow:q}),u.z.object({type:u.z.literal(K.UPLOAD_PROGRESS),data:u.z.object({id:u.z.string(),progress:u.z.number(),total:u.z.number()}),flow:q}),u.z.object({type:u.z.literal(K.UPLOAD_FAILED),data:u.z.object({id:u.z.string(),error:u.z.string()}),flow:q}),u.z.object({type:u.z.literal(K.UPLOAD_VALIDATION_SUCCESS),data:u.z.object({id:u.z.string(),validationType:u.z.enum([`checksum`,`mimetype`]),algorithm:u.z.string().optional()}),flow:q}),u.z.object({type:u.z.literal(K.UPLOAD_VALIDATION_FAILED),data:u.z.object({id:u.z.string(),reason:u.z.string(),expected:u.z.string(),actual:u.z.string()}),flow:q}),u.z.object({type:u.z.literal(K.UPLOAD_VALIDATION_WARNING),data:u.z.object({id:u.z.string(),message:u.z.string()}),flow:q})]),Y=u.default.union([u.default.object({type:u.default.literal(`upload_event`),payload:J,timestamp:u.default.string().optional()}),u.default.object({type:u.default.literal(`flow_event`),payload:u.default.any(),timestamp:u.default.string().optional()}),u.default.object({type:u.default.literal(`subscribed`),payload:u.default.object({eventKey:u.default.string()}),timestamp:u.default.string().optional()}),u.default.object({type:u.default.literal(`error`),message:u.default.string().optional()}),u.default.object({type:u.default.literal(`pong`),timestamp:u.default.string().optional()}),u.default.object({type:u.default.literal(`ping`),timestamp:u.default.string().optional()}),u.default.object({type:u.default.literal(`connection`),message:u.default.string().optional(),uploadId:u.default.string().optional(),timestamp:u.default.string().optional()})]);Object.defineProperty(exports,`A`,{enumerable:!0,get:function(){return p}}),Object.defineProperty(exports,`C`,{enumerable:!0,get:function(){return j}}),Object.defineProperty(exports,`D`,{enumerable:!0,get:function(){return h}}),Object.defineProperty(exports,`E`,{enumerable:!0,get:function(){return w}}),Object.defineProperty(exports,`F`,{enumerable:!0,get:function(){return _}}),Object.defineProperty(exports,`I`,{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,`L`,{enumerable:!0,get:function(){return f}}),Object.defineProperty(exports,`M`,{enumerable:!0,get:function(){return x}}),Object.defineProperty(exports,`N`,{enumerable:!0,get:function(){return y}}),Object.defineProperty(exports,`O`,{enumerable:!0,get:function(){return b}}),Object.defineProperty(exports,`P`,{enumerable:!0,get:function(){return m}}),Object.defineProperty(exports,`R`,{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,`S`,{enumerable:!0,get:function(){return k}}),Object.defineProperty(exports,`T`,{enumerable:!0,get:function(){return S}}),Object.defineProperty(exports,`_`,{enumerable:!0,get:function(){return M}}),Object.defineProperty(exports,`a`,{enumerable:!0,get:function(){return G}}),Object.defineProperty(exports,`b`,{enumerable:!0,get:function(){return T}}),Object.defineProperty(exports,`c`,{enumerable:!0,get:function(){return H}}),Object.defineProperty(exports,`d`,{enumerable:!0,get:function(){return R}}),Object.defineProperty(exports,`f`,{enumerable:!0,get:function(){return N}}),Object.defineProperty(exports,`g`,{enumerable:!0,get:function(){return L}}),Object.defineProperty(exports,`h`,{enumerable:!0,get:function(){return z}}),Object.defineProperty(exports,`i`,{enumerable:!0,get:function(){return W}}),Object.defineProperty(exports,`j`,{enumerable:!0,get:function(){return g}}),Object.defineProperty(exports,`k`,{enumerable:!0,get:function(){return v}}),Object.defineProperty(exports,`l`,{enumerable:!0,get:function(){return V}}),Object.defineProperty(exports,`m`,{enumerable:!0,get:function(){return P}}),Object.defineProperty(exports,`n`,{enumerable:!0,get:function(){return K}}),Object.defineProperty(exports,`o`,{enumerable:!0,get:function(){return U}}),Object.defineProperty(exports,`p`,{enumerable:!0,get:function(){return I}}),Object.defineProperty(exports,`r`,{enumerable:!0,get:function(){return J}}),Object.defineProperty(exports,`s`,{enumerable:!0,get:function(){return B}}),Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return Y}}),Object.defineProperty(exports,`u`,{enumerable:!0,get:function(){return F}}),Object.defineProperty(exports,`v`,{enumerable:!0,get:function(){return O}}),Object.defineProperty(exports,`w`,{enumerable:!0,get:function(){return A}}),Object.defineProperty(exports,`x`,{enumerable:!0,get:function(){return D}}),Object.defineProperty(exports,`y`,{enumerable:!0,get:function(){return 5242880}});
@@ -0,0 +1,2 @@
1
+ import{n as e}from"./uploadista-error-CkSxSyNo.mjs";import{Context as t,Effect as n,Layer as r}from"effect";import i,{z as a}from"zod";var o=class extends t.Tag(`CircuitBreakerStoreService`)(){};function s(e){let t=Date.now();return{state:`closed`,failureCount:0,lastStateChange:t,halfOpenSuccesses:0,windowStart:t,config:e}}var c=class{constructor(e,t,n,r){this.baseStore=e,this.keyPrefix=t,this.serialize=n,this.deserialize=r}get=t=>this.baseStore.get(this.keyPrefix+t).pipe(n.flatMap(r=>{if(r===null)return n.fail(e.fromCode(`FILE_NOT_FOUND`,{cause:`Key "${t}" not found`}));try{return n.succeed(this.deserialize(r))}catch(r){return n.fail(new e({code:`VALIDATION_ERROR`,status:400,body:`Failed to deserialize value for key "${t}"`,cause:r}))}}));set=(t,r)=>{try{let e=this.serialize(r);return this.baseStore.set(this.keyPrefix+t,e)}catch(r){return n.fail(new e({code:`VALIDATION_ERROR`,status:400,body:`Failed to serialize value for key "${t}"`,cause:r}))}};delete=e=>this.baseStore.delete(this.keyPrefix+e);list=()=>this.baseStore.list?this.baseStore.list(this.keyPrefix).pipe(n.map(e=>e.map(e=>e.startsWith(this.keyPrefix)?e.slice(this.keyPrefix.length):e))):n.fail(new e({code:`UNKNOWN_ERROR`,status:501,body:`List operation not supported by this store`}))};const l={serialize:e=>JSON.stringify(e),deserialize:e=>JSON.parse(e)};var u=class extends t.Tag(`BaseKvStore`)(){},d=class extends t.Tag(`UploadFileKVStore`)(){};const f=r.effect(d,n.gen(function*(){return new c(yield*u,`uploadista:upload-file:`,l.serialize,l.deserialize)}));var p=class extends t.Tag(`FlowJobKVStore`)(){};const m=r.effect(p,n.gen(function*(){return new c(yield*u,`uploadista:flow-job:`,l.serialize,l.deserialize)}));var h=class extends t.Tag(`DeadLetterQueueKVStore`)(){};const g=r.effect(h,n.gen(function*(){return new c(yield*u,`uploadista:dlq:`,l.serialize,l.deserialize)})),_=a.object({traceId:a.string(),spanId:a.string(),traceFlags:a.number()}),v=a.lazy(()=>a.union([a.string(),a.number(),a.boolean(),a.null(),a.array(v),a.record(a.string(),v)])),y=a.object({id:a.string(),size:a.number().optional(),offset:a.number(),metadata:a.record(a.string(),v).optional(),creationDate:a.string().optional(),url:a.string().optional(),sizeIsDeferred:a.boolean().optional(),checksum:a.string().optional(),checksumAlgorithm:a.string().optional(),storage:a.object({id:a.string(),type:a.string(),path:a.string().optional(),uploadId:a.string().optional(),bucket:a.string().optional(),parts:a.array(a.object({partNumber:a.number(),etag:a.string(),size:a.number()})).optional()}),flow:a.object({flowId:a.string(),nodeId:a.string(),jobId:a.string()}).optional(),traceContext:_.optional()}),b={fileSizeThreshold:1048576,chunkSize:65536},x=5*1024*1024;var S=class extends t.Tag(`UploadFileDataStore`)(){},C=class extends t.Tag(`BufferedUploadFileDataStore`)(){},w=class extends t.Tag(`UploadFileDataStores`)(){};const T=e=>`create`in e&&`write`in e,E=async t=>{if(r.isLayer(t))return t;if(n.isEffect(t))return r.effect(w,n.gen(function*(){let e=yield*t;return{getDataStore:t=>n.succeed(e),bufferedDataStore:n.succeed(void 0)}}));if(T(t)){let e=t;return r.succeed(w,{getDataStore:t=>n.succeed(e),bufferedDataStore:n.succeed(void 0)})}let i=t,a=i.default||Object.keys(i.stores)[0],o={};for(let[e,t]of Object.entries(i.stores))`pipe`in t&&!(`create`in t)?o[e]=await n.runPromise(t):o[e]=t;return r.succeed(w,{getDataStore:t=>{let r=o[t]||(a?o[a]:void 0);return r?n.succeed(r):n.fail(e.fromCode(`FILE_NOT_FOUND`))},bufferedDataStore:n.succeed(void 0)})};var D=class extends t.Tag(`EventBroadcaster`)(){},O=class{constructor(e,t){this.baseEmitter=e,this.eventToMessage=t}subscribe=(e,t)=>this.baseEmitter.subscribe(e,t);unsubscribe=e=>this.baseEmitter.unsubscribe(e);emit=(e,t)=>{let n=this.eventToMessage(t);return this.baseEmitter.emit(e,n)}};const k=e=>({eventToMessage:t=>JSON.stringify({type:e,payload:t,timestamp:new Date().toISOString()})});var A=class extends t.Tag(`BaseEventEmitter`)(){},j=class extends t.Tag(`UploadEventEmitter`)(){};const M=r.effect(j,n.gen(function*(){return new O(yield*A,k(`upload_event`).eventToMessage)}));var N=class extends t.Tag(`FlowEventEmitter`)(){};const P=r.effect(N,n.gen(function*(){return new O(yield*A,k(`flow_event`).eventToMessage)})),F={timeout:5e3,checkStorage:!0,checkKvStore:!0,checkEventBroadcaster:!0};function I(e){return e?.includes(`text/plain`)?`text`:`json`}function L(e){switch(e){case`healthy`:return`OK`;case`degraded`:return`OK`;case`unhealthy`:return`Service Unavailable`}}const R=a.object({uploadLengthDeferred:a.boolean().optional(),storageId:a.string(),size:a.number().optional(),sizeHint:a.number().optional(),type:a.string(),fileName:a.string().optional(),lastModified:a.number().optional(),metadata:a.string().optional(),checksum:a.string().optional(),checksumAlgorithm:a.string().optional(),flow:a.object({flowId:a.string(),nodeId:a.string(),jobId:a.string()}).optional()}).refine(e=>e.uploadLengthDeferred===!0?!0:e.size!==void 0&&e.size>=0,{message:`size is required when uploadLengthDeferred is not true`,path:[`size`]});var z=class extends t.Tag(`MiddlewareService`)(){};const B=r.succeed(z,z.of({execute:(e,t,r)=>n.gen(function*(){if(e.length===0)return yield*n.tryPromise({try:()=>r(),catch:e=>e});let i=e.reduceRight((e,n)=>()=>n(t,e),r);return yield*n.tryPromise({try:()=>i(),catch:e=>e})})}));let V=function(e){return e.UPLOAD_STARTED=`upload-started`,e.UPLOAD_PROGRESS=`upload-progress`,e.UPLOAD_COMPLETE=`upload-complete`,e.UPLOAD_FAILED=`upload-failed`,e.UPLOAD_VALIDATION_SUCCESS=`upload-validation-success`,e.UPLOAD_VALIDATION_FAILED=`upload-validation-failed`,e.UPLOAD_VALIDATION_WARNING=`upload-validation-warning`,e}({});const H=a.object({flowId:a.string(),nodeId:a.string(),jobId:a.string()}).optional(),U=a.union([a.object({type:a.union([a.literal(V.UPLOAD_STARTED),a.literal(V.UPLOAD_COMPLETE)]),data:y,flow:H}),a.object({type:a.literal(V.UPLOAD_PROGRESS),data:a.object({id:a.string(),progress:a.number(),total:a.number()}),flow:H}),a.object({type:a.literal(V.UPLOAD_FAILED),data:a.object({id:a.string(),error:a.string()}),flow:H}),a.object({type:a.literal(V.UPLOAD_VALIDATION_SUCCESS),data:a.object({id:a.string(),validationType:a.enum([`checksum`,`mimetype`]),algorithm:a.string().optional()}),flow:H}),a.object({type:a.literal(V.UPLOAD_VALIDATION_FAILED),data:a.object({id:a.string(),reason:a.string(),expected:a.string(),actual:a.string()}),flow:H}),a.object({type:a.literal(V.UPLOAD_VALIDATION_WARNING),data:a.object({id:a.string(),message:a.string()}),flow:H})]),W=i.union([i.object({type:i.literal(`upload_event`),payload:U,timestamp:i.string().optional()}),i.object({type:i.literal(`flow_event`),payload:i.any(),timestamp:i.string().optional()}),i.object({type:i.literal(`subscribed`),payload:i.object({eventKey:i.string()}),timestamp:i.string().optional()}),i.object({type:i.literal(`error`),message:i.string().optional()}),i.object({type:i.literal(`pong`),timestamp:i.string().optional()}),i.object({type:i.literal(`ping`),timestamp:i.string().optional()}),i.object({type:i.literal(`connection`),message:i.string().optional(),uploadId:i.string().optional(),timestamp:i.string().optional()})]);export{c as A,E as C,u as D,y as E,f as F,o as I,s as L,g as M,m as N,h as O,l as P,w as S,_ as T,D as _,B as a,b,L as c,N as d,O as f,M as g,P as h,z as i,d as j,p as k,I as l,k as m,V as n,R as o,j as p,U as r,F as s,W as t,A as u,C as v,T as w,S as x,x as y};
2
+ //# sourceMappingURL=types-BRnwrJDg.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types-BRnwrJDg.mjs","names":["z"],"sources":["../src/types/circuit-breaker-store.ts","../src/types/kv-store.ts","../src/types/upload-file.ts","../src/types/data-store.ts","../src/types/event-broadcaster.ts","../src/types/event-emitter.ts","../src/types/health-check.ts","../src/types/input-file.ts","../src/types/middleware.ts","../src/types/upload-event.ts","../src/types/websocket.ts"],"sourcesContent":["/**\n * Circuit Breaker Store - Distributed state storage for circuit breakers.\n *\n * This module defines the interface for storing circuit breaker state in\n * distributed environments. It allows circuit breaker state to be shared\n * across multiple instances in a cluster.\n *\n * @module types/circuit-breaker-store\n */\n\nimport { Context, type Effect, Layer } from \"effect\";\nimport type { UploadistaError } from \"../errors\";\n\n// ============================================================================\n// State Types\n// ============================================================================\n\n/**\n * Circuit breaker state values.\n */\nexport type CircuitBreakerStateValue = \"closed\" | \"open\" | \"half-open\";\n\n/**\n * Persisted circuit breaker state data.\n *\n * This represents the full state of a circuit breaker that needs to be\n * stored and shared across instances.\n */\nexport interface CircuitBreakerStateData {\n /** Current circuit state */\n state: CircuitBreakerStateValue;\n /** Number of failures in current window */\n failureCount: number;\n /** Timestamp of last state transition */\n lastStateChange: number;\n /** Number of successful requests in half-open state */\n halfOpenSuccesses: number;\n /** Timestamp when the current failure window started */\n windowStart: number;\n /** Configuration snapshot for consistency */\n config: {\n failureThreshold: number;\n resetTimeout: number;\n halfOpenRequests: number;\n windowDuration: number;\n };\n}\n\n/**\n * Statistics about a circuit breaker.\n */\nexport interface CircuitBreakerStats {\n nodeType: string;\n state: CircuitBreakerStateValue;\n failureCount: number;\n halfOpenSuccesses: number;\n timeSinceLastStateChange: number;\n timeUntilHalfOpen?: number; // Only when state is \"open\"\n}\n\n// ============================================================================\n// Store Interface\n// ============================================================================\n\n/**\n * Interface for circuit breaker state storage.\n *\n * Implementations should handle distributed state for circuit breakers,\n * allowing multiple instances to share circuit state. The interface is\n * designed to work with eventually consistent stores - perfect consistency\n * is not required for circuit breaker functionality.\n *\n * @example\n * ```typescript\n * // Using the store\n * const store: CircuitBreakerStore = yield* CircuitBreakerStoreService;\n *\n * // Record a failure\n * const newCount = yield* store.incrementFailures(\"describe-image\", 60000);\n * if (newCount >= 5) {\n * yield* store.setState(\"describe-image\", {\n * state: \"open\",\n * failureCount: newCount,\n * lastStateChange: Date.now(),\n * // ...\n * });\n * }\n * ```\n */\nexport interface CircuitBreakerStore {\n /**\n * Gets the current state data for a circuit breaker.\n *\n * @param nodeType - The node type identifier\n * @returns The state data or null if no state exists\n */\n readonly getState: (\n nodeType: string,\n ) => Effect.Effect<CircuitBreakerStateData | null, UploadistaError>;\n\n /**\n * Sets the complete state for a circuit breaker.\n *\n * @param nodeType - The node type identifier\n * @param state - The new state data\n */\n readonly setState: (\n nodeType: string,\n state: CircuitBreakerStateData,\n ) => Effect.Effect<void, UploadistaError>;\n\n /**\n * Increments the failure count and returns the new count.\n *\n * This operation should be atomic where possible. For stores that don't\n * support atomic increment, a read-modify-write is acceptable as circuit\n * breakers tolerate eventual consistency.\n *\n * The implementation should also handle window expiry - if the window\n * has expired, reset the count before incrementing.\n *\n * @param nodeType - The node type identifier\n * @param windowDuration - Duration of the sliding window in milliseconds\n * @returns The new failure count after incrementing\n */\n readonly incrementFailures: (\n nodeType: string,\n windowDuration: number,\n ) => Effect.Effect<number, UploadistaError>;\n\n /**\n * Resets the failure count to zero.\n *\n * Called when circuit closes or on successful requests.\n *\n * @param nodeType - The node type identifier\n */\n readonly resetFailures: (\n nodeType: string,\n ) => Effect.Effect<void, UploadistaError>;\n\n /**\n * Increments the half-open success count.\n *\n * @param nodeType - The node type identifier\n * @returns The new half-open success count\n */\n readonly incrementHalfOpenSuccesses: (\n nodeType: string,\n ) => Effect.Effect<number, UploadistaError>;\n\n /**\n * Gets statistics for all tracked circuit breakers.\n *\n * @returns Map of node type to stats\n */\n readonly getAllStats: () => Effect.Effect<\n Map<string, CircuitBreakerStats>,\n UploadistaError\n >;\n\n /**\n * Deletes circuit breaker state for a node type.\n *\n * @param nodeType - The node type identifier\n */\n readonly delete: (nodeType: string) => Effect.Effect<void, UploadistaError>;\n}\n\n// ============================================================================\n// Effect Context\n// ============================================================================\n\n/**\n * Effect-TS context tag for the CircuitBreakerStore service.\n *\n * Use this to inject a circuit breaker store into your Effect programs.\n *\n * @example\n * ```typescript\n * const program = Effect.gen(function* () {\n * const cbStore = yield* CircuitBreakerStoreService;\n * const state = yield* cbStore.getState(\"my-node-type\");\n * // ...\n * });\n *\n * // Provide the implementation\n * const result = yield* program.pipe(\n * Effect.provide(kvCircuitBreakerStoreLayer)\n * );\n * ```\n */\nexport class CircuitBreakerStoreService extends Context.Tag(\n \"CircuitBreakerStoreService\",\n)<CircuitBreakerStoreService, CircuitBreakerStore>() {}\n\n// ============================================================================\n// Default State Factory\n// ============================================================================\n\n/**\n * Creates a default initial state for a circuit breaker.\n *\n * @param config - Circuit breaker configuration\n * @returns Initial state data with closed circuit\n */\nexport function createInitialCircuitBreakerState(config: {\n failureThreshold: number;\n resetTimeout: number;\n halfOpenRequests: number;\n windowDuration: number;\n}): CircuitBreakerStateData {\n const now = Date.now();\n return {\n state: \"closed\",\n failureCount: 0,\n lastStateChange: now,\n halfOpenSuccesses: 0,\n windowStart: now,\n config,\n };\n}\n","import { Context, Effect, Layer } from \"effect\";\nimport { UploadistaError } from \"../errors\";\nimport type { DeadLetterItem, FlowJob } from \"../flow\";\nimport type { UploadFile } from \"./upload-file\";\n\n/**\n * Base key-value store interface for raw string storage.\n *\n * This is the low-level interface that storage adapters implement.\n * It stores raw string values without type safety or serialization.\n *\n * @property get - Retrieves a value by key, returns null if not found\n * @property set - Stores a value with the given key\n * @property delete - Removes a value by key\n * @property list - Optional operation to list all keys with a given prefix\n *\n * @example\n * ```typescript\n * // Implement a BaseKvStore with Redis\n * const redisKvStore: BaseKvStore = {\n * get: (key) => Effect.tryPromise({\n * try: () => redis.get(key),\n * catch: (error) => UploadistaError.fromCode(\"UNKNOWN_ERROR\", { cause: error })\n * }),\n *\n * set: (key, value) => Effect.tryPromise({\n * try: () => redis.set(key, value),\n * catch: (error) => UploadistaError.fromCode(\"UNKNOWN_ERROR\", { cause: error })\n * }),\n *\n * delete: (key) => Effect.tryPromise({\n * try: () => redis.del(key),\n * catch: (error) => UploadistaError.fromCode(\"UNKNOWN_ERROR\", { cause: error })\n * }),\n *\n * list: (prefix) => Effect.tryPromise({\n * try: () => redis.keys(`${prefix}*`),\n * catch: (error) => UploadistaError.fromCode(\"UNKNOWN_ERROR\", { cause: error })\n * })\n * };\n * ```\n */\nexport interface BaseKvStore {\n readonly get: (key: string) => Effect.Effect<string | null, UploadistaError>;\n readonly set: (\n key: string,\n value: string,\n ) => Effect.Effect<void, UploadistaError>;\n readonly delete: (key: string) => Effect.Effect<void, UploadistaError>;\n readonly list?: (\n keyPrefix: string,\n ) => Effect.Effect<Array<string>, UploadistaError>;\n}\n\n/**\n * Type-safe key-value store interface with automatic serialization.\n *\n * This wraps a BaseKvStore and handles JSON serialization/deserialization\n * for a specific data type, providing type safety and eliminating the need\n * for manual JSON.stringify/parse calls.\n *\n * @template TData - The type of data stored in this KV store\n *\n * @property get - Retrieves and deserializes a value, fails if not found\n * @property set - Serializes and stores a value\n * @property delete - Removes a value by key\n * @property list - Optional operation to list all keys (without prefix)\n *\n * @example\n * ```typescript\n * // Use a typed KV store\n * const uploadStore: KvStore<UploadFile> = new TypedKvStore(\n * baseStore,\n * \"uploads:\",\n * jsonSerializer.serialize,\n * jsonSerializer.deserialize\n * );\n *\n * // Store and retrieve typed data\n * const program = Effect.gen(function* () {\n * const file: UploadFile = {\n * id: \"file123\",\n * offset: 0,\n * storage: { id: \"s3\", type: \"s3\" }\n * };\n *\n * // Automatic serialization\n * yield* uploadStore.set(\"file123\", file);\n *\n * // Automatic deserialization with type safety\n * const retrieved = yield* uploadStore.get(\"file123\");\n * console.log(retrieved.offset); // TypeScript knows this is a number\n * });\n * ```\n */\nexport type KvStore<TData> = {\n readonly get: (key: string) => Effect.Effect<TData, UploadistaError>;\n readonly set: (\n key: string,\n value: TData,\n ) => Effect.Effect<void, UploadistaError>;\n readonly delete: (key: string) => Effect.Effect<void, UploadistaError>;\n readonly list?: () => Effect.Effect<Array<string>, UploadistaError>;\n};\n\n/**\n * Typed wrapper class that adds serialization to a BaseKvStore.\n *\n * This class implements the KvStore interface by wrapping a BaseKvStore\n * and handling serialization/deserialization for a specific type. It also\n * adds a key prefix to isolate different data types in the same store.\n *\n * @template TData - The type of data to store\n *\n * @example\n * ```typescript\n * // Create a typed store for UploadFile\n * const uploadFileStore = new TypedKvStore<UploadFile>(\n * baseKvStore,\n * \"uploadista:upload-file:\", // All keys will be prefixed\n * (data) => JSON.stringify(data),\n * (str) => JSON.parse(str) as UploadFile\n * );\n *\n * // Use the store\n * const effect = Effect.gen(function* () {\n * const file: UploadFile = { ... };\n * yield* uploadFileStore.set(\"abc123\", file);\n * // Internally stores at key \"uploadista:upload-file:abc123\"\n *\n * const retrieved = yield* uploadFileStore.get(\"abc123\");\n * return retrieved;\n * });\n *\n * // Custom serialization for binary data\n * const binaryStore = new TypedKvStore<Uint8Array>(\n * baseKvStore,\n * \"binary:\",\n * (data) => btoa(String.fromCharCode(...data)), // Base64 encode\n * (str) => Uint8Array.from(atob(str), c => c.charCodeAt(0)) // Base64 decode\n * );\n * ```\n */\nexport class TypedKvStore<TData> implements KvStore<TData> {\n constructor(\n private baseStore: BaseKvStore,\n private keyPrefix: string,\n private serialize: (data: TData) => string,\n private deserialize: (str: string) => TData,\n ) {}\n\n get = (key: string): Effect.Effect<TData, UploadistaError> =>\n this.baseStore.get(this.keyPrefix + key).pipe(\n Effect.flatMap((value) => {\n if (value === null) {\n return Effect.fail(\n UploadistaError.fromCode(\"FILE_NOT_FOUND\", {\n cause: `Key \"${key}\" not found`,\n }),\n );\n }\n try {\n return Effect.succeed(this.deserialize(value));\n } catch (error) {\n return Effect.fail(\n new UploadistaError({\n code: \"VALIDATION_ERROR\",\n status: 400,\n body: `Failed to deserialize value for key \"${key}\"`,\n cause: error,\n }),\n );\n }\n }),\n );\n\n set = (key: string, value: TData): Effect.Effect<void, UploadistaError> => {\n try {\n const serialized = this.serialize(value);\n return this.baseStore.set(this.keyPrefix + key, serialized);\n } catch (error) {\n return Effect.fail(\n new UploadistaError({\n code: \"VALIDATION_ERROR\",\n status: 400,\n body: `Failed to serialize value for key \"${key}\"`,\n cause: error,\n }),\n );\n }\n };\n\n delete = (key: string): Effect.Effect<void, UploadistaError> =>\n this.baseStore.delete(this.keyPrefix + key);\n\n list = (): Effect.Effect<Array<string>, UploadistaError> => {\n if (this.baseStore.list) {\n // Get keys with prefix and strip the prefix for use with get/set/delete\n return this.baseStore\n .list(this.keyPrefix)\n .pipe(\n Effect.map((keys) =>\n keys.map((key) =>\n key.startsWith(this.keyPrefix)\n ? key.slice(this.keyPrefix.length)\n : key,\n ),\n ),\n );\n }\n return Effect.fail(\n new UploadistaError({\n code: \"UNKNOWN_ERROR\",\n status: 501,\n body: \"List operation not supported by this store\",\n }),\n );\n };\n}\n\n/**\n * Default JSON serialization helpers.\n *\n * These functions provide standard JSON serialization for use with TypedKvStore.\n * They work with any JSON-serializable type.\n *\n * @example\n * ```typescript\n * const store = new TypedKvStore<MyType>(\n * baseStore,\n * \"mydata:\",\n * jsonSerializer.serialize,\n * jsonSerializer.deserialize\n * );\n * ```\n */\nexport const jsonSerializer = {\n serialize: <T>(data: T): string => JSON.stringify(data),\n deserialize: <T>(str: string): T => JSON.parse(str),\n};\n\n/**\n * Effect-TS context tag for the base untyped KV store.\n *\n * This is the low-level store that storage adapter implementations provide.\n * Most application code should use typed stores like UploadFileKVStore instead.\n *\n * @example\n * ```typescript\n * // Provide a base store implementation\n * const baseStoreLayer = Layer.succeed(BaseKvStoreService, redisKvStore);\n *\n * // Use in an Effect\n * const effect = Effect.gen(function* () {\n * const baseStore = yield* BaseKvStoreService;\n * yield* baseStore.set(\"raw-key\", \"raw-value\");\n * });\n * ```\n */\nexport class BaseKvStoreService extends Context.Tag(\"BaseKvStore\")<\n BaseKvStoreService,\n BaseKvStore\n>() {}\n\n/**\n * Effect-TS context tag for the UploadFile typed KV store.\n *\n * This provides type-safe storage for UploadFile metadata. It's the primary\n * way to store and retrieve upload metadata in the system.\n *\n * @example\n * ```typescript\n * const uploadEffect = Effect.gen(function* () {\n * const kvStore = yield* UploadFileKVStore;\n *\n * // Store upload metadata\n * const file: UploadFile = {\n * id: \"upload123\",\n * offset: 0,\n * storage: { id: \"s3\", type: \"s3\" }\n * };\n * yield* kvStore.set(\"upload123\", file);\n *\n * // Retrieve with type safety\n * const retrieved = yield* kvStore.get(\"upload123\");\n * return retrieved;\n * });\n * ```\n */\nexport class UploadFileKVStore extends Context.Tag(\"UploadFileKVStore\")<\n UploadFileKVStore,\n KvStore<UploadFile>\n>() {}\n\n/**\n * Effect Layer that creates the UploadFileKVStore from a BaseKvStore.\n *\n * This layer automatically wires up JSON serialization for UploadFile objects\n * with the \"uploadista:upload-file:\" key prefix.\n *\n * @example\n * ```typescript\n * const program = Effect.gen(function* () {\n * const kvStore = yield* UploadFileKVStore;\n * // Use the store...\n * }).pipe(\n * Effect.provide(uploadFileKvStore),\n * Effect.provide(baseStoreLayer)\n * );\n * ```\n */\nexport const uploadFileKvStore = Layer.effect(\n UploadFileKVStore,\n Effect.gen(function* () {\n const baseStore = yield* BaseKvStoreService;\n return new TypedKvStore<UploadFile>(\n baseStore,\n \"uploadista:upload-file:\",\n jsonSerializer.serialize,\n jsonSerializer.deserialize,\n );\n }),\n);\n\n/**\n * Effect-TS context tag for the FlowJob typed KV store.\n *\n * This provides type-safe storage for FlowJob metadata, tracking the\n * execution state of flow processing jobs.\n *\n * @example\n * ```typescript\n * const flowEffect = Effect.gen(function* () {\n * const jobStore = yield* FlowJobKVStore;\n *\n * // Store job state\n * const job: FlowJob = {\n * id: \"job123\",\n * flowId: \"flow_resize\",\n * status: \"running\",\n * tasks: [],\n * createdAt: new Date(),\n * updatedAt: new Date()\n * };\n * yield* jobStore.set(\"job123\", job);\n *\n * // Retrieve and check status\n * const retrieved = yield* jobStore.get(\"job123\");\n * return retrieved.status;\n * });\n * ```\n */\nexport class FlowJobKVStore extends Context.Tag(\"FlowJobKVStore\")<\n FlowJobKVStore,\n KvStore<FlowJob>\n>() {}\n\n/**\n * Effect Layer that creates the FlowJobKVStore from a BaseKvStore.\n *\n * This layer automatically wires up JSON serialization for FlowJob objects\n * with the \"uploadista:flow-job:\" key prefix.\n *\n * @example\n * ```typescript\n * const program = Effect.gen(function* () {\n * const jobStore = yield* FlowJobKVStore;\n * // Use the store...\n * }).pipe(\n * Effect.provide(flowJobKvStore),\n * Effect.provide(baseStoreLayer)\n * );\n * ```\n */\nexport const flowJobKvStore = Layer.effect(\n FlowJobKVStore,\n Effect.gen(function* () {\n const baseStore = yield* BaseKvStoreService;\n return new TypedKvStore<FlowJob>(\n baseStore,\n \"uploadista:flow-job:\",\n jsonSerializer.serialize,\n jsonSerializer.deserialize,\n );\n }),\n);\n\n/**\n * Effect-TS context tag for the Dead Letter Queue typed KV store.\n *\n * This provides type-safe storage for DeadLetterItem objects, tracking\n * failed flow jobs for retry, debugging, and manual intervention.\n *\n * @example\n * ```typescript\n * const dlqEffect = Effect.gen(function* () {\n * const dlqStore = yield* DeadLetterQueueKVStore;\n *\n * // Store a DLQ item\n * const item: DeadLetterItem = {\n * id: \"dlq_123\",\n * jobId: \"job_456\",\n * flowId: \"image-pipeline\",\n * storageId: \"s3\",\n * clientId: \"client_789\",\n * error: { code: \"FLOW_NODE_ERROR\", message: \"Timeout\" },\n * inputs: { input: { uploadId: \"upload_abc\" } },\n * nodeResults: {},\n * retryCount: 0,\n * maxRetries: 3,\n * retryHistory: [],\n * createdAt: new Date(),\n * updatedAt: new Date(),\n * status: \"pending\"\n * };\n * yield* dlqStore.set(\"dlq_123\", item);\n *\n * // Retrieve with type safety\n * const retrieved = yield* dlqStore.get(\"dlq_123\");\n * return retrieved.status;\n * });\n * ```\n */\nexport class DeadLetterQueueKVStore extends Context.Tag(\n \"DeadLetterQueueKVStore\",\n)<DeadLetterQueueKVStore, KvStore<DeadLetterItem>>() {}\n\n/**\n * Effect Layer that creates the DeadLetterQueueKVStore from a BaseKvStore.\n *\n * This layer automatically wires up JSON serialization for DeadLetterItem objects\n * with the \"uploadista:dlq:\" key prefix.\n *\n * @example\n * ```typescript\n * const program = Effect.gen(function* () {\n * const dlqStore = yield* DeadLetterQueueKVStore;\n * // Use the store...\n * }).pipe(\n * Effect.provide(deadLetterQueueKvStore),\n * Effect.provide(baseStoreLayer)\n * );\n * ```\n */\nexport const deadLetterQueueKvStore = Layer.effect(\n DeadLetterQueueKVStore,\n Effect.gen(function* () {\n const baseStore = yield* BaseKvStoreService;\n return new TypedKvStore<DeadLetterItem>(\n baseStore,\n \"uploadista:dlq:\",\n jsonSerializer.serialize,\n jsonSerializer.deserialize,\n );\n }),\n);\n","import { z } from \"zod\";\n\n/**\n * Zod schema for validating UploadFile objects.\n *\n * This schema defines the structure and validation rules for upload file metadata.\n * Use this schema to parse and validate UploadFile data from external sources.\n *\n * @see {@link UploadFile} for the TypeScript type\n */\n/**\n * Zod schema for trace context used in distributed tracing.\n */\nexport const traceContextSchema = z.object({\n traceId: z.string(),\n spanId: z.string(),\n traceFlags: z.number(),\n});\n\n/**\n * JSON value type that allows any JSON-serializable data.\n * Used for metadata values which can be primitives, arrays, or nested objects.\n */\nexport type JsonValue =\n | string\n | number\n | boolean\n | null\n | JsonValue[]\n | { [key: string]: JsonValue };\n\n/**\n * JSON value schema that allows any JSON-serializable data.\n * This is used for metadata values which can be primitives, arrays, or objects.\n */\nconst jsonValueSchema: z.ZodType<JsonValue> = z.lazy(() =>\n z.union([\n z.string(),\n z.number(),\n z.boolean(),\n z.null(),\n z.array(jsonValueSchema),\n z.record(z.string(), jsonValueSchema),\n ]),\n);\n\nexport const uploadFileSchema = z.object({\n id: z.string(),\n size: z.number().optional(),\n offset: z.number(),\n metadata: z.record(z.string(), jsonValueSchema).optional(),\n creationDate: z.string().optional(),\n url: z.string().optional(),\n sizeIsDeferred: z.boolean().optional(),\n checksum: z.string().optional(),\n checksumAlgorithm: z.string().optional(),\n storage: z.object({\n id: z.string(),\n type: z.string(),\n path: z.string().optional(),\n uploadId: z.string().optional(),\n bucket: z.string().optional(),\n parts: z\n .array(\n z.object({\n partNumber: z.number(),\n etag: z.string(),\n size: z.number(),\n }),\n )\n .optional(),\n }),\n flow: z\n .object({\n flowId: z.string(),\n nodeId: z.string(),\n jobId: z.string(),\n })\n .optional(),\n traceContext: traceContextSchema.optional(),\n});\n\n/**\n * Represents an uploaded file with its metadata and storage information.\n *\n * This is the core data structure that tracks file uploads throughout their lifecycle.\n * It contains all metadata needed to resume uploads, track progress, and locate files\n * in storage backends.\n *\n * @property id - Unique identifier for this upload\n * @property offset - Current byte offset (how many bytes have been uploaded)\n * @property storage - Storage backend information\n * @property storage.id - Storage backend identifier (e.g., \"s3-production\")\n * @property storage.type - Storage backend type (e.g., \"s3\", \"azure\", \"gcs\")\n * @property storage.path - Optional path prefix within the storage backend\n * @property storage.uploadId - Optional backend-specific upload ID (e.g., S3 multipart upload ID)\n * @property storage.bucket - Optional bucket or container name\n * @property storage.parts - Optional array of uploaded parts (used by data stores that need to track parts locally, like R2)\n * @property flow - Optional flow processing information (when file is part of a flow)\n * @property flow.flowId - ID of the flow processing this file\n * @property flow.nodeId - ID of the flow node that created this file\n * @property flow.jobId - ID of the flow job execution\n * @property size - Total file size in bytes (undefined if deferred)\n * @property metadata - Custom key-value metadata attached to the file\n * @property creationDate - ISO 8601 timestamp when upload was created\n * @property url - Optional public URL to access the file\n * @property sizeIsDeferred - True if file size is not known at upload start\n * @property checksum - Optional file checksum/hash value\n * @property checksumAlgorithm - Algorithm used for checksum (e.g., \"md5\", \"sha256\")\n *\n * @example\n * ```typescript\n * // Create an UploadFile for a new upload\n * const uploadFile: UploadFile = {\n * id: \"upload_abc123\",\n * offset: 0,\n * size: 1024000,\n * storage: {\n * id: \"s3-production\",\n * type: \"s3\",\n * bucket: \"my-uploads\",\n * path: \"files/\"\n * },\n * metadata: {\n * fileName: \"image.jpg\",\n * contentType: \"image/jpeg\",\n * userId: \"user_123\"\n * },\n * creationDate: new Date().toISOString(),\n * checksum: \"5d41402abc4b2a76b9719d911017c592\",\n * checksumAlgorithm: \"md5\"\n * };\n *\n * // UploadFile with flow processing\n * const flowFile: UploadFile = {\n * id: \"upload_xyz789\",\n * offset: 0,\n * size: 2048000,\n * storage: {\n * id: \"s3-temp\",\n * type: \"s3\",\n * bucket: \"temp-processing\"\n * },\n * flow: {\n * flowId: \"flow_resize_optimize\",\n * nodeId: \"input_1\",\n * jobId: \"job_456\"\n * }\n * };\n *\n * // Resume an interrupted upload\n * const resumingFile: UploadFile = {\n * id: \"upload_resume\",\n * offset: 524288, // Already uploaded 512KB\n * size: 1024000,\n * storage: {\n * id: \"s3-production\",\n * type: \"s3\",\n * uploadId: \"multipart_xyz\" // S3 multipart upload ID\n * }\n * };\n * ```\n */\n/**\n * Trace context for distributed tracing.\n * Allows upload operations to be linked under a single trace.\n */\nexport type UploadFileTraceContext = {\n /** 128-bit trace identifier (32 hex characters) */\n traceId: string;\n /** 64-bit span identifier (16 hex characters) */\n spanId: string;\n /** Trace flags (1 = sampled) */\n traceFlags: number;\n};\n\nexport type UploadFile = {\n id: string;\n offset: number;\n storage: {\n id: string;\n type: string;\n path?: string | undefined;\n uploadId?: string | undefined;\n bucket?: string | undefined;\n parts?:\n | Array<{\n partNumber: number;\n etag: string;\n size: number;\n }>\n | undefined;\n };\n flow?: {\n flowId: string;\n nodeId: string;\n jobId: string;\n };\n size?: number | undefined;\n metadata?: Record<string, JsonValue> | undefined;\n creationDate?: string | undefined;\n url?: string | undefined;\n sizeIsDeferred?: boolean | undefined;\n checksum?: string | undefined;\n checksumAlgorithm?: string | undefined;\n /**\n * OpenTelemetry trace context for distributed tracing.\n * When set, subsequent upload operations (chunks, validation) will be\n * linked as children of this trace context.\n */\n traceContext?: UploadFileTraceContext | undefined;\n};\n","import { Context, Effect, Layer, type Stream } from \"effect\";\nimport { UploadistaError } from \"../errors/uploadista-error\";\nimport type { UploadFileKVStore } from \"./kv-store\";\nimport type { UploadFile } from \"./upload-file\";\n\n/**\n * Options for writing data to a DataStore.\n *\n * @property file_id - Unique identifier for the file being written\n * @property stream - Stream of byte chunks to write to storage\n * @property offset - Byte offset where writing should begin (for resumable uploads)\n */\nexport type DataStoreWriteOptions = {\n file_id: string;\n stream: Stream.Stream<Uint8Array, UploadistaError>;\n offset: number;\n};\n\n/**\n * Upload strategy type indicating how chunks are uploaded.\n *\n * - `single`: Upload file in a single request (traditional upload)\n * - `parallel`: Upload file chunks in parallel (for large files)\n */\nexport type UploadStrategy = \"single\" | \"parallel\";\n\n/**\n * Configuration options for streaming file reads.\n *\n * Used to control streaming behavior in transform nodes and data stores.\n *\n * @property fileSizeThreshold - Files below this size use buffered mode (default: 1MB)\n * @property chunkSize - Chunk size for streaming reads in bytes (default: 64KB)\n *\n * @example\n * ```typescript\n * const config: StreamingConfig = {\n * fileSizeThreshold: 1_048_576, // 1MB - use buffered for smaller files\n * chunkSize: 65_536, // 64KB chunks\n * };\n * ```\n */\nexport type StreamingConfig = {\n /** Files below this size use buffered mode (default: 1MB = 1_048_576 bytes) */\n fileSizeThreshold?: number;\n /** Chunk size for streaming reads in bytes (default: 64KB = 65_536 bytes) */\n chunkSize?: number;\n};\n\n/**\n * Default streaming configuration values.\n */\nexport const DEFAULT_STREAMING_CONFIG: Required<StreamingConfig> = {\n fileSizeThreshold: 1_048_576, // 1MB\n chunkSize: 65_536, // 64KB\n};\n\n/**\n * Default multipart part size for S3/R2 streaming writes.\n * S3 requires minimum 5MB parts (except for the last part).\n */\nexport const DEFAULT_MULTIPART_PART_SIZE = 5 * 1024 * 1024; // 5MB\n\n/**\n * Options for streaming write operations.\n *\n * Used when writing file content from a stream with unknown final size.\n * The store will finalize the upload when the stream completes.\n *\n * @property stream - Effect Stream of byte chunks to write\n * @property contentType - Optional MIME type for the file\n * @property metadata - Optional metadata to store with the file\n * @property sizeHint - Optional estimated size for optimization (e.g., multipart part sizing)\n *\n * @example\n * ```typescript\n * const options: StreamWriteOptions = {\n * stream: transformedStream,\n * contentType: \"image/webp\",\n * metadata: { originalName: \"photo.jpg\" },\n * sizeHint: 5_000_000, // ~5MB expected\n * };\n * ```\n */\nexport type StreamWriteOptions = {\n stream: Stream.Stream<Uint8Array, UploadistaError>;\n contentType?: string;\n metadata?: Record<string, string>;\n /** Optional size hint for optimization (not required) */\n sizeHint?: number;\n};\n\n/**\n * Result of a streaming write operation.\n *\n * Contains the final size after the stream completes, along with\n * storage location information.\n *\n * @property id - Unique identifier of the written file\n * @property size - Final size in bytes after stream completed\n * @property path - Storage path or key where file was written\n * @property bucket - Optional bucket/container name (for cloud storage)\n *\n * @example\n * ```typescript\n * const result = yield* dataStore.writeStream(fileId, options);\n * console.log(`Wrote ${result.size} bytes to ${result.path}`);\n * ```\n */\nexport type StreamWriteResult = {\n id: string;\n size: number;\n path: string;\n bucket?: string;\n /** Public URL for accessing the uploaded file (if available) */\n url?: string;\n};\n\n/**\n * Capabilities and constraints of a DataStore implementation.\n *\n * This type describes what features a storage backend supports and what\n * limitations it has. Use this to determine the optimal upload strategy\n * and validate client requests.\n *\n * @property supportsParallelUploads - Can upload chunks in parallel (e.g., S3 multipart)\n * @property supportsConcatenation - Can concatenate multiple uploads into one file\n * @property supportsDeferredLength - Can start upload without knowing final size\n * @property supportsResumableUploads - Can resume interrupted uploads from last offset\n * @property supportsTransactionalUploads - Guarantees atomic upload success/failure\n * @property supportsStreamingRead - Can read file content as a stream instead of buffering\n * @property maxConcurrentUploads - Maximum parallel upload parts (if parallel supported)\n * @property minChunkSize - Minimum size in bytes for each chunk (except last)\n * @property maxChunkSize - Maximum size in bytes for each chunk\n * @property maxParts - Maximum number of parts in a multipart upload\n * @property optimalChunkSize - Recommended chunk size for best performance\n * @property requiresOrderedChunks - Must receive chunks in sequential order\n * @property requiresMimeTypeValidation - Validates file MIME type matches declaration\n * @property maxValidationSize - Maximum file size for MIME type validation\n *\n * @example\n * ```typescript\n * const capabilities = dataStore.getCapabilities();\n *\n * if (capabilities.supportsParallelUploads && fileSize > 10_000_000) {\n * // Use parallel upload for large files\n * const chunkSize = capabilities.optimalChunkSize || 5_242_880; // 5MB default\n * uploadInParallel(file, chunkSize);\n * } else {\n * // Use single upload\n * uploadAsSingleChunk(file);\n * }\n *\n * // Check for streaming support\n * if (capabilities.supportsStreamingRead) {\n * // Use streaming for memory-efficient processing\n * const stream = yield* dataStore.readStream(fileId);\n * }\n * ```\n */\nexport type DataStoreCapabilities = {\n supportsParallelUploads: boolean;\n supportsConcatenation: boolean;\n supportsDeferredLength: boolean;\n supportsResumableUploads: boolean;\n supportsTransactionalUploads: boolean;\n /** Whether the store supports streaming reads via readStream() */\n supportsStreamingRead?: boolean;\n /** Whether the store supports streaming writes via writeStream() with unknown final size */\n supportsStreamingWrite?: boolean;\n maxConcurrentUploads?: number;\n minChunkSize?: number;\n maxChunkSize?: number;\n maxParts?: number;\n optimalChunkSize?: number;\n requiresOrderedChunks: boolean;\n requiresMimeTypeValidation?: boolean;\n maxValidationSize?: number;\n};\n\n/**\n * Core interface for all storage backend implementations.\n *\n * DataStore abstracts file storage operations across different backends\n * (S3, Azure Blob, GCS, local filesystem, etc.). All storage adapters\n * must implement this interface.\n *\n * @template TData - The data type stored (typically UploadFile)\n *\n * @property bucket - Optional storage bucket or container name\n * @property path - Optional base path prefix for all stored files\n * @property create - Creates a new file record in storage\n * @property remove - Deletes a file from storage\n * @property read - Reads complete file contents as bytes\n * @property write - Writes data stream to storage at specified offset\n * @property deleteExpired - Optional cleanup of expired files\n * @property getCapabilities - Returns storage backend capabilities\n * @property validateUploadStrategy - Validates if strategy is supported\n *\n * @example\n * ```typescript\n * // Implement a custom DataStore\n * const myDataStore: DataStore<UploadFile> = {\n * bucket: \"my-uploads\",\n * path: \"files/\",\n *\n * create: (file) => Effect.gen(function* () {\n * // Store file metadata\n * yield* saveMetadata(file);\n * return file;\n * }),\n *\n * write: ({ file_id, stream, offset }, { onProgress }) => Effect.gen(function* () {\n * // Write chunks to storage\n * let bytesWritten = offset;\n * yield* Stream.runForEach(stream, (chunk) => Effect.sync(() => {\n * writeChunk(file_id, chunk, bytesWritten);\n * bytesWritten += chunk.byteLength;\n * onProgress?.(chunk.byteLength);\n * }));\n * return bytesWritten;\n * }),\n *\n * read: (file_id) => Effect.gen(function* () {\n * // Read complete file\n * const data = yield* readFromStorage(file_id);\n * return data;\n * }),\n *\n * remove: (file_id) => Effect.gen(function* () {\n * yield* deleteFromStorage(file_id);\n * }),\n *\n * getCapabilities: () => ({\n * supportsParallelUploads: true,\n * supportsConcatenation: false,\n * supportsDeferredLength: true,\n * supportsResumableUploads: true,\n * supportsTransactionalUploads: false,\n * maxConcurrentUploads: 10,\n * optimalChunkSize: 5_242_880, // 5MB\n * requiresOrderedChunks: false,\n * }),\n *\n * validateUploadStrategy: (strategy) =>\n * Effect.succeed(strategy === \"parallel\" || strategy === \"single\"),\n * };\n * ```\n */\nexport type DataStore<TData = unknown> = {\n readonly bucket?: string;\n readonly path?: string;\n readonly create: (file: TData) => Effect.Effect<TData, UploadistaError>;\n readonly remove: (file_id: string) => Effect.Effect<void, UploadistaError>;\n /**\n * Reads the complete file contents as bytes (buffered mode).\n * For large files, consider using readStream() if available.\n */\n readonly read: (\n file_id: string,\n ) => Effect.Effect<Uint8Array, UploadistaError>;\n /**\n * Reads file content as a stream of chunks for memory-efficient processing.\n * Optional - check getCapabilities().supportsStreamingRead before using.\n *\n * @param file_id - The unique identifier of the file to read\n * @param config - Optional streaming configuration (chunk size)\n * @returns An Effect that resolves to a Stream of byte chunks\n *\n * @example\n * ```typescript\n * const capabilities = dataStore.getCapabilities();\n * if (capabilities.supportsStreamingRead && dataStore.readStream) {\n * const stream = yield* dataStore.readStream(fileId, { chunkSize: 65536 });\n * // Process stream chunk by chunk\n * }\n * ```\n */\n readonly readStream?: (\n file_id: string,\n config?: StreamingConfig,\n ) => Effect.Effect<\n Stream.Stream<Uint8Array, UploadistaError>,\n UploadistaError\n >;\n readonly write: (\n options: DataStoreWriteOptions,\n dependencies: {\n onProgress?: (chunkSize: number) => void;\n },\n ) => Effect.Effect<number, UploadistaError>;\n /**\n * Writes file content from a stream with unknown final size.\n * Optional - check getCapabilities().supportsStreamingWrite before using.\n *\n * This method is optimized for end-to-end streaming where the output\n * size isn't known until the stream completes. It uses store-specific\n * mechanisms like multipart uploads (S3/R2), resumable uploads (GCS),\n * or block staging (Azure) to efficiently handle streaming data.\n *\n * @param fileId - Unique identifier for the file being written\n * @param options - Stream and optional metadata\n * @returns StreamWriteResult containing final size after completion\n *\n * @example\n * ```typescript\n * const capabilities = dataStore.getCapabilities();\n * if (capabilities.supportsStreamingWrite && dataStore.writeStream) {\n * const result = yield* dataStore.writeStream(fileId, {\n * stream: transformedStream,\n * contentType: \"image/webp\",\n * });\n * console.log(`Wrote ${result.size} bytes`);\n * }\n * ```\n */\n readonly writeStream?: (\n fileId: string,\n options: StreamWriteOptions,\n ) => Effect.Effect<StreamWriteResult, UploadistaError>;\n readonly deleteExpired?: () => Effect.Effect<number, UploadistaError>;\n readonly getCapabilities: () => DataStoreCapabilities;\n readonly validateUploadStrategy: (\n strategy: UploadStrategy,\n ) => Effect.Effect<boolean, never>;\n};\n\n/**\n * Effect-TS context tag for UploadFile DataStore.\n *\n * Use this tag to access the primary DataStore in an Effect context.\n * This is the standard storage backend for uploaded files.\n *\n * @example\n * ```typescript\n * const uploadEffect = Effect.gen(function* () {\n * const dataStore = yield* UploadFileDataStore;\n * const file = yield* dataStore.create(uploadFile);\n * return file;\n * });\n * ```\n */\nexport class UploadFileDataStore extends Context.Tag(\"UploadFileDataStore\")<\n UploadFileDataStore,\n DataStore<UploadFile>\n>() {}\n\n/**\n * Effect-TS context tag for buffered/temporary DataStore.\n *\n * This is an optional storage backend used for temporary or intermediate files\n * during flow processing. Not all implementations provide a buffered store.\n *\n * @example\n * ```typescript\n * const processEffect = Effect.gen(function* () {\n * const bufferedStore = yield* BufferedUploadFileDataStore;\n * // Store intermediate processing results\n * const tempFile = yield* bufferedStore.create(intermediateFile);\n * return tempFile;\n * });\n * ```\n */\nexport class BufferedUploadFileDataStore extends Context.Tag(\n \"BufferedUploadFileDataStore\",\n)<BufferedUploadFileDataStore, DataStore<UploadFile>>() {}\n\n/**\n * Service interface for managing multiple DataStore instances.\n *\n * This allows routing files to different storage backends based on\n * storageId (e.g., different S3 buckets, Azure containers, or storage tiers).\n *\n * @property getDataStore - Retrieves the appropriate DataStore for a given storage ID\n * @property bufferedDataStore - Optional temporary storage for intermediate files\n */\nexport type UploadFileDataStoresShape = {\n getDataStore: (\n storageId: string,\n clientId: string | null,\n ) => Effect.Effect<DataStore<UploadFile>, UploadistaError>;\n bufferedDataStore: Effect.Effect<\n DataStore<UploadFile> | undefined,\n UploadistaError\n >;\n};\n\n/**\n * Effect-TS context tag for the DataStore routing service.\n *\n * Provides access to multiple DataStore instances with routing logic.\n *\n * @example\n * ```typescript\n * const uploadEffect = Effect.gen(function* () {\n * const dataStores = yield* UploadFileDataStores;\n * // Route to specific storage based on storageId\n * const dataStore = yield* dataStores.getDataStore(\"s3-production\", clientId);\n * const file = yield* dataStore.create(uploadFile);\n * return file;\n * });\n * ```\n */\nexport class UploadFileDataStores extends Context.Tag(\"UploadFileDataStores\")<\n UploadFileDataStores,\n UploadFileDataStoresShape\n>() {}\n\n/**\n * Simplified DataStore configuration for easy setup.\n *\n * This type allows flexible configuration:\n * - Single DataStore instance\n * - Multiple named stores with routing\n * - Effect that resolves to a DataStore\n * - Pre-built Effect Layer\n *\n * @example\n * ```typescript\n * // Single store\n * const config: DataStoreConfig = s3DataStore;\n *\n * // Multiple stores with routing\n * const config: DataStoreConfig = {\n * stores: {\n * \"s3-prod\": s3ProdStore,\n * \"s3-dev\": s3DevStore,\n * \"local\": localFileStore,\n * },\n * default: \"s3-prod\"\n * };\n *\n * // Effect that creates a store\n * const config: DataStoreConfig = Effect.gen(function* () {\n * const kvStore = yield* UploadFileKVStore;\n * return s3Store(kvStore);\n * });\n *\n * // Pre-built Layer\n * const config: DataStoreConfig = Layer.succeed(UploadFileDataStores, {...});\n * ```\n */\nexport type DataStoreConfig =\n | DataStore<UploadFile>\n | Effect.Effect<DataStore<UploadFile>, never, UploadFileKVStore>\n | {\n stores: Record<\n string,\n | DataStore<UploadFile>\n | Effect.Effect<DataStore<UploadFile>, never, UploadFileKVStore>\n >;\n default?: string;\n }\n | Layer.Layer<UploadFileDataStores, never, UploadFileKVStore>;\n\n/**\n * Type guard to check if a value is a DataStore instance.\n *\n * @param config - The value to check\n * @returns True if the value is a DataStore\n *\n * @example\n * ```typescript\n * if (isDataStore(config)) {\n * const capabilities = config.getCapabilities();\n * }\n * ```\n */\nexport const isDataStore = (\n config: DataStoreConfig,\n): config is DataStore<UploadFile> => {\n return \"create\" in config && \"write\" in config;\n};\n\n/**\n * Creates an Effect Layer from simplified DataStoreConfig.\n *\n * This function converts any DataStoreConfig format into a proper Effect Layer\n * that can be provided to the UploadFileDataStores context tag.\n *\n * It handles:\n * - Single DataStore: Wraps in a Layer that always returns that store\n * - Multiple stores: Creates routing logic with optional default\n * - Effect<DataStore>: Executes the Effect and wraps the result\n * - Layer: Returns as-is\n *\n * @param config - The DataStore configuration\n * @returns A Layer that provides UploadFileDataStores service\n *\n * @example\n * ```typescript\n * // Create from single store\n * const layer = await createDataStoreLayer(s3DataStore);\n *\n * // Create from multiple stores\n * const layer = await createDataStoreLayer({\n * stores: {\n * \"production\": s3Store,\n * \"development\": localStore,\n * },\n * default: \"development\"\n * });\n *\n * // Use the layer\n * const program = Effect.gen(function* () {\n * const stores = yield* UploadFileDataStores;\n * const store = yield* stores.getDataStore(\"production\", null);\n * return store;\n * }).pipe(Effect.provide(layer));\n * ```\n */\nexport const createDataStoreLayer = async (\n config: DataStoreConfig,\n): Promise<Layer.Layer<UploadFileDataStores, never, UploadFileKVStore>> => {\n // Already a Layer, return as-is\n if (Layer.isLayer(config)) {\n return config as Layer.Layer<\n UploadFileDataStores,\n never,\n UploadFileKVStore\n >;\n }\n\n // Check if it's an Effect\n if (Effect.isEffect(config)) {\n return Layer.effect(\n UploadFileDataStores,\n Effect.gen(function* () {\n const dataStore = config as Effect.Effect<\n DataStore<UploadFile>,\n never,\n UploadFileKVStore\n >;\n const resolvedStore = yield* dataStore;\n return {\n getDataStore: (_storageId: string) => Effect.succeed(resolvedStore),\n bufferedDataStore: Effect.succeed(undefined),\n };\n }),\n );\n }\n\n // Single store (most common case)\n if (isDataStore(config)) {\n const store = config as DataStore<UploadFile>;\n return Layer.succeed(UploadFileDataStores, {\n getDataStore: (_storageId: string) => Effect.succeed(store),\n bufferedDataStore: Effect.succeed(undefined),\n });\n }\n\n // Multiple stores with routing\n const multiConfig = config as {\n stores: Record<\n string,\n DataStore<UploadFile> | Effect.Effect<DataStore<UploadFile>>\n >;\n default?: string;\n };\n\n const defaultKey = multiConfig.default || Object.keys(multiConfig.stores)[0];\n\n // Resolve any Effects in the stores\n const resolvedStores: Record<string, DataStore<UploadFile>> = {};\n for (const [key, storeOrEffect] of Object.entries(multiConfig.stores)) {\n if (\"pipe\" in storeOrEffect && !(\"create\" in storeOrEffect)) {\n resolvedStores[key] = await Effect.runPromise(\n storeOrEffect as Effect.Effect<DataStore<UploadFile>>,\n );\n } else {\n resolvedStores[key] = storeOrEffect as DataStore<UploadFile>;\n }\n }\n\n return Layer.succeed(UploadFileDataStores, {\n getDataStore: (storageId: string) => {\n const store =\n resolvedStores[storageId] ||\n (defaultKey ? resolvedStores[defaultKey] : undefined);\n if (store) {\n return Effect.succeed(store);\n }\n return Effect.fail(UploadistaError.fromCode(\"FILE_NOT_FOUND\"));\n },\n bufferedDataStore: Effect.succeed(undefined),\n });\n};\n","import { Context, type Effect } from \"effect\";\nimport type { UploadistaError } from \"../errors\";\n\n/**\n * Event broadcaster interface for pub/sub messaging across distributed instances.\n * Used by WebSocketManager to broadcast upload events to all connected instances.\n */\nexport interface EventBroadcaster {\n /**\n * Publish a message to a channel\n */\n readonly publish: (\n channel: string,\n message: string,\n ) => Effect.Effect<void, UploadistaError>;\n\n /**\n * Subscribe to messages on a channel\n */\n readonly subscribe: (\n channel: string,\n handler: (message: string) => void,\n ) => Effect.Effect<void, UploadistaError>;\n\n /**\n * Unsubscribe from a channel (optional - not all implementations may support)\n */\n readonly unsubscribe?: (\n channel: string,\n ) => Effect.Effect<void, UploadistaError>;\n}\n\n/**\n * Context tag for EventBroadcaster service\n */\nexport class EventBroadcasterService extends Context.Tag(\"EventBroadcaster\")<\n EventBroadcasterService,\n EventBroadcaster\n>() {}\n","import { Context, Effect, Layer } from \"effect\";\nimport type { UploadistaError } from \"../errors\";\nimport type { FlowEvent } from \"../flow/event\";\nimport type { UploadEvent } from \"./upload-event\";\nimport type { WebSocketConnection } from \"./websocket\";\n\n/**\n * Base event emitter interface for raw string message broadcasting.\n *\n * This is the low-level interface that event broadcasting implementations\n * (WebSocket, Server-Sent Events, etc.) implement. It emits raw string messages\n * without type safety or serialization.\n *\n * @property subscribe - Registers a WebSocket connection to receive events for a key\n * @property unsubscribe - Removes subscription for a key\n * @property emit - Broadcasts a string message to all subscribers of a key\n *\n * @example\n * ```typescript\n * // Implement BaseEventEmitter with WebSocket broadcast\n * const websocketEmitter: BaseEventEmitter = {\n * subscribe: (key, connection) => Effect.sync(() => {\n * connections.set(key, [...(connections.get(key) || []), connection]);\n * }),\n *\n * unsubscribe: (key) => Effect.sync(() => {\n * connections.delete(key);\n * }),\n *\n * emit: (key, event) => Effect.sync(() => {\n * const subs = connections.get(key) || [];\n * subs.forEach(conn => conn.send(event));\n * })\n * };\n * ```\n */\nexport interface BaseEventEmitter {\n readonly subscribe: (\n key: string,\n connection: WebSocketConnection,\n ) => Effect.Effect<void, UploadistaError>;\n readonly unsubscribe: (key: string) => Effect.Effect<void, UploadistaError>;\n readonly emit: (\n key: string,\n event: string,\n ) => Effect.Effect<void, UploadistaError>;\n}\n\n/**\n * Type-safe event emitter interface with automatic serialization.\n *\n * This wraps a BaseEventEmitter and handles event serialization to JSON messages,\n * providing type safety for events and ensuring consistent message format.\n *\n * @template TEvent - The type of events emitted by this emitter\n *\n * @property subscribe - Registers a WebSocket connection to receive typed events\n * @property unsubscribe - Removes subscription\n * @property emit - Serializes and broadcasts a typed event\n *\n * @example\n * ```typescript\n * // Use a typed event emitter\n * const uploadEmitter: EventEmitter<UploadEvent> = new TypedEventEmitter(\n * baseEmitter,\n * (event) => JSON.stringify({ type: 'upload', payload: event })\n * );\n *\n * // Emit type-safe events\n * const program = Effect.gen(function* () {\n * const event: UploadEvent = {\n * uploadId: \"upload123\",\n * type: \"progress\",\n * offset: 1024,\n * size: 2048\n * };\n *\n * // Automatic serialization\n * yield* uploadEmitter.emit(\"upload123\", event);\n * });\n * ```\n */\nexport type EventEmitter<TEvent> = {\n readonly subscribe: (\n key: string,\n connection: WebSocketConnection,\n ) => Effect.Effect<void, UploadistaError>;\n readonly unsubscribe: (key: string) => Effect.Effect<void, UploadistaError>;\n readonly emit: (\n key: string,\n event: TEvent,\n ) => Effect.Effect<void, UploadistaError>;\n};\n\n/**\n * Typed wrapper class that adds event serialization to a BaseEventEmitter.\n *\n * This class implements the EventEmitter interface by wrapping a BaseEventEmitter\n * and handling serialization for a specific event type. It converts typed events\n * to JSON message strings before broadcasting.\n *\n * @template TEvent - The type of events to emit\n *\n * @example\n * ```typescript\n * // Create a typed emitter for UploadEvent\n * const uploadEmitter = new TypedEventEmitter<UploadEvent>(\n * baseEmitter,\n * (event) => JSON.stringify({\n * type: \"upload_event\",\n * payload: event,\n * timestamp: new Date().toISOString()\n * })\n * );\n *\n * // Use the emitter\n * const effect = Effect.gen(function* () {\n * // Subscribe a WebSocket connection\n * yield* uploadEmitter.subscribe(\"upload123\", websocket);\n *\n * // Emit an event (automatically serialized)\n * yield* uploadEmitter.emit(\"upload123\", {\n * uploadId: \"upload123\",\n * type: \"completed\",\n * offset: 2048,\n * size: 2048\n * });\n *\n * // Unsubscribe when done\n * yield* uploadEmitter.unsubscribe(\"upload123\");\n * });\n *\n * // Custom message format\n * const customEmitter = new TypedEventEmitter<MyEvent>(\n * baseEmitter,\n * (event) => `EVENT:${event.type}:${JSON.stringify(event.data)}`\n * );\n * ```\n */\nexport class TypedEventEmitter<TEvent> implements EventEmitter<TEvent> {\n constructor(\n private baseEmitter: BaseEventEmitter,\n private eventToMessage: (event: TEvent) => string,\n ) {}\n\n subscribe = (\n key: string,\n connection: WebSocketConnection,\n ): Effect.Effect<void, UploadistaError> =>\n this.baseEmitter.subscribe(key, connection);\n\n unsubscribe = (key: string): Effect.Effect<void, UploadistaError> =>\n this.baseEmitter.unsubscribe(key);\n\n emit = (key: string, event: TEvent): Effect.Effect<void, UploadistaError> => {\n const message = this.eventToMessage(event);\n return this.baseEmitter.emit(key, message);\n };\n}\n\n/**\n * Default event-to-message serialization helper.\n *\n * Creates a standardized JSON message format with type, payload, and timestamp.\n * This is the recommended way to serialize events for WebSocket transmission.\n *\n * @param messageType - The message type identifier (\"upload_event\" or \"flow_event\")\n * @returns An object with an eventToMessage function\n *\n * @example\n * ```typescript\n * // Create emitter with standard serialization\n * const emitter = new TypedEventEmitter<UploadEvent>(\n * baseEmitter,\n * eventToMessageSerializer(\"upload_event\").eventToMessage\n * );\n *\n * // Messages will be formatted as:\n * // {\n * // \"type\": \"upload_event\",\n * // \"payload\": { ...event data... },\n * // \"timestamp\": \"2024-01-15T10:30:00.000Z\"\n * // }\n * ```\n */\nexport const eventToMessageSerializer = (\n messageType: \"upload_event\" | \"flow_event\",\n) => ({\n eventToMessage: <T>(event: T): string =>\n JSON.stringify({\n type: messageType,\n payload: event,\n timestamp: new Date().toISOString(),\n }),\n});\n\n/**\n * Effect-TS context tag for the base untyped event emitter.\n *\n * This is the low-level emitter that broadcasting implementations provide.\n * Most application code should use typed emitters like UploadEventEmitter instead.\n *\n * @example\n * ```typescript\n * // Provide a base emitter implementation\n * const baseEmitterLayer = Layer.succeed(BaseEventEmitterService, websocketEmitter);\n *\n * // Use in an Effect\n * const effect = Effect.gen(function* () {\n * const baseEmitter = yield* BaseEventEmitterService;\n * yield* baseEmitter.emit(\"channel1\", \"raw message\");\n * });\n * ```\n */\nexport class BaseEventEmitterService extends Context.Tag(\"BaseEventEmitter\")<\n BaseEventEmitterService,\n BaseEventEmitter\n>() {}\n\n/**\n * Effect-TS context tag for the UploadEvent typed emitter.\n *\n * This provides type-safe event emission for upload progress and lifecycle events.\n * It's the primary way to broadcast upload events to connected clients.\n *\n * @example\n * ```typescript\n * const uploadEffect = Effect.gen(function* () {\n * const emitter = yield* UploadEventEmitter;\n *\n * // Subscribe a client to upload events\n * yield* emitter.subscribe(\"upload123\", websocketConnection);\n *\n * // Emit progress event\n * yield* emitter.emit(\"upload123\", {\n * uploadId: \"upload123\",\n * type: \"progress\",\n * offset: 512000,\n * size: 1024000\n * });\n *\n * // Emit completion event\n * yield* emitter.emit(\"upload123\", {\n * uploadId: \"upload123\",\n * type: \"completed\",\n * offset: 1024000,\n * size: 1024000\n * });\n * });\n * ```\n */\nexport class UploadEventEmitter extends Context.Tag(\"UploadEventEmitter\")<\n UploadEventEmitter,\n EventEmitter<UploadEvent>\n>() {}\n\n/**\n * Effect Layer that creates the UploadEventEmitter from a BaseEventEmitter.\n *\n * This layer automatically wires up JSON serialization for UploadEvent objects\n * with the standard \"upload_event\" message format.\n *\n * @example\n * ```typescript\n * const program = Effect.gen(function* () {\n * const emitter = yield* UploadEventEmitter;\n * // Use the emitter...\n * }).pipe(\n * Effect.provide(uploadEventEmitter),\n * Effect.provide(baseEmitterLayer)\n * );\n * ```\n */\nexport const uploadEventEmitter = Layer.effect(\n UploadEventEmitter,\n Effect.gen(function* () {\n const baseEmitter = yield* BaseEventEmitterService;\n return new TypedEventEmitter<UploadEvent>(\n baseEmitter,\n eventToMessageSerializer(\"upload_event\").eventToMessage,\n );\n }),\n);\n\n/**\n * Effect-TS context tag for the FlowEvent typed emitter.\n *\n * This provides type-safe event emission for flow processing lifecycle events.\n * It's used to broadcast flow execution progress, node completion, and errors.\n *\n * @example\n * ```typescript\n * const flowEffect = Effect.gen(function* () {\n * const emitter = yield* FlowEventEmitter;\n *\n * // Subscribe a client to flow job events\n * yield* emitter.subscribe(\"job123\", websocketConnection);\n *\n * // Emit node start event\n * yield* emitter.emit(\"job123\", {\n * jobId: \"job123\",\n * eventType: \"NodeStart\",\n * flowId: \"flow_resize\",\n * nodeId: \"resize_1\"\n * });\n *\n * // Emit node completion event\n * yield* emitter.emit(\"job123\", {\n * jobId: \"job123\",\n * eventType: \"NodeEnd\",\n * flowId: \"flow_resize\",\n * nodeId: \"resize_1\",\n * result: { width: 800, height: 600 }\n * });\n * });\n * ```\n */\nexport class FlowEventEmitter extends Context.Tag(\"FlowEventEmitter\")<\n FlowEventEmitter,\n EventEmitter<FlowEvent>\n>() {}\n\n/**\n * Effect Layer that creates the FlowEventEmitter from a BaseEventEmitter.\n *\n * This layer automatically wires up JSON serialization for FlowEvent objects\n * with the standard \"flow_event\" message format.\n *\n * @example\n * ```typescript\n * const program = Effect.gen(function* () {\n * const emitter = yield* FlowEventEmitter;\n * // Use the emitter...\n * }).pipe(\n * Effect.provide(flowEventEmitter),\n * Effect.provide(baseEmitterLayer)\n * );\n * ```\n */\nexport const flowEventEmitter = Layer.effect(\n FlowEventEmitter,\n Effect.gen(function* () {\n const baseEmitter = yield* BaseEventEmitterService;\n return new TypedEventEmitter<FlowEvent>(\n baseEmitter,\n eventToMessageSerializer(\"flow_event\").eventToMessage,\n );\n }),\n);\n","/**\n * Health Check Types for Uploadista SDK.\n *\n * This module provides types for the health monitoring system including:\n * - Liveness probes (`/health`)\n * - Readiness probes (`/ready`)\n * - Component health details (`/health/components`)\n *\n * @module types/health-check\n */\n\n// ============================================================================\n// Health Status Types\n// ============================================================================\n\n/**\n * Health status values for components and overall system health.\n *\n * - `healthy`: All checks passed, system is fully operational\n * - `degraded`: Some non-critical issues detected, but system is functional\n * - `unhealthy`: Critical components unavailable, system cannot serve requests\n */\nexport type HealthStatus = \"healthy\" | \"degraded\" | \"unhealthy\";\n\n// ============================================================================\n// Component Health Types\n// ============================================================================\n\n/**\n * Health status for an individual component (storage, KV store, etc.).\n */\nexport interface ComponentHealth {\n /** Current health status of the component */\n status: HealthStatus;\n /** Latency of the last health check in milliseconds */\n latency?: number;\n /** Human-readable status message */\n message?: string;\n /** ISO 8601 timestamp of the last health check */\n lastCheck?: string;\n}\n\n/**\n * Circuit breaker health summary aggregating all circuit states.\n */\nexport interface CircuitBreakerHealthSummary {\n /** Overall circuit breaker system status */\n status: HealthStatus;\n /** Number of circuits currently in open state */\n openCircuits: number;\n /** Total number of tracked circuits */\n totalCircuits: number;\n /** Detailed stats for each circuit (optional, for debugging) */\n circuits?: Array<{\n nodeType: string;\n state: \"closed\" | \"open\" | \"half-open\";\n failureCount: number;\n timeSinceLastStateChange: number;\n }>;\n}\n\n/**\n * Dead Letter Queue health summary.\n */\nexport interface DlqHealthSummary {\n /** Overall DLQ status */\n status: HealthStatus;\n /** Number of items pending retry */\n pendingItems: number;\n /** Number of items that have exhausted all retries */\n exhaustedItems: number;\n /** ISO 8601 timestamp of the oldest item in the queue */\n oldestItem?: string;\n}\n\n// ============================================================================\n// Response Types\n// ============================================================================\n\n/**\n * Components health map for detailed health responses.\n */\nexport interface HealthComponents {\n /** Storage backend health */\n storage?: ComponentHealth;\n /** KV store health */\n kvStore?: ComponentHealth;\n /** Event broadcaster health */\n eventBroadcaster?: ComponentHealth;\n /** Circuit breaker summary (if enabled) */\n circuitBreaker?: CircuitBreakerHealthSummary;\n /** Dead letter queue summary (if enabled) */\n deadLetterQueue?: DlqHealthSummary;\n}\n\n/**\n * Standard health response structure.\n *\n * Used for all health endpoints with varying levels of detail.\n */\nexport interface HealthResponse {\n /** Overall health status */\n status: HealthStatus;\n /** ISO 8601 timestamp of the response */\n timestamp: string;\n /** Optional version string for deployment identification */\n version?: string;\n /** Server uptime in milliseconds */\n uptime?: number;\n /** Component-level health details (for /health/components) */\n components?: HealthComponents;\n}\n\n// ============================================================================\n// Configuration Types\n// ============================================================================\n\n/**\n * Configuration options for health check behavior.\n */\nexport interface HealthCheckConfig {\n /**\n * Timeout for dependency health checks in milliseconds.\n * @default 5000\n */\n timeout?: number;\n\n /**\n * Whether to check storage backend health.\n * @default true\n */\n checkStorage?: boolean;\n\n /**\n * Whether to check KV store health.\n * @default true\n */\n checkKvStore?: boolean;\n\n /**\n * Whether to check event broadcaster health.\n * @default true\n */\n checkEventBroadcaster?: boolean;\n\n /**\n * Optional version string to include in health responses.\n * Useful for identifying deployed versions.\n */\n version?: string;\n}\n\n/**\n * Default health check configuration values.\n */\nexport const DEFAULT_HEALTH_CHECK_CONFIG: Required<\n Omit<HealthCheckConfig, \"version\">\n> = {\n timeout: 5000,\n checkStorage: true,\n checkKvStore: true,\n checkEventBroadcaster: true,\n};\n\n// ============================================================================\n// Request Types (for Accept header handling)\n// ============================================================================\n\n/**\n * Supported response formats for health endpoints.\n */\nexport type HealthResponseFormat = \"json\" | \"text\";\n\n/**\n * Determines the response format based on Accept header.\n *\n * @param acceptHeader - The Accept header value from the request\n * @returns The response format to use\n */\nexport function getHealthResponseFormat(\n acceptHeader?: string | null,\n): HealthResponseFormat {\n if (acceptHeader?.includes(\"text/plain\")) {\n return \"text\";\n }\n return \"json\";\n}\n\n/**\n * Formats a health response as plain text.\n *\n * @param status - The health status\n * @returns Plain text representation\n */\nexport function formatHealthAsText(status: HealthStatus): string {\n switch (status) {\n case \"healthy\":\n return \"OK\";\n case \"degraded\":\n return \"OK\"; // Degraded still returns OK for liveness\n case \"unhealthy\":\n return \"Service Unavailable\";\n }\n}\n","import { z } from \"zod\";\n\n/**\n * Zod schema for validating InputFile objects.\n *\n * This schema defines the structure and validation rules for file upload requests.\n * Use this schema to parse and validate input data when creating new uploads.\n *\n * @see {@link InputFile} for the TypeScript type\n */\nexport const inputFileSchema = z\n .object({\n uploadLengthDeferred: z.boolean().optional(),\n storageId: z.string(),\n /** File size in bytes. Optional when uploadLengthDeferred is true. */\n size: z.number().optional(),\n /** Optional size hint for optimization when size is unknown */\n sizeHint: z.number().optional(),\n type: z.string(),\n fileName: z.string().optional(),\n lastModified: z.number().optional(),\n metadata: z.string().optional(),\n checksum: z.string().optional(),\n checksumAlgorithm: z.string().optional(),\n flow: z\n .object({\n flowId: z.string(),\n nodeId: z.string(),\n jobId: z.string(),\n })\n .optional(),\n })\n .refine(\n (data) => {\n // Size is required unless uploadLengthDeferred is true\n if (data.uploadLengthDeferred === true) {\n return true; // Size can be omitted\n }\n return data.size !== undefined && data.size >= 0;\n },\n {\n message: \"size is required when uploadLengthDeferred is not true\",\n path: [\"size\"],\n },\n );\n\n/**\n * Represents the input data for creating a new file upload.\n *\n * This type defines the information required to initiate an upload.\n * It's used by clients to provide upload metadata before sending file data.\n *\n * @property storageId - Target storage backend identifier (e.g., \"s3-production\", \"azure-blob\")\n * @property size - File size in bytes. Optional when uploadLengthDeferred is true.\n * @property sizeHint - Optional size hint for optimization when exact size is unknown\n * @property type - MIME type of the file (e.g., \"image/jpeg\", \"application/pdf\")\n * @property uploadLengthDeferred - If true, file size is not known upfront (streaming upload)\n * @property fileName - Original filename from the client\n * @property lastModified - File's last modified timestamp in milliseconds since epoch\n * @property metadata - Base64-encoded metadata string (as per tus protocol)\n * @property checksum - Expected file checksum for validation\n * @property checksumAlgorithm - Algorithm used for checksum (e.g., \"md5\", \"sha256\")\n * @property flow - Optional flow processing configuration\n * @property flow.flowId - ID of the flow to execute on this file\n * @property flow.nodeId - Starting node ID in the flow\n * @property flow.jobId - Flow job execution ID\n *\n * @example\n * ```typescript\n * // Basic file upload\n * const inputFile: InputFile = {\n * storageId: \"s3-production\",\n * size: 1024000,\n * type: \"image/jpeg\",\n * fileName: \"photo.jpg\",\n * lastModified: Date.now()\n * };\n *\n * // Upload with metadata (base64 encoded as per tus protocol)\n * const metadata = btoa(JSON.stringify({\n * userId: \"user_123\",\n * albumId: \"album_456\"\n * }));\n * const inputWithMetadata: InputFile = {\n * storageId: \"s3-production\",\n * size: 2048000,\n * type: \"image/png\",\n * fileName: \"screenshot.png\",\n * metadata\n * };\n *\n * // Upload with checksum validation\n * const inputWithChecksum: InputFile = {\n * storageId: \"s3-production\",\n * size: 512000,\n * type: \"application/pdf\",\n * fileName: \"document.pdf\",\n * checksum: \"5d41402abc4b2a76b9719d911017c592\",\n * checksumAlgorithm: \"md5\"\n * };\n *\n * // Upload that triggers a flow\n * const inputWithFlow: InputFile = {\n * storageId: \"s3-temp\",\n * size: 4096000,\n * type: \"image/jpeg\",\n * fileName: \"large-image.jpg\",\n * flow: {\n * flowId: \"resize-and-optimize\",\n * nodeId: \"input_1\",\n * jobId: \"job_789\"\n * }\n * };\n *\n * // Streaming upload (size unknown) - size can be omitted\n * const streamingInput: InputFile = {\n * storageId: \"s3-production\",\n * type: \"video/mp4\",\n * uploadLengthDeferred: true,\n * fileName: \"live-stream.mp4\"\n * };\n *\n * // Streaming upload with size hint for optimization\n * const streamingWithHint: InputFile = {\n * storageId: \"s3-production\",\n * type: \"image/webp\",\n * uploadLengthDeferred: true,\n * sizeHint: 5_000_000, // ~5MB expected\n * fileName: \"optimized-image.webp\"\n * };\n * ```\n */\nexport type InputFile = z.infer<typeof inputFileSchema>;\n","import { Context, Effect, Layer } from \"effect\";\nimport type { UploadistaError } from \"../errors\";\n\nexport type MiddlewareContext = {\n request: Request;\n uploadId?: string;\n metadata?: Record<string, string>;\n};\n\nexport type MiddlewareNext = () => Promise<Response>;\n\nexport type Middleware = (\n context: MiddlewareContext,\n next: MiddlewareNext,\n) => Promise<Response>;\n\n// Effect-based Middleware service\nexport class MiddlewareService extends Context.Tag(\"MiddlewareService\")<\n MiddlewareService,\n {\n readonly execute: (\n middlewares: Middleware[],\n context: MiddlewareContext,\n handler: MiddlewareNext,\n ) => Effect.Effect<Response, UploadistaError>;\n }\n>() {}\n\nexport const MiddlewareServiceLive = Layer.succeed(\n MiddlewareService,\n MiddlewareService.of({\n execute: (middlewares, context, handler) =>\n Effect.gen(function* () {\n if (middlewares.length === 0) {\n return yield* Effect.tryPromise({\n try: () => handler(),\n catch: (error) => error as UploadistaError,\n });\n }\n\n const chain = middlewares.reduceRight(\n (next: MiddlewareNext, middleware: Middleware) => {\n return () => middleware(context, next);\n },\n handler,\n );\n\n return yield* Effect.tryPromise({\n try: () => chain(),\n catch: (error) => error as UploadistaError,\n });\n }),\n }),\n);\n","import { z } from \"zod\";\nimport { uploadFileSchema } from \"./upload-file\";\n\nexport enum UploadEventType {\n UPLOAD_STARTED = \"upload-started\",\n UPLOAD_PROGRESS = \"upload-progress\",\n UPLOAD_COMPLETE = \"upload-complete\",\n UPLOAD_FAILED = \"upload-failed\",\n UPLOAD_VALIDATION_SUCCESS = \"upload-validation-success\",\n UPLOAD_VALIDATION_FAILED = \"upload-validation-failed\",\n UPLOAD_VALIDATION_WARNING = \"upload-validation-warning\",\n}\n\nconst flowContextSchema = z\n .object({\n flowId: z.string(),\n nodeId: z.string(),\n jobId: z.string(),\n })\n .optional();\n\nexport const uploadEventSchema = z.union([\n z.object({\n type: z.union([\n z.literal(UploadEventType.UPLOAD_STARTED),\n z.literal(UploadEventType.UPLOAD_COMPLETE),\n ]),\n data: uploadFileSchema,\n flow: flowContextSchema,\n }),\n z.object({\n type: z.literal(UploadEventType.UPLOAD_PROGRESS),\n data: z.object({\n id: z.string(),\n progress: z.number(),\n total: z.number(),\n }),\n flow: flowContextSchema,\n }),\n z.object({\n type: z.literal(UploadEventType.UPLOAD_FAILED),\n data: z.object({\n id: z.string(),\n error: z.string(),\n }),\n flow: flowContextSchema,\n }),\n z.object({\n type: z.literal(UploadEventType.UPLOAD_VALIDATION_SUCCESS),\n data: z.object({\n id: z.string(),\n validationType: z.enum([\"checksum\", \"mimetype\"]),\n algorithm: z.string().optional(),\n }),\n flow: flowContextSchema,\n }),\n z.object({\n type: z.literal(UploadEventType.UPLOAD_VALIDATION_FAILED),\n data: z.object({\n id: z.string(),\n reason: z.string(),\n expected: z.string(),\n actual: z.string(),\n }),\n flow: flowContextSchema,\n }),\n z.object({\n type: z.literal(UploadEventType.UPLOAD_VALIDATION_WARNING),\n data: z.object({\n id: z.string(),\n message: z.string(),\n }),\n flow: flowContextSchema,\n }),\n]);\n\nexport type UploadEvent = z.infer<typeof uploadEventSchema>;\n","import z from \"zod\";\nimport { uploadEventSchema } from \"./upload-event\";\n\n/**\n * Platform-agnostic WebSocket connection interface\n */\nexport interface WebSocketConnection {\n send(data: string): void;\n close(code?: number, reason?: string): void;\n readonly readyState: number;\n readonly id: string;\n}\n\n/**\n * WebSocket message that can be sent/received\n */\n\nexport const webSocketMessageSchema = z.union([\n z.object({\n type: z.literal(\"upload_event\"),\n payload: uploadEventSchema,\n timestamp: z.string().optional(),\n }),\n z.object({\n type: z.literal(\"flow_event\"),\n payload: z.any(), // FlowEvent doesn't have a zod schema, using z.any() for now\n timestamp: z.string().optional(),\n }),\n z.object({\n type: z.literal(\"subscribed\"),\n payload: z.object({ eventKey: z.string() }),\n timestamp: z.string().optional(),\n }),\n z.object({\n type: z.literal(\"error\"),\n message: z.string().optional(),\n }),\n z.object({\n type: z.literal(\"pong\"),\n timestamp: z.string().optional(),\n }),\n z.object({\n type: z.literal(\"ping\"),\n timestamp: z.string().optional(),\n }),\n z.object({\n type: z.literal(\"connection\"),\n message: z.string().optional(),\n uploadId: z.string().optional(),\n timestamp: z.string().optional(),\n }),\n]);\n\nexport type WebSocketMessage<TEvent = unknown> =\n | z.infer<typeof webSocketMessageSchema>\n | {\n type: \"upload_event\";\n payload: TEvent;\n timestamp?: string;\n }\n | {\n type: \"flow_event\";\n payload: TEvent;\n timestamp?: string;\n };\n"],"mappings":"uIAgMA,IAAa,EAAb,cAAgD,EAAQ,IACtD,6BACD,EAAmD,AAAC,GAYrD,SAAgB,EAAiC,EAKrB,CAC1B,IAAM,EAAM,KAAK,KAAK,CACtB,MAAO,CACL,MAAO,SACP,aAAc,EACd,gBAAiB,EACjB,kBAAmB,EACnB,YAAa,EACb,SACD,CC7EH,IAAa,EAAb,KAA2D,CACzD,YACE,EACA,EACA,EACA,EACA,CAJQ,KAAA,UAAA,EACA,KAAA,UAAA,EACA,KAAA,UAAA,EACA,KAAA,YAAA,EAGV,IAAO,GACL,KAAK,UAAU,IAAI,KAAK,UAAY,EAAI,CAAC,KACvC,EAAO,QAAS,GAAU,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,CACH,CAAC"}
@@ -1 +1 @@
1
- require(`../types-Cws60JHC.cjs`),require(`../uploadista-error-BgQU45we.cjs`),require(`../errors-CRm1FHHT.cjs`);const e=require(`../upload-DWBlRXHh.cjs`);require(`../checksum-DVPe3Db4.cjs`),require(`../stream-limiter-BvkaZXcz.cjs`),exports.UploadEngine=e.n,exports.UploadStrategyNegotiator=e.t,exports.compareMimeTypes=e.s,exports.createUploadEngine=e.r,exports.detectMimeType=e.c,exports.uploadEngine=e.i;
1
+ require(`../types-BF_tvkRh.cjs`),require(`../uploadista-error-CLWoRAAr.cjs`),require(`../errors-CRm1FHHT.cjs`);const e=require(`../upload-CLHJ1SFS.cjs`);require(`../checksum-CTpNXWEL.cjs`),require(`../stream-limiter-DH0vv46_.cjs`),exports.UploadEngine=e.n,exports.UploadStrategyNegotiator=e.t,exports.compareMimeTypes=e.s,exports.createUploadEngine=e.r,exports.detectMimeType=e.c,exports.uploadEngine=e.i;
@@ -1,2 +1,2 @@
1
- import { $n as UploadEngineShape, Jn as NegotiatedStrategy, Qn as UploadEngineOptions, Xn as UploadStrategyOptions, Yn as UploadStrategyNegotiator, Zn as UploadEngine, er as createUploadEngine, nr as compareMimeTypes, rr as detectMimeType, tr as uploadEngine } from "../index-DMqaf28W.cjs";
1
+ import { $n as UploadEngineShape, Jn as NegotiatedStrategy, Qn as UploadEngineOptions, Xn as UploadStrategyOptions, Yn as UploadStrategyNegotiator, Zn as UploadEngine, er as createUploadEngine, nr as compareMimeTypes, rr as detectMimeType, tr as uploadEngine } from "../index-j_n72QK0.cjs";
2
2
  export { NegotiatedStrategy, UploadEngine, UploadEngineOptions, UploadEngineShape, UploadStrategyNegotiator, UploadStrategyOptions, compareMimeTypes, createUploadEngine, detectMimeType, uploadEngine };
@@ -1,6 +1,6 @@
1
- import "../uploadista-error-DR0XimpE.mjs";
2
- import "../index-C-svZlpj.mjs";
3
- import { $n as UploadEngineShape, Jn as NegotiatedStrategy, Qn as UploadEngineOptions, Xn as UploadStrategyOptions, Yn as UploadStrategyNegotiator, Zn as UploadEngine, er as createUploadEngine, nr as compareMimeTypes, rr as detectMimeType, tr as uploadEngine } from "../index-RuQUCROH.mjs";
4
- import "../index-B9V5SSxl.mjs";
5
- import "../index-BFSHumky.mjs";
1
+ import "../uploadista-error-B1qbOy9N.mjs";
2
+ import "../index-DWe68pTi.mjs";
3
+ import { $n as UploadEngineShape, Jn as NegotiatedStrategy, Qn as UploadEngineOptions, Xn as UploadStrategyOptions, Yn as UploadStrategyNegotiator, Zn as UploadEngine, er as createUploadEngine, nr as compareMimeTypes, rr as detectMimeType, tr as uploadEngine } from "../index-BKY0VjsL.mjs";
4
+ import "../index-D8MZ6P3o.mjs";
5
+ import "../index-DQuMQssI.mjs";
6
6
  export { NegotiatedStrategy, UploadEngine, UploadEngineOptions, UploadEngineShape, UploadStrategyNegotiator, UploadStrategyOptions, compareMimeTypes, createUploadEngine, detectMimeType, uploadEngine };
@@ -1 +1 @@
1
- import"../uploadista-error-CkSxSyNo.mjs";import"../errors-CtPUOWNd.mjs";import"../types-DKGQJIEr.mjs";import{c as e,i as t,n,r,s as i,t as a}from"../upload-C-C7hn1-.mjs";import"../checksum-COoD-F1l.mjs";import"../stream-limiter-B9nsn2gb.mjs";export{n as UploadEngine,a as UploadStrategyNegotiator,i as compareMimeTypes,r as createUploadEngine,e as detectMimeType,t as uploadEngine};
1
+ import"../uploadista-error-CkSxSyNo.mjs";import"../errors-CtPUOWNd.mjs";import"../types-BRnwrJDg.mjs";import{c as e,i as t,n,r,s as i,t as a}from"../upload-CpsShjP3.mjs";import"../checksum-COoD-F1l.mjs";import"../stream-limiter-B9nsn2gb.mjs";export{n as UploadEngine,a as UploadStrategyNegotiator,i as compareMimeTypes,r as createUploadEngine,e as detectMimeType,t as uploadEngine};