@uploadista/server 0.0.18-beta.2 → 0.0.18-beta.4
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.
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +30 -3
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +30 -3
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +2 -2
- package/dist/index.mjs.map +1 -1
- package/package.json +9 -9
- package/src/core/server.ts +22 -5
- package/src/core/types.ts +28 -0
- package/src/plugins-typing.ts +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require(`./auth-Ck4gisA2.cjs`);let t=require(`effect`),n=require(`@uploadista/core/flow`),r=require(`@uploadista/core/types`),i=require(`@uploadista/core/utils`),a=require(`@uploadista/event-broadcaster-memory`),o=require(`@uploadista/event-emitter-websocket`),s=require(`@uploadista/observability`),c=require(`@uploadista/core/upload`),l=require(`@uploadista/core/errors`);var u=class extends t.Context.Tag(`AuthCacheService`)(){};const d=(e={})=>{let n=e.maxSize??1e4,r=e.ttl??36e5,i=new Map,a=()=>{let e=Date.now();for(let[t,n]of i.entries())e-n.timestamp>r&&i.delete(t)},o=()=>{if(i.size<=n)return;let e=null,t=1/0;for(let[n,r]of i.entries())r.timestamp<t&&(t=r.timestamp,e=n);e&&i.delete(e)};return t.Layer.succeed(u,{set:(e,n)=>t.Effect.sync(()=>{i.size%100==0&&a(),i.set(e,{authContext:n,timestamp:Date.now()}),o()}),get:e=>t.Effect.sync(()=>{let t=i.get(e);return t?Date.now()-t.timestamp>r?(i.delete(e),null):t.authContext:null}),delete:e=>t.Effect.sync(()=>{i.delete(e)}),clear:()=>t.Effect.sync(()=>{i.clear()}),size:()=>t.Effect.sync(()=>i.size)})},f=t.Layer.succeed(u,{set:()=>t.Effect.void,get:()=>t.Effect.succeed(null),delete:()=>t.Effect.void,clear:()=>t.Effect.void,size:()=>t.Effect.succeed(0)}),p=e=>e.split(`/`).filter(Boolean),m=e=>{let t=p(e);return t[t.length-1]},h=(e,t)=>e.includes(`${t}/api/`),g=(e,t)=>e.replace(`${t}/api/`,``).split(`/`).filter(Boolean),_=e=>{let t=500,n=`UNKNOWN_ERROR`,r=`Internal server error`,i;if(typeof e==`object`&&e){let a=e;if(`code`in a&&typeof a.code==`string`&&(n=a.code),`message`in a&&typeof a.message==`string`?r=a.message:`body`in a&&typeof a.body==`string`&&(r=a.body),`details`in a&&(i=a.details),`status`in a&&typeof a.status==`number`)t=a.status;else if(`code`in a)switch(a.code){case`FILE_NOT_FOUND`:case`FLOW_JOB_NOT_FOUND`:case`UPLOAD_ID_NOT_FOUND`:t=404;break;case`FLOW_JOB_ERROR`:case`VALIDATION_ERROR`:case`INVALID_METADATA`:case`INVALID_LENGTH`:case`ABORTED`:case`INVALID_TERMINATION`:t=400;break;case`INVALID_OFFSET`:t=409;break;case`ERR_SIZE_EXCEEDED`:case`ERR_MAX_SIZE_EXCEEDED`:t=413;break;case`FILE_NO_LONGER_EXISTS`:t=410;break;case`MISSING_OFFSET`:case`INVALID_CONTENT_TYPE`:t=403;break;default:t=500}`message`in a&&a.message===`Invalid JSON body`&&(t=400,n=`VALIDATION_ERROR`)}let a={status:t,code:n,message:r};return i!==void 0&&(a.details=i),a},v=e=>e[e.length-2],y=e=>({jobId:e[e.length-3],nodeId:e[e.length-1]}),b=e=>({storageId:e.pop(),flowId:e.pop()}),x=({kvStore:e,eventEmitter:n,dataStore:i,bufferedDataStore:a,generateId:o})=>{let s=t.Layer.provide(r.uploadFileKvStore,e),l=t.Layer.provide(i,s),u=a?t.Layer.provide(a,s):t.Layer.empty,d=t.Layer.provide(r.uploadEventEmitter,n),f=t.Layer.mergeAll(l,s,d,...o?[o]:[],u);return t.Layer.provide(c.uploadServer,f)},S=({kvStore:e,eventEmitter:i,flowProvider:a,uploadServer:o})=>{let s=t.Layer.provide(r.flowJobKvStore,e),c=t.Layer.provide(r.flowEventEmitter,i),l=t.Layer.mergeAll(a,c,s,o);return t.Layer.provide(n.flowServer,l)};var C=class extends t.Context.Tag(`AuthContextService`)(){};const w=e=>t.Layer.succeed(C,{getClientId:()=>t.Effect.succeed(e?.clientId??null),getMetadata:()=>t.Effect.succeed(e?.metadata??{}),hasPermission:n=>t.Effect.succeed(e?.permissions?.includes(n)??!1),getAuthContext:()=>t.Effect.succeed(e)}),T=w(null),E=({flowId:e})=>t.Effect.gen(function*(){let r=yield*n.FlowServer,i=yield*(yield*C).getClientId();return i&&(yield*t.Effect.logInfo(`[Flow] Getting flow data: ${e}, client: ${i}`)),{status:200,body:yield*r.getFlowData(e,i)}}),D=({flowId:e,storageId:r,inputs:i})=>t.Effect.gen(function*(){let a=yield*n.FlowServer,o=yield*C,s=yield*u,c=yield*o.getClientId();c?(yield*t.Effect.logInfo(`[Flow] Executing flow: ${e}, storage: ${r}, client: ${c}`),yield*t.Effect.logInfo(JSON.stringify(i,null,2))):(yield*t.Effect.logInfo(`[Flow] Executing flow: ${e}, storage: ${r}`),yield*t.Effect.logInfo(`[Flow] Inputs: ${JSON.stringify(i,null,2)}`)),yield*t.Effect.logInfo(`[Flow] Calling flowServer.runFlow...`);let l=yield*a.runFlow({flowId:e,storageId:r,clientId:c,inputs:i}).pipe(t.Effect.tap(()=>t.Effect.logInfo(`[Flow] runFlow completed successfully`)),t.Effect.tapError(e=>t.Effect.logError(`[Flow] runFlow failed with error: ${e}`))),d=yield*o.getAuthContext();return d&&(yield*s.set(l.id,d)),yield*t.Effect.logInfo(`[Flow] Flow started with jobId: ${l.id}`),{status:200,body:l}}),O=({jobId:e})=>t.Effect.gen(function*(){let r=yield*n.FlowServer,i=yield*C,a=yield*u,o=yield*i.getClientId();if(!e)throw Error(`No job id`);o&&(yield*t.Effect.logInfo(`[Flow] Getting job status: ${e}, client: ${o}`));let s=yield*r.getJobStatus(e);return(s.status===`completed`||s.status===`failed`)&&(yield*a.delete(e),o&&(yield*t.Effect.logInfo(`[Flow] Flow ${s.status}, cleared auth cache: ${e}`))),{status:200,body:s}}),k=({jobId:e,nodeId:r,newData:i})=>t.Effect.gen(function*(){let a=yield*n.FlowServer,o=yield*C,s=yield*u,c=yield*o.getClientId();if(c||=(yield*s.get(e))?.clientId??null,c&&(yield*t.Effect.logInfo(`[Flow] Continuing flow: jobId=${e}, nodeId=${r}, client: ${c}`)),i===void 0)throw Error(`Missing newData`);let l=yield*a.resumeFlow({jobId:e,nodeId:r,newData:i,clientId:c});return(l.status===`completed`||l.status===`failed`)&&(yield*s.delete(e),c&&(yield*t.Effect.logInfo(`[Flow] Flow ${l.status}, cleared auth cache: ${e}`))),{status:200,body:l}}),A=({jobId:e})=>t.Effect.gen(function*(){let r=yield*n.FlowServer,i=yield*C,a=yield*u,o=yield*i.getClientId();o||=(yield*a.get(e))?.clientId??null,o&&(yield*t.Effect.logInfo(`[Flow] Pausing flow: jobId=${e}, client: ${o}`));let s=yield*r.pauseFlow(e,o);return o&&(yield*t.Effect.logInfo(`[Flow] Flow paused: ${e}, status: ${s.status}`)),{status:200,body:s}}),j=({jobId:e})=>t.Effect.gen(function*(){let r=yield*n.FlowServer,i=yield*C,a=yield*u;if(!e)throw Error(`No job id`);let o=yield*i.getClientId();o||=(yield*a.get(e))?.clientId??null,o&&(yield*t.Effect.logInfo(`[Flow] Cancelling flow: jobId=${e}, client: ${o}`));let s=yield*r.cancelFlow(e,o);return yield*a.delete(e),o&&(yield*t.Effect.logInfo(`[Flow] Flow cancelled, cleared auth cache: ${e}`)),{status:200,body:s}});var M=class extends Error{constructor(e,t=500,n=`INTERNAL_ERROR`){super(e),this.statusCode=t,this.errorCode=n,this.name=`AdapterError`}},N=class extends M{constructor(e){super(e,400,`VALIDATION_ERROR`),this.name=`ValidationError`}},P=class extends M{constructor(e){super(`${e} not found`,404,`NOT_FOUND`),this.name=`NotFoundError`}},F=class extends M{constructor(e){super(e,400,`BAD_REQUEST`),this.name=`BadRequestError`}};const I=e=>({error:e.message,code:e.errorCode,timestamp:new Date().toISOString()}),L=e=>{let t={error:e.body,code:e.code,timestamp:new Date().toISOString()};return e.details!==void 0&&(t.details=e.details),t},R=(e=`Internal server error`)=>({error:e,code:`INTERNAL_ERROR`,timestamp:new Date().toISOString()}),ee=e=>t.Effect.gen(function*(){let n=yield*c.UploadServer,a=yield*C,o=yield*u,s=yield*a.getClientId();s&&(yield*t.Effect.logInfo(`[Upload] Creating upload for client: ${s}`));let l=yield*t.Effect.sync(()=>r.inputFileSchema.safeParse(e.data));if(!l.success)return yield*t.Effect.fail(new N(`Invalid input file schema`));if(l.data.checksumAlgorithm&&!(0,i.isSupportedAlgorithm)(l.data.checksumAlgorithm))return yield*t.Effect.fail(new N(`Unsupported checksum algorithm: ${l.data.checksumAlgorithm}. Supported algorithms: sha256`));let d=yield*n.createUpload(l.data,s),f=yield*a.getAuthContext();return f&&(yield*o.set(d.id,f)),s&&(yield*t.Effect.logInfo(`[Upload] Upload created: ${d.id} for client: ${s}`)),{status:200,body:d}}),z=({storageId:e})=>t.Effect.gen(function*(){let t=yield*c.UploadServer,n=yield*(yield*C).getClientId();return{status:200,body:{storageId:e,capabilities:yield*t.getCapabilities(e,n),timestamp:new Date().toISOString()}}}),B=({uploadId:e})=>t.Effect.gen(function*(){return{status:200,body:yield*(yield*c.UploadServer).getUpload(e)}}),V=e=>t.Effect.gen(function*(){let n=yield*c.UploadServer,r=yield*C,i=yield*u,a=yield*s.MetricsService,{uploadId:o,data:l}=e,d=yield*r.getClientId(),f=yield*r.getMetadata();if(!d){let e=yield*i.get(o);d=e?.clientId??null,f=e?.metadata??{}}d&&(yield*t.Effect.logInfo(`[Upload] Uploading chunk for upload: ${o}, client: ${d}`));let p=yield*n.uploadChunk(o,d,l);return p.size&&p.offset>=p.size&&(yield*i.delete(o),d&&(yield*t.Effect.logInfo(`[Upload] Upload completed, cleared auth cache: ${o}`)),d&&p.size?(yield*t.Effect.logInfo(`[Upload] Recording metrics for org: ${d}, size: ${p.size}`),yield*t.Effect.forkDaemon(a.recordUpload(d,p.size,f))):yield*t.Effect.logWarning(`[Upload] Cannot record metrics - missing organizationId or size`)),d&&(yield*t.Effect.logInfo(`[Upload] Chunk uploaded for upload: ${o}, client: ${d}`)),{status:200,body:p}}),H=e=>t.Effect.gen(function*(){switch(e.type){case`create-upload`:return yield*ee(e);case`get-capabilities`:return yield*z(e);case`get-upload`:return yield*B(e);case`upload-chunk`:return yield*V(e);case`get-flow`:return yield*E(e);case`run-flow`:return yield*D(e);case`job-status`:return yield*O(e);case`resume-flow`:return yield*k(e);case`pause-flow`:return yield*A(e);case`cancel-flow`:return yield*j(e);case`not-found`:return{status:404,headers:{"Content-Type":`application/json`},body:{error:`Not found`}};case`bad-request`:return{status:400,body:{error:`Bad request`,message:e.message}};case`method-not-allowed`:return{status:405,headers:{"Content-Type":`application/json`},body:{error:`Method not allowed`}};case`unsupported-content-type`:return{status:415,headers:{"Content-Type":`application/json`},body:{error:`Unsupported content type`}}}}),U=async({flows:e,dataStore:c,kvStore:l,plugins:u=[],eventEmitter:f,eventBroadcaster:p=a.memoryEventBroadcaster,withTracing:m=!1,baseUrl:h=`uploadista`,generateId:g=i.GenerateIdLive,metricsLayer:v,bufferedDataStore:y,adapter:b,authCacheConfig:C})=>{let T=f??(0,o.webSocketEventEmitter)(p),E=h.endsWith(`/`)?h.slice(0,-1):h,D=t.Layer.effect(n.FlowProvider,t.Effect.succeed({getFlow:(t,n)=>e(t,n)}));if(!T)throw Error(`eventEmitter is required. Provide an event emitter layer in the configuration.`);let O=x({kvStore:l,eventEmitter:T,dataStore:await(0,r.createDataStoreLayer)(c),bufferedDataStore:y,generateId:g}),k=S({kvStore:l,eventEmitter:T,flowProvider:D,uploadServer:O}),A=d(C),j=v??s.NoOpMetricsServiceLive,M=t.Layer.mergeAll(O,k,j,A,...u),N=t.ManagedRuntime.make(M);return{handler:async e=>{let r=t.Effect.gen(function*(){let r=yield*b.extractRequest(e,{baseUrl:E}),i=null;if(b.runAuthMiddleware){let n=yield*b.runAuthMiddleware(e).pipe(t.Effect.timeout(`5 seconds`),t.Effect.catchAll(()=>(console.error(`Auth middleware timeout exceeded (5 seconds)`),t.Effect.succeed({_tag:`TimeoutError`}))),t.Effect.catchAllCause(e=>(console.error(`Auth middleware error:`,e),t.Effect.succeed({_tag:`AuthError`,error:e}))));if(n&&typeof n==`object`&&`_tag`in n&&n._tag===`TimeoutError`)return yield*b.sendResponse({status:503,headers:{"Content-Type":`application/json`},body:{error:`Authentication service unavailable`,message:`Authentication took too long to respond. Please try again.`}},e);if(n&&typeof n==`object`&&`_tag`in n&&n._tag===`AuthError`)return yield*b.sendResponse({status:500,headers:{"Content-Type":`application/json`},body:{error:`Internal Server Error`,message:`An error occurred during authentication`}},e);if(n===null)return yield*b.sendResponse({status:401,headers:{"Content-Type":`application/json`},body:{error:`Unauthorized`,message:`Invalid credentials`}},e);i=n}let a=w(i),o=[];if(b.extractWaitUntil){let r=b.extractWaitUntil(e);r&&o.push(t.Layer.succeed(n.FlowWaitUntil,r))}let s=t.Layer.mergeAll(a,A,j,...u,...o);if(r.type===`not-found`)return yield*b.sendResponse({type:`not-found`,status:404,headers:{"Content-Type":`application/json`},body:{error:`Not found`}},e);let c=yield*H(r).pipe(t.Effect.provide(s));return yield*b.sendResponse(c,e)}).pipe(t.Effect.catchAll(t=>{let n=_(t),r={code:n.code,message:n.message};n.details!==void 0&&(r.details=n.details);let i={status:n.status,headers:{"Content-Type":`application/json`},body:r};return b.sendResponse(i,e)}));return m?N.runPromise(r.pipe(t.Effect.provide(s.NodeSdkLive))):N.runPromise(r)},websocketHandler:await N.runPromise(b.webSocketHandler({baseUrl:E})),baseUrl:E,dispose:()=>N.dispose()}};async function W(e){return U(e)}function G(e){return e}function K(e){return e}const q={ImagePlugin:{packageName:`@uploadista/flow-images-sharp`,variableName:`sharpImagePlugin`},ImageAiPlugin:{packageName:`@uploadista/flow-images-replicate`,variableName:`replicateImagePlugin`},ZipPlugin:{packageName:`@uploadista/flow-utility-zipjs`,variableName:`zipPlugin`},CredentialProvider:{packageName:`@uploadista/core`,variableName:`credentialProviderLayer`}};function J(e){try{let t=e;if(t._tag)return t._tag;if(t.constructor?.name)return t.constructor.name;if(t.context?.services){let e=Array.from(t.context.services.keys());if(e.length>0){let t=e[0];if(t.key)return t.key}}return null}catch{return null}}function Y(e){return e.map(e=>J(e)).filter(e=>e!==null)}function X(e){let{plugins:t,expectedServices:n=[]}=e,r=Y(t),i=n.filter(e=>!r.includes(e));return i.length===0?{success:!0}:{success:!1,required:n,provided:r,missing:i,suggestions:i.map(e=>{let t=q[e];return t?{name:e,packageName:t.packageName,importStatement:`import { ${t.variableName} } from '${t.packageName}';`}:null}).filter(e=>e!==null)}}function Z(e){let t=[`Server initialization failed: Missing required plugins`,``,`Required: ${e.required.join(`, `)}`,`Provided: ${e.provided.length>0?e.provided.join(`, `):`(none)`}`,`Missing: ${e.missing.join(`, `)}`,``];if(e.suggestions.length>0){t.push(`Add the missing plugins to your configuration:`),t.push(``);for(let n of e.suggestions)t.push(` ${n.importStatement}`);t.push(``),t.push(` const server = await createUploadistaServer({`),t.push(` plugins: [${[...e.provided,...e.missing.map(e=>q[e]?.variableName||e)].join(`, `)}],`),t.push(` // ...`),t.push(` });`)}else t.push(`Note: Could not determine package names for missing plugins.`),t.push(`Please ensure all required plugin layers are provided.`);return t.join(`
|
|
1
|
+
const e=require(`./auth-Ck4gisA2.cjs`);let t=require(`effect`),n=require(`@uploadista/core/flow`),r=require(`@uploadista/core/types`),i=require(`@uploadista/core/utils`),a=require(`@uploadista/event-broadcaster-memory`),o=require(`@uploadista/event-emitter-websocket`),s=require(`@uploadista/observability`),c=require(`@uploadista/core/upload`),l=require(`@uploadista/core/errors`);var u=class extends t.Context.Tag(`AuthCacheService`)(){};const d=(e={})=>{let n=e.maxSize??1e4,r=e.ttl??36e5,i=new Map,a=()=>{let e=Date.now();for(let[t,n]of i.entries())e-n.timestamp>r&&i.delete(t)},o=()=>{if(i.size<=n)return;let e=null,t=1/0;for(let[n,r]of i.entries())r.timestamp<t&&(t=r.timestamp,e=n);e&&i.delete(e)};return t.Layer.succeed(u,{set:(e,n)=>t.Effect.sync(()=>{i.size%100==0&&a(),i.set(e,{authContext:n,timestamp:Date.now()}),o()}),get:e=>t.Effect.sync(()=>{let t=i.get(e);return t?Date.now()-t.timestamp>r?(i.delete(e),null):t.authContext:null}),delete:e=>t.Effect.sync(()=>{i.delete(e)}),clear:()=>t.Effect.sync(()=>{i.clear()}),size:()=>t.Effect.sync(()=>i.size)})},f=t.Layer.succeed(u,{set:()=>t.Effect.void,get:()=>t.Effect.succeed(null),delete:()=>t.Effect.void,clear:()=>t.Effect.void,size:()=>t.Effect.succeed(0)}),p=e=>e.split(`/`).filter(Boolean),m=e=>{let t=p(e);return t[t.length-1]},h=(e,t)=>e.includes(`${t}/api/`),g=(e,t)=>e.replace(`${t}/api/`,``).split(`/`).filter(Boolean),_=e=>{let t=500,n=`UNKNOWN_ERROR`,r=`Internal server error`,i;if(typeof e==`object`&&e){let a=e;if(`code`in a&&typeof a.code==`string`&&(n=a.code),`message`in a&&typeof a.message==`string`?r=a.message:`body`in a&&typeof a.body==`string`&&(r=a.body),`details`in a&&(i=a.details),`status`in a&&typeof a.status==`number`)t=a.status;else if(`code`in a)switch(a.code){case`FILE_NOT_FOUND`:case`FLOW_JOB_NOT_FOUND`:case`UPLOAD_ID_NOT_FOUND`:t=404;break;case`FLOW_JOB_ERROR`:case`VALIDATION_ERROR`:case`INVALID_METADATA`:case`INVALID_LENGTH`:case`ABORTED`:case`INVALID_TERMINATION`:t=400;break;case`INVALID_OFFSET`:t=409;break;case`ERR_SIZE_EXCEEDED`:case`ERR_MAX_SIZE_EXCEEDED`:t=413;break;case`FILE_NO_LONGER_EXISTS`:t=410;break;case`MISSING_OFFSET`:case`INVALID_CONTENT_TYPE`:t=403;break;default:t=500}`message`in a&&a.message===`Invalid JSON body`&&(t=400,n=`VALIDATION_ERROR`)}let a={status:t,code:n,message:r};return i!==void 0&&(a.details=i),a},v=e=>e[e.length-2],y=e=>({jobId:e[e.length-3],nodeId:e[e.length-1]}),b=e=>({storageId:e.pop(),flowId:e.pop()}),x=({kvStore:e,eventEmitter:n,dataStore:i,bufferedDataStore:a,generateId:o})=>{let s=t.Layer.provide(r.uploadFileKvStore,e),l=t.Layer.provide(i,s),u=a?t.Layer.provide(a,s):t.Layer.empty,d=t.Layer.provide(r.uploadEventEmitter,n),f=t.Layer.mergeAll(l,s,d,...o?[o]:[],u);return t.Layer.provide(c.uploadServer,f)},S=({kvStore:e,eventEmitter:i,flowProvider:a,uploadServer:o})=>{let s=t.Layer.provide(r.flowJobKvStore,e),c=t.Layer.provide(r.flowEventEmitter,i),l=t.Layer.mergeAll(a,c,s,o);return t.Layer.provide(n.flowServer,l)};var C=class extends t.Context.Tag(`AuthContextService`)(){};const w=e=>t.Layer.succeed(C,{getClientId:()=>t.Effect.succeed(e?.clientId??null),getMetadata:()=>t.Effect.succeed(e?.metadata??{}),hasPermission:n=>t.Effect.succeed(e?.permissions?.includes(n)??!1),getAuthContext:()=>t.Effect.succeed(e)}),T=w(null),E=({flowId:e})=>t.Effect.gen(function*(){let r=yield*n.FlowServer,i=yield*(yield*C).getClientId();return i&&(yield*t.Effect.logInfo(`[Flow] Getting flow data: ${e}, client: ${i}`)),{status:200,body:yield*r.getFlowData(e,i)}}),D=({flowId:e,storageId:r,inputs:i})=>t.Effect.gen(function*(){let a=yield*n.FlowServer,o=yield*C,s=yield*u,c=yield*o.getClientId();c?(yield*t.Effect.logInfo(`[Flow] Executing flow: ${e}, storage: ${r}, client: ${c}`),yield*t.Effect.logInfo(JSON.stringify(i,null,2))):(yield*t.Effect.logInfo(`[Flow] Executing flow: ${e}, storage: ${r}`),yield*t.Effect.logInfo(`[Flow] Inputs: ${JSON.stringify(i,null,2)}`)),yield*t.Effect.logInfo(`[Flow] Calling flowServer.runFlow...`);let l=yield*a.runFlow({flowId:e,storageId:r,clientId:c,inputs:i}).pipe(t.Effect.tap(()=>t.Effect.logInfo(`[Flow] runFlow completed successfully`)),t.Effect.tapError(e=>t.Effect.logError(`[Flow] runFlow failed with error: ${e}`))),d=yield*o.getAuthContext();return d&&(yield*s.set(l.id,d)),yield*t.Effect.logInfo(`[Flow] Flow started with jobId: ${l.id}`),{status:200,body:l}}),O=({jobId:e})=>t.Effect.gen(function*(){let r=yield*n.FlowServer,i=yield*C,a=yield*u,o=yield*i.getClientId();if(!e)throw Error(`No job id`);o&&(yield*t.Effect.logInfo(`[Flow] Getting job status: ${e}, client: ${o}`));let s=yield*r.getJobStatus(e);return(s.status===`completed`||s.status===`failed`)&&(yield*a.delete(e),o&&(yield*t.Effect.logInfo(`[Flow] Flow ${s.status}, cleared auth cache: ${e}`))),{status:200,body:s}}),k=({jobId:e,nodeId:r,newData:i})=>t.Effect.gen(function*(){let a=yield*n.FlowServer,o=yield*C,s=yield*u,c=yield*o.getClientId();if(c||=(yield*s.get(e))?.clientId??null,c&&(yield*t.Effect.logInfo(`[Flow] Continuing flow: jobId=${e}, nodeId=${r}, client: ${c}`)),i===void 0)throw Error(`Missing newData`);let l=yield*a.resumeFlow({jobId:e,nodeId:r,newData:i,clientId:c});return(l.status===`completed`||l.status===`failed`)&&(yield*s.delete(e),c&&(yield*t.Effect.logInfo(`[Flow] Flow ${l.status}, cleared auth cache: ${e}`))),{status:200,body:l}}),A=({jobId:e})=>t.Effect.gen(function*(){let r=yield*n.FlowServer,i=yield*C,a=yield*u,o=yield*i.getClientId();o||=(yield*a.get(e))?.clientId??null,o&&(yield*t.Effect.logInfo(`[Flow] Pausing flow: jobId=${e}, client: ${o}`));let s=yield*r.pauseFlow(e,o);return o&&(yield*t.Effect.logInfo(`[Flow] Flow paused: ${e}, status: ${s.status}`)),{status:200,body:s}}),j=({jobId:e})=>t.Effect.gen(function*(){let r=yield*n.FlowServer,i=yield*C,a=yield*u;if(!e)throw Error(`No job id`);let o=yield*i.getClientId();o||=(yield*a.get(e))?.clientId??null,o&&(yield*t.Effect.logInfo(`[Flow] Cancelling flow: jobId=${e}, client: ${o}`));let s=yield*r.cancelFlow(e,o);return yield*a.delete(e),o&&(yield*t.Effect.logInfo(`[Flow] Flow cancelled, cleared auth cache: ${e}`)),{status:200,body:s}});var M=class extends Error{constructor(e,t=500,n=`INTERNAL_ERROR`){super(e),this.statusCode=t,this.errorCode=n,this.name=`AdapterError`}},N=class extends M{constructor(e){super(e,400,`VALIDATION_ERROR`),this.name=`ValidationError`}},P=class extends M{constructor(e){super(`${e} not found`,404,`NOT_FOUND`),this.name=`NotFoundError`}},F=class extends M{constructor(e){super(e,400,`BAD_REQUEST`),this.name=`BadRequestError`}};const I=e=>({error:e.message,code:e.errorCode,timestamp:new Date().toISOString()}),L=e=>{let t={error:e.body,code:e.code,timestamp:new Date().toISOString()};return e.details!==void 0&&(t.details=e.details),t},R=(e=`Internal server error`)=>({error:e,code:`INTERNAL_ERROR`,timestamp:new Date().toISOString()}),z=e=>t.Effect.gen(function*(){let n=yield*c.UploadServer,a=yield*C,o=yield*u,s=yield*a.getClientId();s&&(yield*t.Effect.logInfo(`[Upload] Creating upload for client: ${s}`));let l=yield*t.Effect.sync(()=>r.inputFileSchema.safeParse(e.data));if(!l.success)return yield*t.Effect.fail(new N(`Invalid input file schema`));if(l.data.checksumAlgorithm&&!(0,i.isSupportedAlgorithm)(l.data.checksumAlgorithm))return yield*t.Effect.fail(new N(`Unsupported checksum algorithm: ${l.data.checksumAlgorithm}. Supported algorithms: sha256`));let d=yield*n.createUpload(l.data,s),f=yield*a.getAuthContext();return f&&(yield*o.set(d.id,f)),s&&(yield*t.Effect.logInfo(`[Upload] Upload created: ${d.id} for client: ${s}`)),{status:200,body:d}}),B=({storageId:e})=>t.Effect.gen(function*(){let t=yield*c.UploadServer,n=yield*(yield*C).getClientId();return{status:200,body:{storageId:e,capabilities:yield*t.getCapabilities(e,n),timestamp:new Date().toISOString()}}}),V=({uploadId:e})=>t.Effect.gen(function*(){return{status:200,body:yield*(yield*c.UploadServer).getUpload(e)}}),ee=e=>t.Effect.gen(function*(){let n=yield*c.UploadServer,r=yield*C,i=yield*u,a=yield*s.MetricsService,{uploadId:o,data:l}=e,d=yield*r.getClientId(),f=yield*r.getMetadata();if(!d){let e=yield*i.get(o);d=e?.clientId??null,f=e?.metadata??{}}d&&(yield*t.Effect.logInfo(`[Upload] Uploading chunk for upload: ${o}, client: ${d}`));let p=yield*n.uploadChunk(o,d,l);return p.size&&p.offset>=p.size&&(yield*i.delete(o),d&&(yield*t.Effect.logInfo(`[Upload] Upload completed, cleared auth cache: ${o}`)),d&&p.size?(yield*t.Effect.logInfo(`[Upload] Recording metrics for org: ${d}, size: ${p.size}`),yield*t.Effect.forkDaemon(a.recordUpload(d,p.size,f))):yield*t.Effect.logWarning(`[Upload] Cannot record metrics - missing organizationId or size`)),d&&(yield*t.Effect.logInfo(`[Upload] Chunk uploaded for upload: ${o}, client: ${d}`)),{status:200,body:p}}),H=e=>t.Effect.gen(function*(){switch(e.type){case`create-upload`:return yield*z(e);case`get-capabilities`:return yield*B(e);case`get-upload`:return yield*V(e);case`upload-chunk`:return yield*ee(e);case`get-flow`:return yield*E(e);case`run-flow`:return yield*D(e);case`job-status`:return yield*O(e);case`resume-flow`:return yield*k(e);case`pause-flow`:return yield*A(e);case`cancel-flow`:return yield*j(e);case`not-found`:return{status:404,headers:{"Content-Type":`application/json`},body:{error:`Not found`}};case`bad-request`:return{status:400,body:{error:`Bad request`,message:e.message}};case`method-not-allowed`:return{status:405,headers:{"Content-Type":`application/json`},body:{error:`Method not allowed`}};case`unsupported-content-type`:return{status:415,headers:{"Content-Type":`application/json`},body:{error:`Unsupported content type`}}}}),U=async({flows:e,dataStore:c,kvStore:l,plugins:u=[],eventEmitter:f,eventBroadcaster:p=a.memoryEventBroadcaster,withTracing:m=!1,baseUrl:h=`uploadista`,generateId:g=i.GenerateIdLive,metricsLayer:v,bufferedDataStore:y,adapter:b,authCacheConfig:C,circuitBreaker:T=!0})=>{let E=f??(0,o.webSocketEventEmitter)(p),D=h.endsWith(`/`)?h.slice(0,-1):h,O=t.Layer.effect(n.FlowProvider,t.Effect.succeed({getFlow:(t,n)=>e(t,n)}));if(!E)throw Error(`eventEmitter is required. Provide an event emitter layer in the configuration.`);let k=x({kvStore:l,eventEmitter:E,dataStore:await(0,r.createDataStoreLayer)(c),bufferedDataStore:y,generateId:g}),A=S({kvStore:l,eventEmitter:E,flowProvider:O,uploadServer:k}),j=d(C),M=v??s.NoOpMetricsServiceLive,N=T?n.kvCircuitBreakerStoreLayer.pipe(t.Layer.provide(l)):null,P=t.Layer.mergeAll(k,A,M,j,...u),F=N?t.Layer.merge(P,N):P,I=t.ManagedRuntime.make(F);return{handler:async e=>{let r=t.Effect.gen(function*(){let r=yield*b.extractRequest(e,{baseUrl:D}),i=null;if(b.runAuthMiddleware){let n=yield*b.runAuthMiddleware(e).pipe(t.Effect.timeout(`5 seconds`),t.Effect.catchAll(()=>(console.error(`Auth middleware timeout exceeded (5 seconds)`),t.Effect.succeed({_tag:`TimeoutError`}))),t.Effect.catchAllCause(e=>(console.error(`Auth middleware error:`,e),t.Effect.succeed({_tag:`AuthError`,error:e}))));if(n&&typeof n==`object`&&`_tag`in n&&n._tag===`TimeoutError`)return yield*b.sendResponse({status:503,headers:{"Content-Type":`application/json`},body:{error:`Authentication service unavailable`,message:`Authentication took too long to respond. Please try again.`}},e);if(n&&typeof n==`object`&&`_tag`in n&&n._tag===`AuthError`)return yield*b.sendResponse({status:500,headers:{"Content-Type":`application/json`},body:{error:`Internal Server Error`,message:`An error occurred during authentication`}},e);if(n===null)return yield*b.sendResponse({status:401,headers:{"Content-Type":`application/json`},body:{error:`Unauthorized`,message:`Invalid credentials`}},e);i=n}let a=w(i),o=[];if(b.extractWaitUntil){let r=b.extractWaitUntil(e);r&&o.push(t.Layer.succeed(n.FlowWaitUntil,r))}let s=t.Layer.mergeAll(a,j,M,...u,...o),c=N?t.Layer.merge(s,N):s;if(r.type===`not-found`)return yield*b.sendResponse({type:`not-found`,status:404,headers:{"Content-Type":`application/json`},body:{error:`Not found`}},e);let l=yield*H(r).pipe(t.Effect.provide(c));return yield*b.sendResponse(l,e)}).pipe(t.Effect.catchAll(t=>{let n=_(t),r={code:n.code,message:n.message};n.details!==void 0&&(r.details=n.details);let i={status:n.status,headers:{"Content-Type":`application/json`},body:r};return b.sendResponse(i,e)}));return m?I.runPromise(r.pipe(t.Effect.provide(s.NodeSdkLive))):I.runPromise(r)},websocketHandler:await I.runPromise(b.webSocketHandler({baseUrl:D})),baseUrl:D,dispose:()=>I.dispose()}};async function W(e){return U(e)}function G(e){return e}function K(e){return e}const q={ImagePlugin:{packageName:`@uploadista/flow-images-sharp`,variableName:`sharpImagePlugin`},ImageAiPlugin:{packageName:`@uploadista/flow-images-replicate`,variableName:`replicateImagePlugin`},ZipPlugin:{packageName:`@uploadista/flow-utility-zipjs`,variableName:`zipPlugin`},CredentialProvider:{packageName:`@uploadista/core`,variableName:`credentialProviderLayer`}};function J(e){try{let t=e;if(t._tag)return t._tag;if(t.constructor?.name)return t.constructor.name;if(t.context?.services){let e=Array.from(t.context.services.keys());if(e.length>0){let t=e[0];if(t.key)return t.key}}return null}catch{return null}}function Y(e){return e.map(e=>J(e)).filter(e=>e!==null)}function X(e){let{plugins:t,expectedServices:n=[]}=e,r=Y(t),i=n.filter(e=>!r.includes(e));return i.length===0?{success:!0}:{success:!1,required:n,provided:r,missing:i,suggestions:i.map(e=>{let t=q[e];return t?{name:e,packageName:t.packageName,importStatement:`import { ${t.variableName} } from '${t.packageName}';`}:null}).filter(e=>e!==null)}}function Z(e){let t=[`Server initialization failed: Missing required plugins`,``,`Required: ${e.required.join(`, `)}`,`Provided: ${e.provided.length>0?e.provided.join(`, `):`(none)`}`,`Missing: ${e.missing.join(`, `)}`,``];if(e.suggestions.length>0){t.push(`Add the missing plugins to your configuration:`),t.push(``);for(let n of e.suggestions)t.push(` ${n.importStatement}`);t.push(``),t.push(` const server = await createUploadistaServer({`),t.push(` plugins: [${[...e.provided,...e.missing.map(e=>q[e]?.variableName||e)].join(`, `)}],`),t.push(` // ...`),t.push(` });`)}else t.push(`Note: Could not determine package names for missing plugins.`),t.push(`Please ensure all required plugin layers are provided.`);return t.join(`
|
|
2
2
|
`)}function Q(e){return t.Effect.sync(()=>{let t=X(e);if(!t.success){let e=Z(t);throw Error(e)}})}function te(e){let t=X(e);if(!t.success){let e=Z(t);throw Error(e)}}const ne=(e,n,r)=>t.Effect.gen(function*(){if(!n){yield*t.Effect.sync(()=>{r.send(JSON.stringify({type:`error`,message:`Job ID is required for flow event subscription`,code:`MISSING_JOB_ID`}))});return}yield*e.subscribeToFlowEvents(n,r)}),re=(e,n)=>t.Effect.gen(function*(){n&&(yield*e.unsubscribeFromFlowEvents(n))}),$=(e,n,r)=>t.Effect.gen(function*(){if(!n){yield*t.Effect.sync(()=>{r.send(JSON.stringify({type:`error`,message:`Upload ID is required for upload event subscription`,code:`MISSING_UPLOAD_ID`}))});return}yield*e.subscribeToUploadEvents(n,r)}),ie=(e,n)=>t.Effect.gen(function*(){n&&(yield*e.unsubscribeFromUploadEvents(n))}),ae=(e,n,r)=>{let{connection:i,isFlowRoute:a,isUploadRoute:o,jobId:s,uploadId:c,eventId:u}=e;return t.Effect.gen(function*(){a&&(yield*ne(r,s,i)),o&&(yield*$(n,c,i)),i.send(JSON.stringify({type:`connection`,message:`Uploadista WebSocket connected`,id:u,jobId:s,uploadId:c,timestamp:new Date().toISOString()}))}).pipe(t.Effect.catchAll(e=>t.Effect.sync(()=>{console.error(`Error subscribing to events:`,e);let t=e instanceof l.UploadistaError?e.body:`Failed to subscribe to events`;i.send(JSON.stringify({type:`error`,message:t,code:e instanceof l.UploadistaError?e.code:`SUBSCRIPTION_ERROR`}))})))},oe=(e,n)=>t.Effect.sync(()=>{try{JSON.parse(e).type===`ping`&&n.send(JSON.stringify({type:`pong`,timestamp:new Date().toISOString()}))}catch(e){console.error(`Error handling WebSocket message:`,e),n.send(JSON.stringify({type:`error`,message:`Invalid message format`}))}}),se=(e,n,r)=>{let{isFlowRoute:i,isUploadRoute:a,jobId:o,uploadId:s}=e;return t.Effect.gen(function*(){i&&(yield*re(r,o)),a&&(yield*ie(n,s))}).pipe(t.Effect.catchAll(e=>t.Effect.sync(()=>{console.error(`Error unsubscribing from events:`,e instanceof l.UploadistaError?e.body:e)})))},ce=(e,n)=>t.Effect.sync(()=>{console.error(`WebSocket error for event ${n}:`,e)});exports.AdapterError=M,exports.AuthCacheService=u,exports.AuthCacheServiceLive=d,exports.AuthContextService=C,exports.AuthContextServiceLive=w,exports.BadRequestError=F,exports.NoAuthCacheServiceLive=f,exports.NoAuthContextServiceLive=T,exports.NotFoundError=P,exports.ValidationError=N,exports.createErrorResponseBody=I,exports.createFlowServerLayer=S,exports.createGenericErrorResponseBody=R,exports.createTypeSafeServer=W,exports.createUploadServerLayer=x,exports.createUploadistaErrorResponseBody=L,exports.createUploadistaServer=U,exports.defineFlow=G,exports.defineSimpleFlow=K,exports.extractFlowAndStorageId=b,exports.extractJobAndNodeId=y,exports.extractJobIdFromStatus=v,exports.extractServiceIdentifiers=Y,exports.formatPluginValidationError=Z,exports.getAuthCredentials=e.t,exports.getLastSegment=m,exports.getRouteSegments=g,exports.handleFlowError=_,exports.handleWebSocketClose=se,exports.handleWebSocketError=ce,exports.handleWebSocketMessage=oe,exports.handleWebSocketOpen=ae,exports.hasBasePath=h,exports.parseUrlSegments=p,exports.validatePluginRequirements=X,exports.validatePluginRequirementsEffect=Q,exports.validatePluginsOrThrow=te;
|
package/dist/index.d.cts
CHANGED
|
@@ -9,7 +9,6 @@ import { GenerateId } from "@uploadista/core/utils";
|
|
|
9
9
|
import { MetricsService } from "@uploadista/observability";
|
|
10
10
|
import { UploadServer as UploadServer$1, UploadServerShape } from "@uploadista/core/upload";
|
|
11
11
|
import { UploadistaError as UploadistaError$1 } from "@uploadista/core/errors";
|
|
12
|
-
import { ExtractLayerServices as ExtractLayerServices$1 } from "@uploadista/core/flow/types";
|
|
13
12
|
|
|
14
13
|
//#region src/core/routes.d.ts
|
|
15
14
|
type UploadistaRouteType = "create-upload" | "get-capabilities" | "get-upload" | "upload-chunk" | "get-flow" | "run-flow" | "job-status" | "resume-flow" | "pause-flow" | "cancel-flow" | "not-found" | "bad-request" | "method-not-allowed" | "unsupported-content-type";
|
|
@@ -817,6 +816,33 @@ interface UploadistaServerConfig<TRequest, TResponse, TWebSocket = unknown, TFlo
|
|
|
817
816
|
* ```
|
|
818
817
|
*/
|
|
819
818
|
authCacheConfig?: AuthCacheConfig;
|
|
819
|
+
/**
|
|
820
|
+
* Optional: Enable circuit breakers for flow nodes.
|
|
821
|
+
*
|
|
822
|
+
* When enabled (default), circuit breaker state is stored in the KV store,
|
|
823
|
+
* allowing circuit breaker state to be shared across multiple server instances
|
|
824
|
+
* in a cluster deployment.
|
|
825
|
+
*
|
|
826
|
+
* Set to `false` to disable circuit breakers entirely.
|
|
827
|
+
*
|
|
828
|
+
* @default true
|
|
829
|
+
*
|
|
830
|
+
* @example
|
|
831
|
+
* ```typescript
|
|
832
|
+
* // Circuit breakers enabled by default (uses the provided kvStore)
|
|
833
|
+
* const server = await createUploadistaServer({
|
|
834
|
+
* kvStore: redisKvStore,
|
|
835
|
+
* // circuitBreaker: true (default)
|
|
836
|
+
* });
|
|
837
|
+
*
|
|
838
|
+
* // Disable circuit breakers
|
|
839
|
+
* const server = await createUploadistaServer({
|
|
840
|
+
* kvStore: redisKvStore,
|
|
841
|
+
* circuitBreaker: false
|
|
842
|
+
* });
|
|
843
|
+
* ```
|
|
844
|
+
*/
|
|
845
|
+
circuitBreaker?: boolean;
|
|
820
846
|
}
|
|
821
847
|
/**
|
|
822
848
|
* Return type from createUploadistaServer.
|
|
@@ -1288,7 +1314,8 @@ declare const createUploadistaServer: <TContext, TResponse, TWebSocketHandler =
|
|
|
1288
1314
|
metricsLayer,
|
|
1289
1315
|
bufferedDataStore,
|
|
1290
1316
|
adapter,
|
|
1291
|
-
authCacheConfig
|
|
1317
|
+
authCacheConfig,
|
|
1318
|
+
circuitBreaker
|
|
1292
1319
|
}: UploadistaServerConfig<TContext, TResponse, TWebSocketHandler, TFlows, TPlugins>) => Promise<UploadistaServer<TContext, TResponse, TWebSocketHandler>>;
|
|
1293
1320
|
//#endregion
|
|
1294
1321
|
//#region src/core/websocket-routes.d.ts
|
|
@@ -1840,7 +1867,7 @@ declare const createFlowServerLayer: ({
|
|
|
1840
1867
|
* type Services = ExtractLayerServices<[ImagePluginLayer, ZipPluginLayer]>;
|
|
1841
1868
|
* ```
|
|
1842
1869
|
*/
|
|
1843
|
-
type LayerSuccessUnion<Layers extends readonly Layer.Layer<any, never, never>[]> = ExtractLayerServices
|
|
1870
|
+
type LayerSuccessUnion<Layers extends readonly Layer.Layer<any, never, never>[]> = ExtractLayerServices<Layers>;
|
|
1844
1871
|
/**
|
|
1845
1872
|
* @deprecated This type is deprecated. Extract flow requirements directly from your flow types instead.
|
|
1846
1873
|
*
|
package/dist/index.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.cts","names":[],"sources":["../src/core/routes.ts","../src/types.ts","../src/adapter/types.ts","../src/cache.ts","../src/core/plugin-types.ts","../src/core/types.ts","../src/core/create-type-safe-server.ts","../src/core/plugin-validation.ts","../src/core/server.ts","../src/core/websocket-routes.ts","../src/core/websocket-handlers/websocket-handlers.ts","../src/error-types.ts","../src/http-utils.ts","../src/layer-utils.ts","../src/plugins-typing.ts","../src/service.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;;;KAQY,mBAAA;KAgBA,0BAA0B;QAC9B;;KAGI,qCACA,kEAGR,gBAAgB;UACV;;;;QAEF;;KAGI,eAAA,GAAkB;AA9BlB,KAgCA,gBAAA,GAAmB,0BAhCA,CAAA,WAAA,EAAA;EAgBnB,KAAA,EAAA,WAAe;AAI3B,CAAA,EAAA,GAAY,CAAA;AACA,KAiBA,uBAAA,GAA0B,eAjB1B,CAAA,oBAAA,CAAA;AAGQ,KAgBR,wBAAA,GAA2B,0BAhBnB,CAAA,oBAAA,E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A,EAAA,CAAA,GYgEd,OZhEc,CYiEhB,iBZjEgB,CYiEE,MZjEF,CAAA,EYkEhB,iBZlEgB,CYkEE,QZlEF,CAAA,CAAA,SAAA,KAAA,GAAA,OAAA,GAAA;EAuBD,gBAAA,EY+CO,OZ/CS,CYgDzB,iBZ9BgB,CY8BE,MZ9BF,CAAA,EY+BhB,iBZ/BgB,CY+BE,QZ/BF,CAAA,CAAA;AAqCxB,CAAA;;;cajJ2C;;;;;8BA8BX,MAAA,CAAO;;;;;8BAMP,MAAA,CAAO,OAAO;;Af7B9C;AAgBA;AAIA;EACY,SAAA,aAAA,EAAA,CAAA,UAAA,EAAA,MAAA,EAAA,GecwC,MAAA,CAAO,Mfd/C,CAAA,OAAA,CAAA;EAGQ;;;;EAGA,SAAA,cAAA,EAAA,GAAA,Gece,MAAA,CAAO,MfdtB,Cec6B,Wfd7B,GAAA,IAAA,CAAA;AAGpB,CAAA,CAAA;AAEA;AAMA;AAEA;AAMA;AAIA;AAMA;AAGA;AAKA;AAGA;AAIA;AAGA;AASA;AAIA;AAKA;AAKA;AAKA;AAGA;AAEA;AAKA;AAEA;AAGA;AAKY,ce1GC,kBAAA,SAA2B,uBAAA,Cf0GO;AAU/C;AAGA;AAKA;AAGA;AAKA;;;AAGI,cenGS,sBfmGT,EAAA,CAAA,WAAA,EelGW,WfkGX,GAAA,IAAA,EAAA,GejGD,KAAA,CAAM,KfiGL,CejGW,kBfiGX,CAAA;;;;;;AAMA,cezFS,wBfyFT,EezFmC,KAAA,CAAM,KfyFzC,CezF+C,kBfyF/C,CAAA"}
|
|
1
|
+
{"version":3,"file":"index.d.cts","names":[],"sources":["../src/core/routes.ts","../src/types.ts","../src/adapter/types.ts","../src/cache.ts","../src/core/plugin-types.ts","../src/core/types.ts","../src/core/create-type-safe-server.ts","../src/core/plugin-validation.ts","../src/core/server.ts","../src/core/websocket-routes.ts","../src/core/websocket-handlers/websocket-handlers.ts","../src/error-types.ts","../src/http-utils.ts","../src/layer-utils.ts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AA,CAAA;AAE7C,CAAA,CAAA;AAMA;AAEA;AAMA;AAIA;AAMA;AAGA;AAKA;AAGA;AAIA;AAGA;AASA;AAIA;AAKA;AAKA;AAKA;AAGA;AAEA;AAKA;AAEA;AAGA;AAKA;AAKY,ce/GC,kBAAA,SAA2B,uBAAA,Cf+GP;AAQjC;AAKA;AAGA;AAKA;;;;AAII,cepGS,sBfoGT,EAAA,CAAA,WAAA,EenGW,WfmGX,GAAA,IAAA,EAAA,GelGD,KAAA,CAAM,KfkGL,CelGW,kBfkGX,CAAA;;;;;;AAMA,ce1FS,wBf0FT,Ee1FmC,KAAA,CAAM,Kf0FzC,Ce1F+C,kBf0F/C,CAAA"}
|
package/dist/index.d.mts
CHANGED
|
@@ -9,7 +9,6 @@ import { UploadistaError } from "@uploadista/core/errors";
|
|
|
9
9
|
import * as _uploadista_core0 from "@uploadista/core";
|
|
10
10
|
import { DataStoreCapabilities, Flow as Flow$1, FlowData, FlowJob, FlowServer as FlowServer$1, PluginLayer, UploadEvent, UploadFile, UploadServer as UploadServer$1, UploadistaError as UploadistaError$1, VideoPluginLayer } from "@uploadista/core";
|
|
11
11
|
import z$1, { z } from "zod";
|
|
12
|
-
import { ExtractLayerServices as ExtractLayerServices$1 } from "@uploadista/core/flow/types";
|
|
13
12
|
|
|
14
13
|
//#region src/core/routes.d.ts
|
|
15
14
|
type UploadistaRouteType = "create-upload" | "get-capabilities" | "get-upload" | "upload-chunk" | "get-flow" | "run-flow" | "job-status" | "resume-flow" | "pause-flow" | "cancel-flow" | "not-found" | "bad-request" | "method-not-allowed" | "unsupported-content-type";
|
|
@@ -817,6 +816,33 @@ interface UploadistaServerConfig<TRequest, TResponse, TWebSocket = unknown, TFlo
|
|
|
817
816
|
* ```
|
|
818
817
|
*/
|
|
819
818
|
authCacheConfig?: AuthCacheConfig;
|
|
819
|
+
/**
|
|
820
|
+
* Optional: Enable circuit breakers for flow nodes.
|
|
821
|
+
*
|
|
822
|
+
* When enabled (default), circuit breaker state is stored in the KV store,
|
|
823
|
+
* allowing circuit breaker state to be shared across multiple server instances
|
|
824
|
+
* in a cluster deployment.
|
|
825
|
+
*
|
|
826
|
+
* Set to `false` to disable circuit breakers entirely.
|
|
827
|
+
*
|
|
828
|
+
* @default true
|
|
829
|
+
*
|
|
830
|
+
* @example
|
|
831
|
+
* ```typescript
|
|
832
|
+
* // Circuit breakers enabled by default (uses the provided kvStore)
|
|
833
|
+
* const server = await createUploadistaServer({
|
|
834
|
+
* kvStore: redisKvStore,
|
|
835
|
+
* // circuitBreaker: true (default)
|
|
836
|
+
* });
|
|
837
|
+
*
|
|
838
|
+
* // Disable circuit breakers
|
|
839
|
+
* const server = await createUploadistaServer({
|
|
840
|
+
* kvStore: redisKvStore,
|
|
841
|
+
* circuitBreaker: false
|
|
842
|
+
* });
|
|
843
|
+
* ```
|
|
844
|
+
*/
|
|
845
|
+
circuitBreaker?: boolean;
|
|
820
846
|
}
|
|
821
847
|
/**
|
|
822
848
|
* Return type from createUploadistaServer.
|
|
@@ -1288,7 +1314,8 @@ declare const createUploadistaServer: <TContext, TResponse, TWebSocketHandler =
|
|
|
1288
1314
|
metricsLayer,
|
|
1289
1315
|
bufferedDataStore,
|
|
1290
1316
|
adapter,
|
|
1291
|
-
authCacheConfig
|
|
1317
|
+
authCacheConfig,
|
|
1318
|
+
circuitBreaker
|
|
1292
1319
|
}: UploadistaServerConfig<TContext, TResponse, TWebSocketHandler, TFlows, TPlugins>) => Promise<UploadistaServer<TContext, TResponse, TWebSocketHandler>>;
|
|
1293
1320
|
//#endregion
|
|
1294
1321
|
//#region src/core/websocket-routes.d.ts
|
|
@@ -1840,7 +1867,7 @@ declare const createFlowServerLayer: ({
|
|
|
1840
1867
|
* type Services = ExtractLayerServices<[ImagePluginLayer, ZipPluginLayer]>;
|
|
1841
1868
|
* ```
|
|
1842
1869
|
*/
|
|
1843
|
-
type LayerSuccessUnion<Layers extends readonly Layer.Layer<any, never, never>[]> = ExtractLayerServices
|
|
1870
|
+
type LayerSuccessUnion<Layers extends readonly Layer.Layer<any, never, never>[]> = ExtractLayerServices<Layers>;
|
|
1844
1871
|
/**
|
|
1845
1872
|
* @deprecated This type is deprecated. Extract flow requirements directly from your flow types instead.
|
|
1846
1873
|
*
|
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/core/routes.ts","../src/types.ts","../src/adapter/types.ts","../src/cache.ts","../src/core/plugin-types.ts","../src/core/types.ts","../src/core/create-type-safe-server.ts","../src/core/plugin-validation.ts","../src/core/server.ts","../src/core/websocket-routes.ts","../src/core/websocket-handlers/websocket-handlers.ts","../src/error-types.ts","../src/http-utils.ts","../src/layer-utils.ts","../src/plugins-typing.ts","../src/service.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;;;KAQY,mBAAA;KAgBA,0BAA0B;QAC9B;;KAGI,qCACA,kEAGR,gBAAgB;UACV;;;;QAEF;;KAGI,eAAA,GAAkB;AA9BlB,KAgCA,gBAAA,GAAmB,0BAhCA,CAAA,WAAA,EAAA;EAgBnB,KAAA,EAAA,WAAe;AAI3B,CAAA,EAAA,GAAY,CAAA;AACA,KAiBA,uBAAA,GAA0B,eAjB1B,CAAA,oBAAA,CAAA;AAGQ,KAgBR,wBAAA,GAA2B,0BAhBnB,CAAA,oBAAA,EAAA;EAAhB,KAAA,EAAA,oBAAA;CACM,EAAA,GAAA,CAAA;AAEF,KAmBI,iBAAA,GAAoB,eAnBxB,CAAA,aAAA,CAAA,GAAA;EAAY,OAAA,EAAA,MAAA;AAGpB,CAAA;AAEY,KAkBA,kBAAA,GAAqB,0BAlBF,CAAA,aAA0B,EAAA;EAM7C,KAAA,EAAA,aAAA;EAEA,OAAA,EAAA,MAAA;AAMZ,CAAA,EAAA,GAAY,CAAA;AAIA,KAMA,6BAAA,GACV,eAP+B,CAAA,0BAA0B,CAAA;AAM/C,KAGA,8BAAA,GAAiC,0BAF5B,CAAA,0BAAA,EAAA;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,UAAA,EAAA,MAAA,EAAA,GecwC,MAAA,CAAO,Mfd/C,CAAA,OAAA,CAAA;EAGQ;;;;EAGA,SAAA,cAAA,EAAA,GAAA,Gece,MAAA,CAAO,MfdtB,Cec6B,Wfd7B,GAAA,IAAA,CAAA;AAGpB,CAAA,CAAA;AAEA;AAMA;AAEA;AAMA;AAIA;AAMA;AAGA;AAKA;AAGA;AAIA;AAGA;AASA;AAIA;AAKA;AAKA;AAKA;AAGA;AAEA;AAKA;AAEA;AAGA;AAKY,ce1GC,kBAAA,SAA2B,uBAAA,Cf0GO;AAU/C;AAGA;AAKA;AAGA;AAKA;;;AAGI,cenGS,sBfmGT,EAAA,CAAA,WAAA,EelGW,WfkGX,GAAA,IAAA,EAAA,GejGD,KAAA,CAAM,KfiGL,CejGW,kBfiGX,CAAA;;;;;;AAMA,cezFS,wBfyFT,EezFmC,KAAA,CAAM,KfyFzC,CezF+C,kBfyF/C,CAAA"}
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/core/routes.ts","../src/types.ts","../src/adapter/types.ts","../src/cache.ts","../src/core/plugin-types.ts","../src/core/types.ts","../src/core/create-type-safe-server.ts","../src/core/plugin-validation.ts","../src/core/server.ts","../src/core/websocket-routes.ts","../src/core/websocket-handlers/websocket-handlers.ts","../src/error-types.ts","../src/http-utils.ts","../src/layer-utils.ts","../src/plugins-typing.ts","../src/service.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;;KAQY,mBAAA;KAgBA,0BAA0B;QAC9B;;KAGI,qCACA,kEAGR,gBAAgB;UACV;;;;QAEF;;AA3BI,KA8BA,eAAA,GAAkB,eA9BC,CAAA,WAAA,CAAA;AAgBnB,KAgBA,gBAAA,GAAmB,0BAfvB,CAAC,WAAA,EAAA;EAGG,KAAA,EAAA,WAAA;CACA,EAAA,GAAA,CAAA;AAGQ,KAcR,uBAAA,GAA0B,eAdlB,CAAA,oBAAA,CAAA;AAAhB,KAgBQ,wBAAA,GAA2B,0BAhBnC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Kf0FzC,Ce1F+C,kBf0F/C,CAAA"}
|
package/dist/index.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{t as e}from"./auth-DG0enyjj.mjs";import{Context as t,Effect as n,Layer as r,ManagedRuntime as i}from"effect";import{FlowProvider as a,FlowServer as o,FlowWaitUntil as s,flowServer as c}from"@uploadista/core/flow";import{createDataStoreLayer as l,flowEventEmitter as u,flowJobKvStore as d,inputFileSchema as f,uploadEventEmitter as p,uploadFileKvStore as m}from"@uploadista/core/types";import{GenerateIdLive as ee,isSupportedAlgorithm as h}from"@uploadista/core/utils";import{memoryEventBroadcaster as te}from"@uploadista/event-broadcaster-memory";import{webSocketEventEmitter as ne}from"@uploadista/event-emitter-websocket";import{MetricsService as g,NoOpMetricsServiceLive as re,NodeSdkLive as _}from"@uploadista/observability";import{UploadServer as v,uploadServer as y}from"@uploadista/core/upload";import{UploadistaError as b}from"@uploadista/core/errors";var x=class extends t.Tag(`AuthCacheService`)(){};const S=(e={})=>{let t=e.maxSize??1e4,i=e.ttl??36e5,a=new Map,o=()=>{let e=Date.now();for(let[t,n]of a.entries())e-n.timestamp>i&&a.delete(t)},s=()=>{if(a.size<=t)return;let e=null,n=1/0;for(let[t,r]of a.entries())r.timestamp<n&&(n=r.timestamp,e=t);e&&a.delete(e)};return r.succeed(x,{set:(e,t)=>n.sync(()=>{a.size%100==0&&o(),a.set(e,{authContext:t,timestamp:Date.now()}),s()}),get:e=>n.sync(()=>{let t=a.get(e);return t?Date.now()-t.timestamp>i?(a.delete(e),null):t.authContext:null}),delete:e=>n.sync(()=>{a.delete(e)}),clear:()=>n.sync(()=>{a.clear()}),size:()=>n.sync(()=>a.size)})},C=r.succeed(x,{set:()=>n.void,get:()=>n.succeed(null),delete:()=>n.void,clear:()=>n.void,size:()=>n.succeed(0)}),w=e=>e.split(`/`).filter(Boolean),T=e=>{let t=w(e);return t[t.length-1]},E=(e,t)=>e.includes(`${t}/api/`),D=(e,t)=>e.replace(`${t}/api/`,``).split(`/`).filter(Boolean),O=e=>{let t=500,n=`UNKNOWN_ERROR`,r=`Internal server error`,i;if(typeof e==`object`&&e){let a=e;if(`code`in a&&typeof a.code==`string`&&(n=a.code),`message`in a&&typeof a.message==`string`?r=a.message:`body`in a&&typeof a.body==`string`&&(r=a.body),`details`in a&&(i=a.details),`status`in a&&typeof a.status==`number`)t=a.status;else if(`code`in a)switch(a.code){case`FILE_NOT_FOUND`:case`FLOW_JOB_NOT_FOUND`:case`UPLOAD_ID_NOT_FOUND`:t=404;break;case`FLOW_JOB_ERROR`:case`VALIDATION_ERROR`:case`INVALID_METADATA`:case`INVALID_LENGTH`:case`ABORTED`:case`INVALID_TERMINATION`:t=400;break;case`INVALID_OFFSET`:t=409;break;case`ERR_SIZE_EXCEEDED`:case`ERR_MAX_SIZE_EXCEEDED`:t=413;break;case`FILE_NO_LONGER_EXISTS`:t=410;break;case`MISSING_OFFSET`:case`INVALID_CONTENT_TYPE`:t=403;break;default:t=500}`message`in a&&a.message===`Invalid JSON body`&&(t=400,n=`VALIDATION_ERROR`)}let a={status:t,code:n,message:r};return i!==void 0&&(a.details=i),a},k=e=>e[e.length-2],A=e=>({jobId:e[e.length-3],nodeId:e[e.length-1]}),j=e=>({storageId:e.pop(),flowId:e.pop()}),M=({kvStore:e,eventEmitter:t,dataStore:n,bufferedDataStore:i,generateId:a})=>{let o=r.provide(m,e),s=r.provide(n,o),c=i?r.provide(i,o):r.empty,l=r.provide(p,t),u=r.mergeAll(s,o,l,...a?[a]:[],c);return r.provide(y,u)},N=({kvStore:e,eventEmitter:t,flowProvider:n,uploadServer:i})=>{let a=r.provide(d,e),o=r.provide(u,t),s=r.mergeAll(n,o,a,i);return r.provide(c,s)};var P=class extends t.Tag(`AuthContextService`)(){};const F=e=>r.succeed(P,{getClientId:()=>n.succeed(e?.clientId??null),getMetadata:()=>n.succeed(e?.metadata??{}),hasPermission:t=>n.succeed(e?.permissions?.includes(t)??!1),getAuthContext:()=>n.succeed(e)}),ie=F(null),ae=({flowId:e})=>n.gen(function*(){let t=yield*o,r=yield*(yield*P).getClientId();return r&&(yield*n.logInfo(`[Flow] Getting flow data: ${e}, client: ${r}`)),{status:200,body:yield*t.getFlowData(e,r)}}),oe=({flowId:e,storageId:t,inputs:r})=>n.gen(function*(){let i=yield*o,a=yield*P,s=yield*x,c=yield*a.getClientId();c?(yield*n.logInfo(`[Flow] Executing flow: ${e}, storage: ${t}, client: ${c}`),yield*n.logInfo(JSON.stringify(r,null,2))):(yield*n.logInfo(`[Flow] Executing flow: ${e}, storage: ${t}`),yield*n.logInfo(`[Flow] Inputs: ${JSON.stringify(r,null,2)}`)),yield*n.logInfo(`[Flow] Calling flowServer.runFlow...`);let l=yield*i.runFlow({flowId:e,storageId:t,clientId:c,inputs:r}).pipe(n.tap(()=>n.logInfo(`[Flow] runFlow completed successfully`)),n.tapError(e=>n.logError(`[Flow] runFlow failed with error: ${e}`))),u=yield*a.getAuthContext();return u&&(yield*s.set(l.id,u)),yield*n.logInfo(`[Flow] Flow started with jobId: ${l.id}`),{status:200,body:l}}),I=({jobId:e})=>n.gen(function*(){let t=yield*o,r=yield*P,i=yield*x,a=yield*r.getClientId();if(!e)throw Error(`No job id`);a&&(yield*n.logInfo(`[Flow] Getting job status: ${e}, client: ${a}`));let s=yield*t.getJobStatus(e);return(s.status===`completed`||s.status===`failed`)&&(yield*i.delete(e),a&&(yield*n.logInfo(`[Flow] Flow ${s.status}, cleared auth cache: ${e}`))),{status:200,body:s}}),L=({jobId:e,nodeId:t,newData:r})=>n.gen(function*(){let i=yield*o,a=yield*P,s=yield*x,c=yield*a.getClientId();if(c||=(yield*s.get(e))?.clientId??null,c&&(yield*n.logInfo(`[Flow] Continuing flow: jobId=${e}, nodeId=${t}, client: ${c}`)),r===void 0)throw Error(`Missing newData`);let l=yield*i.resumeFlow({jobId:e,nodeId:t,newData:r,clientId:c});return(l.status===`completed`||l.status===`failed`)&&(yield*s.delete(e),c&&(yield*n.logInfo(`[Flow] Flow ${l.status}, cleared auth cache: ${e}`))),{status:200,body:l}}),R=({jobId:e})=>n.gen(function*(){let t=yield*o,r=yield*P,i=yield*x,a=yield*r.getClientId();a||=(yield*i.get(e))?.clientId??null,a&&(yield*n.logInfo(`[Flow] Pausing flow: jobId=${e}, client: ${a}`));let s=yield*t.pauseFlow(e,a);return a&&(yield*n.logInfo(`[Flow] Flow paused: ${e}, status: ${s.status}`)),{status:200,body:s}}),z=({jobId:e})=>n.gen(function*(){let t=yield*o,r=yield*P,i=yield*x;if(!e)throw Error(`No job id`);let a=yield*r.getClientId();a||=(yield*i.get(e))?.clientId??null,a&&(yield*n.logInfo(`[Flow] Cancelling flow: jobId=${e}, client: ${a}`));let s=yield*t.cancelFlow(e,a);return yield*i.delete(e),a&&(yield*n.logInfo(`[Flow] Flow cancelled, cleared auth cache: ${e}`)),{status:200,body:s}});var B=class extends Error{constructor(e,t=500,n=`INTERNAL_ERROR`){super(e),this.statusCode=t,this.errorCode=n,this.name=`AdapterError`}},V=class extends B{constructor(e){super(e,400,`VALIDATION_ERROR`),this.name=`ValidationError`}},H=class extends B{constructor(e){super(`${e} not found`,404,`NOT_FOUND`),this.name=`NotFoundError`}},U=class extends B{constructor(e){super(e,400,`BAD_REQUEST`),this.name=`BadRequestError`}};const W=e=>({error:e.message,code:e.errorCode,timestamp:new Date().toISOString()}),G=e=>{let t={error:e.body,code:e.code,timestamp:new Date().toISOString()};return e.details!==void 0&&(t.details=e.details),t},K=(e=`Internal server error`)=>({error:e,code:`INTERNAL_ERROR`,timestamp:new Date().toISOString()}),q=e=>n.gen(function*(){let t=yield*v,r=yield*P,i=yield*x,a=yield*r.getClientId();a&&(yield*n.logInfo(`[Upload] Creating upload for client: ${a}`));let o=yield*n.sync(()=>f.safeParse(e.data));if(!o.success)return yield*n.fail(new V(`Invalid input file schema`));if(o.data.checksumAlgorithm&&!h(o.data.checksumAlgorithm))return yield*n.fail(new V(`Unsupported checksum algorithm: ${o.data.checksumAlgorithm}. Supported algorithms: sha256`));let s=yield*t.createUpload(o.data,a),c=yield*r.getAuthContext();return c&&(yield*i.set(s.id,c)),a&&(yield*n.logInfo(`[Upload] Upload created: ${s.id} for client: ${a}`)),{status:200,body:s}}),se=({storageId:e})=>n.gen(function*(){let t=yield*v,n=yield*(yield*P).getClientId();return{status:200,body:{storageId:e,capabilities:yield*t.getCapabilities(e,n),timestamp:new Date().toISOString()}}}),ce=({uploadId:e})=>n.gen(function*(){return{status:200,body:yield*(yield*v).getUpload(e)}}),le=e=>n.gen(function*(){let t=yield*v,r=yield*P,i=yield*x,a=yield*g,{uploadId:o,data:s}=e,c=yield*r.getClientId(),l=yield*r.getMetadata();if(!c){let e=yield*i.get(o);c=e?.clientId??null,l=e?.metadata??{}}c&&(yield*n.logInfo(`[Upload] Uploading chunk for upload: ${o}, client: ${c}`));let u=yield*t.uploadChunk(o,c,s);return u.size&&u.offset>=u.size&&(yield*i.delete(o),c&&(yield*n.logInfo(`[Upload] Upload completed, cleared auth cache: ${o}`)),c&&u.size?(yield*n.logInfo(`[Upload] Recording metrics for org: ${c}, size: ${u.size}`),yield*n.forkDaemon(a.recordUpload(c,u.size,l))):yield*n.logWarning(`[Upload] Cannot record metrics - missing organizationId or size`)),c&&(yield*n.logInfo(`[Upload] Chunk uploaded for upload: ${o}, client: ${c}`)),{status:200,body:u}}),ue=e=>n.gen(function*(){switch(e.type){case`create-upload`:return yield*q(e);case`get-capabilities`:return yield*se(e);case`get-upload`:return yield*ce(e);case`upload-chunk`:return yield*le(e);case`get-flow`:return yield*ae(e);case`run-flow`:return yield*oe(e);case`job-status`:return yield*I(e);case`resume-flow`:return yield*L(e);case`pause-flow`:return yield*R(e);case`cancel-flow`:return yield*z(e);case`not-found`:return{status:404,headers:{"Content-Type":`application/json`},body:{error:`Not found`}};case`bad-request`:return{status:400,body:{error:`Bad request`,message:e.message}};case`method-not-allowed`:return{status:405,headers:{"Content-Type":`application/json`},body:{error:`Method not allowed`}};case`unsupported-content-type`:return{status:415,headers:{"Content-Type":`application/json`},body:{error:`Unsupported content type`}}}}),J=async({flows:e,dataStore:t,kvStore:o,plugins:c=[],eventEmitter:u,eventBroadcaster:d=te,withTracing:f=!1,baseUrl:p=`uploadista`,generateId:m=ee,metricsLayer:h,bufferedDataStore:g,adapter:v,authCacheConfig:y})=>{let b=u??ne(d),x=p.endsWith(`/`)?p.slice(0,-1):p,C=r.effect(a,n.succeed({getFlow:(t,n)=>e(t,n)}));if(!b)throw Error(`eventEmitter is required. Provide an event emitter layer in the configuration.`);let w=M({kvStore:o,eventEmitter:b,dataStore:await l(t),bufferedDataStore:g,generateId:m}),T=N({kvStore:o,eventEmitter:b,flowProvider:C,uploadServer:w}),E=S(y),D=h??re,k=r.mergeAll(w,T,D,E,...c),A=i.make(k);return{handler:async e=>{let t=n.gen(function*(){let t=yield*v.extractRequest(e,{baseUrl:x}),i=null;if(v.runAuthMiddleware){let t=yield*v.runAuthMiddleware(e).pipe(n.timeout(`5 seconds`),n.catchAll(()=>(console.error(`Auth middleware timeout exceeded (5 seconds)`),n.succeed({_tag:`TimeoutError`}))),n.catchAllCause(e=>(console.error(`Auth middleware error:`,e),n.succeed({_tag:`AuthError`,error:e}))));if(t&&typeof t==`object`&&`_tag`in t&&t._tag===`TimeoutError`)return yield*v.sendResponse({status:503,headers:{"Content-Type":`application/json`},body:{error:`Authentication service unavailable`,message:`Authentication took too long to respond. Please try again.`}},e);if(t&&typeof t==`object`&&`_tag`in t&&t._tag===`AuthError`)return yield*v.sendResponse({status:500,headers:{"Content-Type":`application/json`},body:{error:`Internal Server Error`,message:`An error occurred during authentication`}},e);if(t===null)return yield*v.sendResponse({status:401,headers:{"Content-Type":`application/json`},body:{error:`Unauthorized`,message:`Invalid credentials`}},e);i=t}let a=F(i),o=[];if(v.extractWaitUntil){let t=v.extractWaitUntil(e);t&&o.push(r.succeed(s,t))}let l=r.mergeAll(a,E,D,...c,...o);if(t.type===`not-found`)return yield*v.sendResponse({type:`not-found`,status:404,headers:{"Content-Type":`application/json`},body:{error:`Not found`}},e);let u=yield*ue(t).pipe(n.provide(l));return yield*v.sendResponse(u,e)}).pipe(n.catchAll(t=>{let n=O(t),r={code:n.code,message:n.message};n.details!==void 0&&(r.details=n.details);let i={status:n.status,headers:{"Content-Type":`application/json`},body:r};return v.sendResponse(i,e)}));return f?A.runPromise(t.pipe(n.provide(_))):A.runPromise(t)},websocketHandler:await A.runPromise(v.webSocketHandler({baseUrl:x})),baseUrl:x,dispose:()=>A.dispose()}};async function de(e){return J(e)}function fe(e){return e}function pe(e){return e}const Y={ImagePlugin:{packageName:`@uploadista/flow-images-sharp`,variableName:`sharpImagePlugin`},ImageAiPlugin:{packageName:`@uploadista/flow-images-replicate`,variableName:`replicateImagePlugin`},ZipPlugin:{packageName:`@uploadista/flow-utility-zipjs`,variableName:`zipPlugin`},CredentialProvider:{packageName:`@uploadista/core`,variableName:`credentialProviderLayer`}};function me(e){try{let t=e;if(t._tag)return t._tag;if(t.constructor?.name)return t.constructor.name;if(t.context?.services){let e=Array.from(t.context.services.keys());if(e.length>0){let t=e[0];if(t.key)return t.key}}return null}catch{return null}}function X(e){return e.map(e=>me(e)).filter(e=>e!==null)}function Z(e){let{plugins:t,expectedServices:n=[]}=e,r=X(t),i=n.filter(e=>!r.includes(e));return i.length===0?{success:!0}:{success:!1,required:n,provided:r,missing:i,suggestions:i.map(e=>{let t=Y[e];return t?{name:e,packageName:t.packageName,importStatement:`import { ${t.variableName} } from '${t.packageName}';`}:null}).filter(e=>e!==null)}}function Q(e){let t=[`Server initialization failed: Missing required plugins`,``,`Required: ${e.required.join(`, `)}`,`Provided: ${e.provided.length>0?e.provided.join(`, `):`(none)`}`,`Missing: ${e.missing.join(`, `)}`,``];if(e.suggestions.length>0){t.push(`Add the missing plugins to your configuration:`),t.push(``);for(let n of e.suggestions)t.push(` ${n.importStatement}`);t.push(``),t.push(` const server = await createUploadistaServer({`),t.push(` plugins: [${[...e.provided,...e.missing.map(e=>Y[e]?.variableName||e)].join(`, `)}],`),t.push(` // ...`),t.push(` });`)}else t.push(`Note: Could not determine package names for missing plugins.`),t.push(`Please ensure all required plugin layers are provided.`);return t.join(`
|
|
2
|
-
`)}function
|
|
1
|
+
import{t as e}from"./auth-DG0enyjj.mjs";import{Context as t,Effect as n,Layer as r,ManagedRuntime as i}from"effect";import{FlowProvider as a,FlowServer as o,FlowWaitUntil as s,flowServer as c,kvCircuitBreakerStoreLayer as l}from"@uploadista/core/flow";import{createDataStoreLayer as u,flowEventEmitter as d,flowJobKvStore as f,inputFileSchema as p,uploadEventEmitter as m,uploadFileKvStore as h}from"@uploadista/core/types";import{GenerateIdLive as g,isSupportedAlgorithm as _}from"@uploadista/core/utils";import{memoryEventBroadcaster as v}from"@uploadista/event-broadcaster-memory";import{webSocketEventEmitter as ee}from"@uploadista/event-emitter-websocket";import{MetricsService as y,NoOpMetricsServiceLive as te,NodeSdkLive as ne}from"@uploadista/observability";import{UploadServer as b,uploadServer as x}from"@uploadista/core/upload";import{UploadistaError as S}from"@uploadista/core/errors";var C=class extends t.Tag(`AuthCacheService`)(){};const w=(e={})=>{let t=e.maxSize??1e4,i=e.ttl??36e5,a=new Map,o=()=>{let e=Date.now();for(let[t,n]of a.entries())e-n.timestamp>i&&a.delete(t)},s=()=>{if(a.size<=t)return;let e=null,n=1/0;for(let[t,r]of a.entries())r.timestamp<n&&(n=r.timestamp,e=t);e&&a.delete(e)};return r.succeed(C,{set:(e,t)=>n.sync(()=>{a.size%100==0&&o(),a.set(e,{authContext:t,timestamp:Date.now()}),s()}),get:e=>n.sync(()=>{let t=a.get(e);return t?Date.now()-t.timestamp>i?(a.delete(e),null):t.authContext:null}),delete:e=>n.sync(()=>{a.delete(e)}),clear:()=>n.sync(()=>{a.clear()}),size:()=>n.sync(()=>a.size)})},T=r.succeed(C,{set:()=>n.void,get:()=>n.succeed(null),delete:()=>n.void,clear:()=>n.void,size:()=>n.succeed(0)}),E=e=>e.split(`/`).filter(Boolean),D=e=>{let t=E(e);return t[t.length-1]},O=(e,t)=>e.includes(`${t}/api/`),k=(e,t)=>e.replace(`${t}/api/`,``).split(`/`).filter(Boolean),A=e=>{let t=500,n=`UNKNOWN_ERROR`,r=`Internal server error`,i;if(typeof e==`object`&&e){let a=e;if(`code`in a&&typeof a.code==`string`&&(n=a.code),`message`in a&&typeof a.message==`string`?r=a.message:`body`in a&&typeof a.body==`string`&&(r=a.body),`details`in a&&(i=a.details),`status`in a&&typeof a.status==`number`)t=a.status;else if(`code`in a)switch(a.code){case`FILE_NOT_FOUND`:case`FLOW_JOB_NOT_FOUND`:case`UPLOAD_ID_NOT_FOUND`:t=404;break;case`FLOW_JOB_ERROR`:case`VALIDATION_ERROR`:case`INVALID_METADATA`:case`INVALID_LENGTH`:case`ABORTED`:case`INVALID_TERMINATION`:t=400;break;case`INVALID_OFFSET`:t=409;break;case`ERR_SIZE_EXCEEDED`:case`ERR_MAX_SIZE_EXCEEDED`:t=413;break;case`FILE_NO_LONGER_EXISTS`:t=410;break;case`MISSING_OFFSET`:case`INVALID_CONTENT_TYPE`:t=403;break;default:t=500}`message`in a&&a.message===`Invalid JSON body`&&(t=400,n=`VALIDATION_ERROR`)}let a={status:t,code:n,message:r};return i!==void 0&&(a.details=i),a},j=e=>e[e.length-2],M=e=>({jobId:e[e.length-3],nodeId:e[e.length-1]}),N=e=>({storageId:e.pop(),flowId:e.pop()}),P=({kvStore:e,eventEmitter:t,dataStore:n,bufferedDataStore:i,generateId:a})=>{let o=r.provide(h,e),s=r.provide(n,o),c=i?r.provide(i,o):r.empty,l=r.provide(m,t),u=r.mergeAll(s,o,l,...a?[a]:[],c);return r.provide(x,u)},F=({kvStore:e,eventEmitter:t,flowProvider:n,uploadServer:i})=>{let a=r.provide(f,e),o=r.provide(d,t),s=r.mergeAll(n,o,a,i);return r.provide(c,s)};var I=class extends t.Tag(`AuthContextService`)(){};const L=e=>r.succeed(I,{getClientId:()=>n.succeed(e?.clientId??null),getMetadata:()=>n.succeed(e?.metadata??{}),hasPermission:t=>n.succeed(e?.permissions?.includes(t)??!1),getAuthContext:()=>n.succeed(e)}),R=L(null),re=({flowId:e})=>n.gen(function*(){let t=yield*o,r=yield*(yield*I).getClientId();return r&&(yield*n.logInfo(`[Flow] Getting flow data: ${e}, client: ${r}`)),{status:200,body:yield*t.getFlowData(e,r)}}),ie=({flowId:e,storageId:t,inputs:r})=>n.gen(function*(){let i=yield*o,a=yield*I,s=yield*C,c=yield*a.getClientId();c?(yield*n.logInfo(`[Flow] Executing flow: ${e}, storage: ${t}, client: ${c}`),yield*n.logInfo(JSON.stringify(r,null,2))):(yield*n.logInfo(`[Flow] Executing flow: ${e}, storage: ${t}`),yield*n.logInfo(`[Flow] Inputs: ${JSON.stringify(r,null,2)}`)),yield*n.logInfo(`[Flow] Calling flowServer.runFlow...`);let l=yield*i.runFlow({flowId:e,storageId:t,clientId:c,inputs:r}).pipe(n.tap(()=>n.logInfo(`[Flow] runFlow completed successfully`)),n.tapError(e=>n.logError(`[Flow] runFlow failed with error: ${e}`))),u=yield*a.getAuthContext();return u&&(yield*s.set(l.id,u)),yield*n.logInfo(`[Flow] Flow started with jobId: ${l.id}`),{status:200,body:l}}),ae=({jobId:e})=>n.gen(function*(){let t=yield*o,r=yield*I,i=yield*C,a=yield*r.getClientId();if(!e)throw Error(`No job id`);a&&(yield*n.logInfo(`[Flow] Getting job status: ${e}, client: ${a}`));let s=yield*t.getJobStatus(e);return(s.status===`completed`||s.status===`failed`)&&(yield*i.delete(e),a&&(yield*n.logInfo(`[Flow] Flow ${s.status}, cleared auth cache: ${e}`))),{status:200,body:s}}),oe=({jobId:e,nodeId:t,newData:r})=>n.gen(function*(){let i=yield*o,a=yield*I,s=yield*C,c=yield*a.getClientId();if(c||=(yield*s.get(e))?.clientId??null,c&&(yield*n.logInfo(`[Flow] Continuing flow: jobId=${e}, nodeId=${t}, client: ${c}`)),r===void 0)throw Error(`Missing newData`);let l=yield*i.resumeFlow({jobId:e,nodeId:t,newData:r,clientId:c});return(l.status===`completed`||l.status===`failed`)&&(yield*s.delete(e),c&&(yield*n.logInfo(`[Flow] Flow ${l.status}, cleared auth cache: ${e}`))),{status:200,body:l}}),z=({jobId:e})=>n.gen(function*(){let t=yield*o,r=yield*I,i=yield*C,a=yield*r.getClientId();a||=(yield*i.get(e))?.clientId??null,a&&(yield*n.logInfo(`[Flow] Pausing flow: jobId=${e}, client: ${a}`));let s=yield*t.pauseFlow(e,a);return a&&(yield*n.logInfo(`[Flow] Flow paused: ${e}, status: ${s.status}`)),{status:200,body:s}}),B=({jobId:e})=>n.gen(function*(){let t=yield*o,r=yield*I,i=yield*C;if(!e)throw Error(`No job id`);let a=yield*r.getClientId();a||=(yield*i.get(e))?.clientId??null,a&&(yield*n.logInfo(`[Flow] Cancelling flow: jobId=${e}, client: ${a}`));let s=yield*t.cancelFlow(e,a);return yield*i.delete(e),a&&(yield*n.logInfo(`[Flow] Flow cancelled, cleared auth cache: ${e}`)),{status:200,body:s}});var V=class extends Error{constructor(e,t=500,n=`INTERNAL_ERROR`){super(e),this.statusCode=t,this.errorCode=n,this.name=`AdapterError`}},H=class extends V{constructor(e){super(e,400,`VALIDATION_ERROR`),this.name=`ValidationError`}},U=class extends V{constructor(e){super(`${e} not found`,404,`NOT_FOUND`),this.name=`NotFoundError`}},W=class extends V{constructor(e){super(e,400,`BAD_REQUEST`),this.name=`BadRequestError`}};const G=e=>({error:e.message,code:e.errorCode,timestamp:new Date().toISOString()}),K=e=>{let t={error:e.body,code:e.code,timestamp:new Date().toISOString()};return e.details!==void 0&&(t.details=e.details),t},q=(e=`Internal server error`)=>({error:e,code:`INTERNAL_ERROR`,timestamp:new Date().toISOString()}),se=e=>n.gen(function*(){let t=yield*b,r=yield*I,i=yield*C,a=yield*r.getClientId();a&&(yield*n.logInfo(`[Upload] Creating upload for client: ${a}`));let o=yield*n.sync(()=>p.safeParse(e.data));if(!o.success)return yield*n.fail(new H(`Invalid input file schema`));if(o.data.checksumAlgorithm&&!_(o.data.checksumAlgorithm))return yield*n.fail(new H(`Unsupported checksum algorithm: ${o.data.checksumAlgorithm}. Supported algorithms: sha256`));let s=yield*t.createUpload(o.data,a),c=yield*r.getAuthContext();return c&&(yield*i.set(s.id,c)),a&&(yield*n.logInfo(`[Upload] Upload created: ${s.id} for client: ${a}`)),{status:200,body:s}}),ce=({storageId:e})=>n.gen(function*(){let t=yield*b,n=yield*(yield*I).getClientId();return{status:200,body:{storageId:e,capabilities:yield*t.getCapabilities(e,n),timestamp:new Date().toISOString()}}}),le=({uploadId:e})=>n.gen(function*(){return{status:200,body:yield*(yield*b).getUpload(e)}}),ue=e=>n.gen(function*(){let t=yield*b,r=yield*I,i=yield*C,a=yield*y,{uploadId:o,data:s}=e,c=yield*r.getClientId(),l=yield*r.getMetadata();if(!c){let e=yield*i.get(o);c=e?.clientId??null,l=e?.metadata??{}}c&&(yield*n.logInfo(`[Upload] Uploading chunk for upload: ${o}, client: ${c}`));let u=yield*t.uploadChunk(o,c,s);return u.size&&u.offset>=u.size&&(yield*i.delete(o),c&&(yield*n.logInfo(`[Upload] Upload completed, cleared auth cache: ${o}`)),c&&u.size?(yield*n.logInfo(`[Upload] Recording metrics for org: ${c}, size: ${u.size}`),yield*n.forkDaemon(a.recordUpload(c,u.size,l))):yield*n.logWarning(`[Upload] Cannot record metrics - missing organizationId or size`)),c&&(yield*n.logInfo(`[Upload] Chunk uploaded for upload: ${o}, client: ${c}`)),{status:200,body:u}}),de=e=>n.gen(function*(){switch(e.type){case`create-upload`:return yield*se(e);case`get-capabilities`:return yield*ce(e);case`get-upload`:return yield*le(e);case`upload-chunk`:return yield*ue(e);case`get-flow`:return yield*re(e);case`run-flow`:return yield*ie(e);case`job-status`:return yield*ae(e);case`resume-flow`:return yield*oe(e);case`pause-flow`:return yield*z(e);case`cancel-flow`:return yield*B(e);case`not-found`:return{status:404,headers:{"Content-Type":`application/json`},body:{error:`Not found`}};case`bad-request`:return{status:400,body:{error:`Bad request`,message:e.message}};case`method-not-allowed`:return{status:405,headers:{"Content-Type":`application/json`},body:{error:`Method not allowed`}};case`unsupported-content-type`:return{status:415,headers:{"Content-Type":`application/json`},body:{error:`Unsupported content type`}}}}),J=async({flows:e,dataStore:t,kvStore:o,plugins:c=[],eventEmitter:d,eventBroadcaster:f=v,withTracing:p=!1,baseUrl:m=`uploadista`,generateId:h=g,metricsLayer:_,bufferedDataStore:y,adapter:b,authCacheConfig:x,circuitBreaker:S=!0})=>{let C=d??ee(f),T=m.endsWith(`/`)?m.slice(0,-1):m,E=r.effect(a,n.succeed({getFlow:(t,n)=>e(t,n)}));if(!C)throw Error(`eventEmitter is required. Provide an event emitter layer in the configuration.`);let D=P({kvStore:o,eventEmitter:C,dataStore:await u(t),bufferedDataStore:y,generateId:h}),O=F({kvStore:o,eventEmitter:C,flowProvider:E,uploadServer:D}),k=w(x),j=_??te,M=S?l.pipe(r.provide(o)):null,N=r.mergeAll(D,O,j,k,...c),I=M?r.merge(N,M):N,R=i.make(I);return{handler:async e=>{let t=n.gen(function*(){let t=yield*b.extractRequest(e,{baseUrl:T}),i=null;if(b.runAuthMiddleware){let t=yield*b.runAuthMiddleware(e).pipe(n.timeout(`5 seconds`),n.catchAll(()=>(console.error(`Auth middleware timeout exceeded (5 seconds)`),n.succeed({_tag:`TimeoutError`}))),n.catchAllCause(e=>(console.error(`Auth middleware error:`,e),n.succeed({_tag:`AuthError`,error:e}))));if(t&&typeof t==`object`&&`_tag`in t&&t._tag===`TimeoutError`)return yield*b.sendResponse({status:503,headers:{"Content-Type":`application/json`},body:{error:`Authentication service unavailable`,message:`Authentication took too long to respond. Please try again.`}},e);if(t&&typeof t==`object`&&`_tag`in t&&t._tag===`AuthError`)return yield*b.sendResponse({status:500,headers:{"Content-Type":`application/json`},body:{error:`Internal Server Error`,message:`An error occurred during authentication`}},e);if(t===null)return yield*b.sendResponse({status:401,headers:{"Content-Type":`application/json`},body:{error:`Unauthorized`,message:`Invalid credentials`}},e);i=t}let a=L(i),o=[];if(b.extractWaitUntil){let t=b.extractWaitUntil(e);t&&o.push(r.succeed(s,t))}let l=r.mergeAll(a,k,j,...c,...o),u=M?r.merge(l,M):l;if(t.type===`not-found`)return yield*b.sendResponse({type:`not-found`,status:404,headers:{"Content-Type":`application/json`},body:{error:`Not found`}},e);let d=yield*de(t).pipe(n.provide(u));return yield*b.sendResponse(d,e)}).pipe(n.catchAll(t=>{let n=A(t),r={code:n.code,message:n.message};n.details!==void 0&&(r.details=n.details);let i={status:n.status,headers:{"Content-Type":`application/json`},body:r};return b.sendResponse(i,e)}));return p?R.runPromise(t.pipe(n.provide(ne))):R.runPromise(t)},websocketHandler:await R.runPromise(b.webSocketHandler({baseUrl:T})),baseUrl:T,dispose:()=>R.dispose()}};async function fe(e){return J(e)}function pe(e){return e}function me(e){return e}const Y={ImagePlugin:{packageName:`@uploadista/flow-images-sharp`,variableName:`sharpImagePlugin`},ImageAiPlugin:{packageName:`@uploadista/flow-images-replicate`,variableName:`replicateImagePlugin`},ZipPlugin:{packageName:`@uploadista/flow-utility-zipjs`,variableName:`zipPlugin`},CredentialProvider:{packageName:`@uploadista/core`,variableName:`credentialProviderLayer`}};function he(e){try{let t=e;if(t._tag)return t._tag;if(t.constructor?.name)return t.constructor.name;if(t.context?.services){let e=Array.from(t.context.services.keys());if(e.length>0){let t=e[0];if(t.key)return t.key}}return null}catch{return null}}function X(e){return e.map(e=>he(e)).filter(e=>e!==null)}function Z(e){let{plugins:t,expectedServices:n=[]}=e,r=X(t),i=n.filter(e=>!r.includes(e));return i.length===0?{success:!0}:{success:!1,required:n,provided:r,missing:i,suggestions:i.map(e=>{let t=Y[e];return t?{name:e,packageName:t.packageName,importStatement:`import { ${t.variableName} } from '${t.packageName}';`}:null}).filter(e=>e!==null)}}function Q(e){let t=[`Server initialization failed: Missing required plugins`,``,`Required: ${e.required.join(`, `)}`,`Provided: ${e.provided.length>0?e.provided.join(`, `):`(none)`}`,`Missing: ${e.missing.join(`, `)}`,``];if(e.suggestions.length>0){t.push(`Add the missing plugins to your configuration:`),t.push(``);for(let n of e.suggestions)t.push(` ${n.importStatement}`);t.push(``),t.push(` const server = await createUploadistaServer({`),t.push(` plugins: [${[...e.provided,...e.missing.map(e=>Y[e]?.variableName||e)].join(`, `)}],`),t.push(` // ...`),t.push(` });`)}else t.push(`Note: Could not determine package names for missing plugins.`),t.push(`Please ensure all required plugin layers are provided.`);return t.join(`
|
|
2
|
+
`)}function ge(e){return n.sync(()=>{let t=Z(e);if(!t.success){let e=Q(t);throw Error(e)}})}function $(e){let t=Z(e);if(!t.success){let e=Q(t);throw Error(e)}}const _e=(e,t,r)=>n.gen(function*(){if(!t){yield*n.sync(()=>{r.send(JSON.stringify({type:`error`,message:`Job ID is required for flow event subscription`,code:`MISSING_JOB_ID`}))});return}yield*e.subscribeToFlowEvents(t,r)}),ve=(e,t)=>n.gen(function*(){t&&(yield*e.unsubscribeFromFlowEvents(t))}),ye=(e,t,r)=>n.gen(function*(){if(!t){yield*n.sync(()=>{r.send(JSON.stringify({type:`error`,message:`Upload ID is required for upload event subscription`,code:`MISSING_UPLOAD_ID`}))});return}yield*e.subscribeToUploadEvents(t,r)}),be=(e,t)=>n.gen(function*(){t&&(yield*e.unsubscribeFromUploadEvents(t))}),xe=(e,t,r)=>{let{connection:i,isFlowRoute:a,isUploadRoute:o,jobId:s,uploadId:c,eventId:l}=e;return n.gen(function*(){a&&(yield*_e(r,s,i)),o&&(yield*ye(t,c,i)),i.send(JSON.stringify({type:`connection`,message:`Uploadista WebSocket connected`,id:l,jobId:s,uploadId:c,timestamp:new Date().toISOString()}))}).pipe(n.catchAll(e=>n.sync(()=>{console.error(`Error subscribing to events:`,e);let t=e instanceof S?e.body:`Failed to subscribe to events`;i.send(JSON.stringify({type:`error`,message:t,code:e instanceof S?e.code:`SUBSCRIPTION_ERROR`}))})))},Se=(e,t)=>n.sync(()=>{try{JSON.parse(e).type===`ping`&&t.send(JSON.stringify({type:`pong`,timestamp:new Date().toISOString()}))}catch(e){console.error(`Error handling WebSocket message:`,e),t.send(JSON.stringify({type:`error`,message:`Invalid message format`}))}}),Ce=(e,t,r)=>{let{isFlowRoute:i,isUploadRoute:a,jobId:o,uploadId:s}=e;return n.gen(function*(){i&&(yield*ve(r,o)),a&&(yield*be(t,s))}).pipe(n.catchAll(e=>n.sync(()=>{console.error(`Error unsubscribing from events:`,e instanceof S?e.body:e)})))},we=(e,t)=>n.sync(()=>{console.error(`WebSocket error for event ${t}:`,e)});export{V as AdapterError,C as AuthCacheService,w as AuthCacheServiceLive,I as AuthContextService,L as AuthContextServiceLive,W as BadRequestError,T as NoAuthCacheServiceLive,R as NoAuthContextServiceLive,U as NotFoundError,H as ValidationError,G as createErrorResponseBody,F as createFlowServerLayer,q as createGenericErrorResponseBody,fe as createTypeSafeServer,P as createUploadServerLayer,K as createUploadistaErrorResponseBody,J as createUploadistaServer,pe as defineFlow,me as defineSimpleFlow,N as extractFlowAndStorageId,M as extractJobAndNodeId,j as extractJobIdFromStatus,X as extractServiceIdentifiers,Q as formatPluginValidationError,e as getAuthCredentials,D as getLastSegment,k as getRouteSegments,A as handleFlowError,Ce as handleWebSocketClose,we as handleWebSocketError,Se as handleWebSocketMessage,xe as handleWebSocketOpen,O as hasBasePath,E as parseUrlSegments,Z as validatePluginRequirements,ge as validatePluginRequirementsEffect,$ as validatePluginsOrThrow};
|
|
3
3
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["oldestKey: string | null","NoAuthCacheServiceLive: Layer.Layer<AuthCacheService>","details: unknown","result: {\n status: number;\n code: string;\n message: string;\n details?: unknown;\n }","uploadServer","NoAuthContextServiceLive: Layer.Layer<AuthContextService>","flowServer","statusCode: number","errorCode: string","response: {\n error: string;\n code: string;\n timestamp: string;\n details?: unknown;\n }","authContext: AuthContext | null","authResult:\n | AuthContext\n | null\n | { _tag: \"TimeoutError\" }\n | { _tag: \"AuthError\"; error: unknown }","waitUntilLayers: Layer.Layer<any, never, never>[]","errorBody: Record<string, unknown>","errorResponse: StandardResponse","KNOWN_PLUGINS: Record<\n string,\n { packageName: string; variableName: string }\n>","lines: string[]","flowServer","uploadServer","flowServer","uploadServer"],"sources":["../src/cache.ts","../src/http-utils.ts","../src/layer-utils.ts","../src/service.ts","../src/core/http-handlers/flow-http-handlers.ts","../src/error-types.ts","../src/core/http-handlers/upload-http-handlers.ts","../src/core/http-handlers/http-handlers.ts","../src/core/server.ts","../src/core/create-type-safe-server.ts","../src/core/plugin-validation.ts","../src/core/websocket-handlers/flow-websocket-handlers.ts","../src/core/websocket-handlers/upload-websocket-handlers.ts","../src/core/websocket-handlers/websocket-handlers.ts"],"sourcesContent":["import { Context, Effect, Layer } from \"effect\";\nimport type { AuthContext } from \"./types\";\n\n/**\n * Configuration options for the auth cache.\n */\nexport type AuthCacheConfig = {\n /**\n * Maximum number of entries in the cache.\n * When exceeded, oldest entries are removed (LRU eviction).\n * @default 10000\n */\n maxSize?: number;\n\n /**\n * Time-to-live for cache entries in milliseconds.\n * Entries older than this will be automatically evicted.\n * @default 3600000 (1 hour)\n */\n ttl?: number;\n};\n\n/**\n * Cache entry with auth context and timestamp.\n */\ntype CacheEntry = {\n authContext: AuthContext;\n timestamp: number;\n};\n\n/**\n * Auth Cache Service\n *\n * Provides caching of authentication contexts for upload and flow jobs.\n * This allows subsequent operations (chunk uploads, flow continuations)\n * to reuse the auth context from the initial request without re-authenticating.\n *\n * @example\n * ```typescript\n * import { Effect } from \"effect\";\n * import { AuthCacheService } from \"@uploadista/server\";\n *\n * const handler = Effect.gen(function* () {\n * const authCache = yield* AuthCacheService;\n * const authContext = { userId: \"user-123\" };\n *\n * // Cache auth for upload\n * yield* authCache.set(\"upload-abc\", authContext);\n *\n * // Retrieve cached auth later\n * const cached = yield* authCache.get(\"upload-abc\");\n * console.log(cached?.userId); // \"user-123\"\n *\n * // Clear when done\n * yield* authCache.delete(\"upload-abc\");\n * });\n * ```\n */\nexport class AuthCacheService extends Context.Tag(\"AuthCacheService\")<\n AuthCacheService,\n {\n /**\n * Store an auth context for a job ID.\n */\n readonly set: (\n jobId: string,\n authContext: AuthContext,\n ) => Effect.Effect<void>;\n\n /**\n * Retrieve a cached auth context by job ID.\n * Returns null if not found or expired.\n */\n readonly get: (jobId: string) => Effect.Effect<AuthContext | null>;\n\n /**\n * Delete a cached auth context by job ID.\n */\n readonly delete: (jobId: string) => Effect.Effect<void>;\n\n /**\n * Clear all cached auth contexts.\n */\n readonly clear: () => Effect.Effect<void>;\n\n /**\n * Get the current number of cached entries.\n */\n readonly size: () => Effect.Effect<number>;\n }\n>() {}\n\n/**\n * Creates an AuthCacheService Layer with in-memory storage.\n *\n * @param config - Optional configuration for cache behavior\n * @returns Effect Layer providing AuthCacheService\n */\nexport const AuthCacheServiceLive = (\n config: AuthCacheConfig = {},\n): Layer.Layer<AuthCacheService> => {\n const maxSize = config.maxSize ?? 10000;\n const ttl = config.ttl ?? 3600000; // 1 hour default\n\n // In-memory cache storage\n const cache = new Map<string, CacheEntry>();\n\n /**\n * Evict expired entries based on TTL.\n */\n const evictExpired = (): void => {\n const now = Date.now();\n for (const [jobId, entry] of cache.entries()) {\n if (now - entry.timestamp > ttl) {\n cache.delete(jobId);\n }\n }\n };\n\n /**\n * Enforce max size limit using LRU eviction.\n * Removes oldest entry when cache exceeds max size.\n */\n const enforceSizeLimit = (): void => {\n if (cache.size <= maxSize) return;\n\n // Find and remove oldest entry\n let oldestKey: string | null = null;\n let oldestTime = Number.POSITIVE_INFINITY;\n\n for (const [jobId, entry] of cache.entries()) {\n if (entry.timestamp < oldestTime) {\n oldestTime = entry.timestamp;\n oldestKey = jobId;\n }\n }\n\n if (oldestKey) {\n cache.delete(oldestKey);\n }\n };\n\n return Layer.succeed(AuthCacheService, {\n set: (jobId: string, authContext: AuthContext) =>\n Effect.sync(() => {\n // Evict expired entries periodically\n if (cache.size % 100 === 0) {\n evictExpired();\n }\n\n cache.set(jobId, {\n authContext,\n timestamp: Date.now(),\n });\n\n // Enforce size limit after adding\n enforceSizeLimit();\n }),\n\n get: (jobId: string) =>\n Effect.sync(() => {\n const entry = cache.get(jobId);\n if (!entry) return null;\n\n // Check if expired\n const now = Date.now();\n if (now - entry.timestamp > ttl) {\n cache.delete(jobId);\n return null;\n }\n\n return entry.authContext;\n }),\n\n delete: (jobId: string) =>\n Effect.sync(() => {\n cache.delete(jobId);\n }),\n\n clear: () =>\n Effect.sync(() => {\n cache.clear();\n }),\n\n size: () =>\n Effect.sync(() => {\n return cache.size;\n }),\n });\n};\n\n/**\n * No-op implementation of AuthCacheService.\n * Does not cache anything - all operations are no-ops.\n * Used when caching is disabled or not needed.\n */\nexport const NoAuthCacheServiceLive: Layer.Layer<AuthCacheService> =\n Layer.succeed(AuthCacheService, {\n set: () => Effect.void,\n get: () => Effect.succeed(null),\n delete: () => Effect.void,\n clear: () => Effect.void,\n size: () => Effect.succeed(0),\n });\n","/**\n * Shared HTTP utilities for server adapters\n *\n * This module provides routing and error handling utilities used across\n * Hono, Express, and Fastify adapters for request parsing and response formatting.\n */\n\n/**\n * Parses URL segments from a pathname, filtering out empty segments.\n * Useful for extracting route components from request paths.\n *\n * @param pathname - The URL pathname (e.g., \"/uploadista/api/upload/abc123\")\n * @returns Array of non-empty path segments\n *\n * @example\n * ```typescript\n * const segments = parseUrlSegments(\"/uploadista/api/upload/abc123\");\n * // => [\"uploadista\", \"api\", \"upload\", \"abc123\"]\n * ```\n */\nexport const parseUrlSegments = (pathname: string): string[] => {\n return pathname.split(\"/\").filter(Boolean);\n};\n\n/**\n * Extracts the last segment from a URL pathname.\n *\n * @param pathname - The URL pathname to parse\n * @returns The last non-empty segment, or undefined if none exists\n *\n * @example\n * ```typescript\n * const id = getLastSegment(\"/uploadista/api/upload/abc123\");\n * // => \"abc123\"\n * ```\n */\nexport const getLastSegment = (pathname: string): string | undefined => {\n const segments = parseUrlSegments(pathname);\n return segments[segments.length - 1];\n};\n\n/**\n * Checks if a pathname includes a specific base path and API prefix.\n * Used to determine if a request should be handled by the Uploadista adapter.\n *\n * @param pathname - The request pathname\n * @param basePath - The base path configured for the adapter (e.g., \"uploadista\")\n * @returns true if the path includes `{basePath}/api/`\n *\n * @example\n * ```typescript\n * const isUploadistaPath = hasBasePath(\"/uploadista/api/upload\", \"uploadista\");\n * // => true\n * ```\n */\nexport const hasBasePath = (pathname: string, basePath: string): boolean => {\n return pathname.includes(`${basePath}/api/`);\n};\n\n/**\n * Removes the base path prefix and returns clean route segments.\n * Transforms \"/uploadista/api/upload/abc123\" → [\"upload\", \"abc123\"]\n *\n * @param pathname - The full request pathname\n * @param basePath - The base path to remove (e.g., \"uploadista\")\n * @returns Array of route segments without base path prefix\n *\n * @example\n * ```typescript\n * const route = getRouteSegments(\"/uploadista/api/upload/abc123\", \"uploadista\");\n * // => [\"upload\", \"abc123\"]\n * ```\n */\nexport const getRouteSegments = (\n pathname: string,\n basePath: string,\n): string[] => {\n return pathname.replace(`${basePath}/api/`, \"\").split(\"/\").filter(Boolean);\n};\n\n/**\n * Standard error handler for flow and job operations.\n * Maps application errors to appropriate HTTP status codes and error formats.\n *\n * Supports errors with `code`, `message`, `status`, and `details` properties.\n * Maps error codes to HTTP status codes (e.g., NOT_FOUND → 404, VALIDATION_ERROR → 400).\n *\n * @param error - The error object to handle (can be any type)\n * @returns Standardized error response with status, code, message, and optional details\n *\n * @example\n * ```typescript\n * import { handleFlowError } from \"@uploadista/server\";\n *\n * const response = handleFlowError({\n * code: \"FLOW_JOB_NOT_FOUND\",\n * message: \"Job not found\",\n * });\n * // => { status: 404, code: \"FLOW_JOB_NOT_FOUND\", message: \"Job not found\" }\n * ```\n */\nexport const handleFlowError = (\n error: unknown,\n): { status: number; code: string; message: string; details?: unknown } => {\n let status = 500;\n let code = \"UNKNOWN_ERROR\";\n let message = \"Internal server error\";\n let details: unknown;\n\n if (typeof error === \"object\" && error !== null) {\n const errorObj = error as Record<string, unknown>;\n\n // Extract error code\n if (\"code\" in errorObj && typeof errorObj.code === \"string\") {\n code = errorObj.code;\n }\n\n // Extract message\n if (\"message\" in errorObj && typeof errorObj.message === \"string\") {\n message = errorObj.message;\n } else if (\"body\" in errorObj && typeof errorObj.body === \"string\") {\n // Support UploadistaError's body property\n message = errorObj.body;\n }\n\n // Extract details if present\n if (\"details\" in errorObj) {\n details = errorObj.details;\n }\n\n // Map error codes to HTTP status codes\n if (\"status\" in errorObj && typeof errorObj.status === \"number\") {\n status = errorObj.status;\n } else if (\"code\" in errorObj) {\n // Fallback: derive status from common error codes\n switch (errorObj.code) {\n case \"FILE_NOT_FOUND\":\n case \"FLOW_JOB_NOT_FOUND\":\n case \"UPLOAD_ID_NOT_FOUND\":\n status = 404;\n break;\n case \"FLOW_JOB_ERROR\":\n case \"VALIDATION_ERROR\":\n case \"INVALID_METADATA\":\n case \"INVALID_LENGTH\":\n case \"ABORTED\":\n case \"INVALID_TERMINATION\":\n status = 400;\n break;\n case \"INVALID_OFFSET\":\n status = 409;\n break;\n case \"ERR_SIZE_EXCEEDED\":\n case \"ERR_MAX_SIZE_EXCEEDED\":\n status = 413;\n break;\n case \"FILE_NO_LONGER_EXISTS\":\n status = 410;\n break;\n case \"MISSING_OFFSET\":\n case \"INVALID_CONTENT_TYPE\":\n status = 403;\n break;\n default:\n status = 500;\n }\n }\n\n // Special handling for specific error messages\n if (\"message\" in errorObj && errorObj.message === \"Invalid JSON body\") {\n status = 400;\n code = \"VALIDATION_ERROR\";\n }\n }\n\n const result: {\n status: number;\n code: string;\n message: string;\n details?: unknown;\n } = {\n status,\n code,\n message,\n };\n\n if (details !== undefined) {\n result.details = details;\n }\n\n return result;\n};\n\n/**\n * Extracts job ID from URL segments for job status endpoint.\n * Expected URL format: `/uploadista/api/jobs/:jobId/status`\n *\n * @param urlSegments - Parsed URL segments (without base path)\n * @returns The job ID if found, or undefined\n *\n * @example\n * ```typescript\n * const jobId = extractJobIdFromStatus([\"jobs\", \"job-123\", \"status\"]);\n * // => \"job-123\"\n * ```\n */\nexport const extractJobIdFromStatus = (\n urlSegments: string[],\n): string | undefined => {\n return urlSegments[urlSegments.length - 2];\n};\n\n/**\n * Extracts job ID and node ID from URL segments for resume flow endpoint.\n * Expected URL format: `/uploadista/api/jobs/:jobId/resume/:nodeId`\n *\n * @param urlSegments - Parsed URL segments (without base path)\n * @returns Object with extracted jobId and nodeId (either can be undefined if not found)\n *\n * @example\n * ```typescript\n * const { jobId, nodeId } = extractJobAndNodeId([\n * \"jobs\",\n * \"job-123\",\n * \"resume\",\n * \"node-456\",\n * ]);\n * // => { jobId: \"job-123\", nodeId: \"node-456\" }\n * ```\n */\nexport const extractJobAndNodeId = (\n urlSegments: string[],\n): { jobId: string | undefined; nodeId: string | undefined } => {\n return {\n jobId: urlSegments[urlSegments.length - 3],\n nodeId: urlSegments[urlSegments.length - 1],\n };\n};\n\n/**\n * Extracts flow ID and storage ID from URL segments.\n * Expected URL format: `/uploadista/api/flow/:flowId/:storageId`\n *\n * Mutates the input array (removes last 2 elements).\n *\n * @param urlSegments - Parsed URL segments (will be mutated)\n * @returns Object with extracted flowId and storageId\n *\n * @example\n * ```typescript\n * const segments = [\"flow\", \"flow-123\", \"storage-456\"];\n * const { flowId, storageId } = extractFlowAndStorageId(segments);\n * // => { flowId: \"flow-123\", storageId: \"storage-456\" }\n * // segments is now [\"flow\"]\n * ```\n */\nexport const extractFlowAndStorageId = (\n urlSegments: string[],\n): { flowId: string | undefined; storageId: string | undefined } => {\n return {\n storageId: urlSegments.pop(),\n flowId: urlSegments.pop(),\n };\n};\n","import type { FlowProvider } from \"@uploadista/core/flow\";\nimport { flowServer } from \"@uploadista/core/flow\";\nimport {\n type BaseEventEmitterService,\n type BaseKvStoreService,\n flowEventEmitter,\n flowJobKvStore,\n type UploadFileDataStore,\n type UploadFileDataStores,\n type UploadFileKVStore,\n uploadEventEmitter,\n uploadFileKvStore,\n} from \"@uploadista/core/types\";\nimport { type UploadServer, uploadServer } from \"@uploadista/core/upload\";\nimport type { GenerateId } from \"@uploadista/core/utils\";\nimport { Layer } from \"effect\";\n\n/**\n * Configuration for creating upload server layers.\n * Specifies all dependencies needed by the upload server Effect Layer.\n *\n * @property kvStore - Key-value store for upload metadata\n * @property eventEmitter - Event emitter for upload progress events\n * @property dataStore - File data storage implementation\n * @property bufferedDataStore - Optional buffered storage for performance optimization\n * @property generateId - Optional custom ID generator (uses default if omitted)\n *\n * @example\n * ```typescript\n * import { createUploadServerLayer } from \"@uploadista/server\";\n *\n * const uploadLayerConfig: UploadServerLayerConfig = {\n * kvStore: redisKvStore,\n * eventEmitter: webSocketEventEmitter,\n * dataStore: s3DataStore,\n * };\n * ```\n */\nexport interface UploadServerLayerConfig {\n kvStore: Layer.Layer<BaseKvStoreService>;\n eventEmitter: Layer.Layer<BaseEventEmitterService>;\n dataStore: Layer.Layer<UploadFileDataStores, never, UploadFileKVStore>;\n bufferedDataStore?: Layer.Layer<\n UploadFileDataStore,\n never,\n UploadFileKVStore\n >;\n generateId?: Layer.Layer<GenerateId>;\n}\n\n/**\n * Configuration for creating flow server layers.\n * Specifies all dependencies needed by the flow processing server.\n *\n * @property kvStore - Key-value store for flow job metadata\n * @property eventEmitter - Event emitter for flow progress events\n * @property flowProvider - Factory function for creating flows\n * @property uploadServer - Upload server layer (used by flows for uploads)\n *\n * @example\n * ```typescript\n * import { createFlowServerLayer } from \"@uploadista/server\";\n *\n * const flowLayerConfig: FlowServerLayerConfig = {\n * kvStore: redisKvStore,\n * eventEmitter: webSocketEventEmitter,\n * flowProvider: createFlowsEffect,\n * uploadServer: uploadServerLayer,\n * };\n * ```\n */\nexport interface FlowServerLayerConfig {\n kvStore: Layer.Layer<BaseKvStoreService>;\n eventEmitter: Layer.Layer<BaseEventEmitterService>;\n flowProvider: Layer.Layer<FlowProvider>;\n uploadServer: Layer.Layer<UploadServer>;\n}\n\n/**\n * Creates the upload server layer with all dependencies composed.\n * This layer handles file uploads with chunked transfer, resumption, and metadata tracking.\n *\n * The created layer includes:\n * - Upload KV store (metadata tracking)\n * - Data store (file storage)\n * - Event emitter (progress notifications)\n * - Optional buffered data store (performance optimization)\n * - Optional custom ID generator\n *\n * @param config - Upload server layer configuration\n * @returns Effect Layer providing UploadServer\n *\n * @example\n * ```typescript\n * import { createUploadServerLayer } from \"@uploadista/server\";\n * import { Layer } from \"effect\";\n *\n * const uploadServerLayer = createUploadServerLayer({\n * kvStore: redisKvStore,\n * eventEmitter: webSocketEventEmitter,\n * dataStore: s3DataStore,\n * });\n *\n * // Use in application\n * const app = Layer.provide(appLogic, uploadServerLayer);\n * ```\n */\nexport const createUploadServerLayer = ({\n kvStore,\n eventEmitter,\n dataStore,\n bufferedDataStore,\n generateId,\n}: UploadServerLayerConfig) => {\n // Set up upload server dependencies\n const uploadFileKVStoreLayer = Layer.provide(uploadFileKvStore, kvStore);\n const uploadDataStoreLayer = Layer.provide(dataStore, uploadFileKVStoreLayer);\n const uploadBufferedDataStoreLayer = bufferedDataStore\n ? Layer.provide(bufferedDataStore, uploadFileKVStoreLayer)\n : Layer.empty;\n const uploadEventEmitterLayer = Layer.provide(\n uploadEventEmitter,\n eventEmitter,\n );\n\n const uploadServerLayers = Layer.mergeAll(\n uploadDataStoreLayer,\n uploadFileKVStoreLayer,\n uploadEventEmitterLayer,\n ...(generateId ? [generateId] : []),\n uploadBufferedDataStoreLayer,\n );\n\n return Layer.provide(uploadServer, uploadServerLayers);\n};\n\n/**\n * Creates the flow server layer with all dependencies composed.\n * This layer handles file processing workflows with multi-stage pipelines.\n *\n * The created layer includes:\n * - Flow job KV store (job metadata and state)\n * - Event emitter (progress notifications)\n * - Flow provider (flow definitions)\n * - Upload server (for uploads within flows)\n *\n * @param config - Flow server layer configuration\n * @returns Effect Layer providing FlowServer\n *\n * @example\n * ```typescript\n * import { createFlowServerLayer } from \"@uploadista/server\";\n * import { Layer } from \"effect\";\n *\n * const flowServerLayer = createFlowServerLayer({\n * kvStore: redisKvStore,\n * eventEmitter: webSocketEventEmitter,\n * flowProvider: createFlowsEffect,\n * uploadServer: uploadServerLayer,\n * });\n *\n * // Use in application\n * const app = Layer.provide(appLogic, flowServerLayer);\n * ```\n */\nexport const createFlowServerLayer = ({\n kvStore,\n eventEmitter,\n flowProvider,\n uploadServer,\n}: FlowServerLayerConfig) => {\n // Set up flow server dependencies\n const flowJobKVStoreLayer = Layer.provide(flowJobKvStore, kvStore);\n const flowEventEmitterLayer = Layer.provide(flowEventEmitter, eventEmitter);\n\n const flowServerLayers = Layer.mergeAll(\n flowProvider,\n flowEventEmitterLayer,\n flowJobKVStoreLayer,\n uploadServer,\n );\n\n return Layer.provide(flowServer, flowServerLayers);\n};\n","import { Context, Effect, Layer } from \"effect\";\nimport type { AuthContext } from \"./types\";\n\n/**\n * Authentication Context Service\n *\n * Provides access to the current authentication context throughout\n * the upload and flow processing pipeline. The service is provided\n * via Effect Layer and can be accessed using Effect.service().\n *\n * @example\n * ```typescript\n * import { Effect } from \"effect\";\n * import { AuthContextService } from \"@uploadista/server\";\n *\n * const uploadHandler = Effect.gen(function* () {\n * const authService = yield* AuthContextService;\n * const clientId = yield* authService.getClientId();\n * if (clientId) {\n * console.log(`Processing upload for client: ${clientId}`);\n * }\n * });\n * ```\n */\nexport class AuthContextService extends Context.Tag(\"AuthContextService\")<\n AuthContextService,\n {\n /**\n * Get the current client ID from auth context.\n * Returns null if no authentication context is available.\n */\n readonly getClientId: () => Effect.Effect<string | null>;\n\n /**\n * Get the current auth metadata.\n * Returns empty object if no authentication context or no metadata.\n */\n readonly getMetadata: () => Effect.Effect<Record<string, unknown>>;\n\n /**\n * Check if the current client has a specific permission.\n * Returns false if no authentication context or permission not found.\n */\n readonly hasPermission: (permission: string) => Effect.Effect<boolean>;\n\n /**\n * Get the full authentication context if available.\n * Returns null if no authentication context is available.\n */\n readonly getAuthContext: () => Effect.Effect<AuthContext | null>;\n }\n>() {}\n\n/**\n * Creates an AuthContextService Layer from an AuthContext.\n * This is typically called by adapters after successful authentication.\n *\n * @param authContext - The authentication context from middleware\n * @returns Effect Layer providing AuthContextService\n */\nexport const AuthContextServiceLive = (\n authContext: AuthContext | null,\n): Layer.Layer<AuthContextService> =>\n Layer.succeed(AuthContextService, {\n getClientId: () => Effect.succeed(authContext?.clientId ?? null),\n getMetadata: () => Effect.succeed(authContext?.metadata ?? {}),\n hasPermission: (permission: string) =>\n Effect.succeed(authContext?.permissions?.includes(permission) ?? false),\n getAuthContext: () => Effect.succeed(authContext),\n });\n\n/**\n * No-auth implementation of AuthContextService.\n * Returns null/empty values for all operations.\n * Used when no authentication middleware is configured (backward compatibility).\n */\nexport const NoAuthContextServiceLive: Layer.Layer<AuthContextService> =\n AuthContextServiceLive(null);\n","import { FlowServer } from \"@uploadista/core/flow\";\nimport { Effect } from \"effect\";\nimport { AuthCacheService } from \"../../cache\";\nimport { AuthContextService } from \"../../service\";\nimport type {\n CancelFlowRequest,\n CancelFlowResponse,\n GetFlowRequest,\n GetFlowResponse,\n GetJobStatusRequest,\n GetJobStatusResponse,\n PauseFlowRequest,\n PauseFlowResponse,\n ResumeFlowRequest,\n ResumeFlowResponse,\n RunFlowRequest,\n RunFlowResponse,\n} from \"../routes\";\n\nexport const handleGetFlow = ({ flowId }: GetFlowRequest) => {\n return Effect.gen(function* () {\n const flowServer = yield* FlowServer;\n // Access auth context if available\n const authService = yield* AuthContextService;\n const clientId = yield* authService.getClientId();\n\n if (clientId) {\n yield* Effect.logInfo(\n `[Flow] Getting flow data: ${flowId}, client: ${clientId}`,\n );\n }\n\n const flowData = yield* flowServer.getFlowData(flowId, clientId);\n\n return {\n status: 200,\n body: flowData,\n } as GetFlowResponse;\n });\n};\n\nexport const handleRunFlow = <TRequirements>({\n flowId,\n storageId,\n inputs,\n}: RunFlowRequest) => {\n return Effect.gen(function* () {\n const flowServer = yield* FlowServer;\n // Access auth context if available\n const authService = yield* AuthContextService;\n const authCache = yield* AuthCacheService;\n const clientId = yield* authService.getClientId();\n\n if (clientId) {\n yield* Effect.logInfo(\n `[Flow] Executing flow: ${flowId}, storage: ${storageId}, client: ${clientId}`,\n );\n yield* Effect.logInfo(JSON.stringify(inputs, null, 2));\n } else {\n yield* Effect.logInfo(\n `[Flow] Executing flow: ${flowId}, storage: ${storageId}`,\n );\n yield* Effect.logInfo(\n `[Flow] Inputs: ${JSON.stringify(inputs, null, 2)}`,\n );\n }\n\n // Run flow returns immediately with jobId\n yield* Effect.logInfo(`[Flow] Calling flowServer.runFlow...`);\n const result = yield* flowServer\n .runFlow<TRequirements>({\n flowId,\n storageId,\n clientId,\n inputs,\n })\n .pipe(\n Effect.tap(() =>\n Effect.logInfo(`[Flow] runFlow completed successfully`),\n ),\n Effect.tapError((error) =>\n Effect.logError(`[Flow] runFlow failed with error: ${error}`),\n ),\n );\n\n // Cache auth context for subsequent flow operations (continue, status)\n const authContext = yield* authService.getAuthContext();\n if (authContext) {\n yield* authCache.set(result.id, authContext);\n }\n\n yield* Effect.logInfo(`[Flow] Flow started with jobId: ${result.id}`);\n\n return {\n status: 200,\n body: result,\n } as RunFlowResponse;\n });\n};\n\nexport const handleJobStatus = ({ jobId }: GetJobStatusRequest) => {\n return Effect.gen(function* () {\n const flowServer = yield* FlowServer;\n // Access auth context if available\n const authService = yield* AuthContextService;\n const authCache = yield* AuthCacheService;\n const clientId = yield* authService.getClientId();\n\n if (!jobId) {\n throw new Error(\"No job id\");\n }\n\n if (clientId) {\n yield* Effect.logInfo(\n `[Flow] Getting job status: ${jobId}, client: ${clientId}`,\n );\n }\n\n const result = yield* flowServer.getJobStatus(jobId);\n\n // Clear cache if flow is completed or failed\n if (result.status === \"completed\" || result.status === \"failed\") {\n yield* authCache.delete(jobId);\n if (clientId) {\n yield* Effect.logInfo(\n `[Flow] Flow ${result.status}, cleared auth cache: ${jobId}`,\n );\n }\n }\n\n return {\n status: 200,\n body: result,\n } as GetJobStatusResponse;\n });\n};\n\nexport const handleResumeFlow = <TRequirements>({\n jobId,\n nodeId,\n newData,\n}: ResumeFlowRequest) => {\n return Effect.gen(function* () {\n const flowServer = yield* FlowServer;\n // Try to get auth from current request or cached auth\n const authService = yield* AuthContextService;\n const authCache = yield* AuthCacheService;\n\n // Try current auth first, fallback to cached auth\n let clientId = yield* authService.getClientId();\n if (!clientId) {\n const cachedAuth = yield* authCache.get(jobId);\n clientId = cachedAuth?.clientId ?? null;\n }\n\n if (clientId) {\n yield* Effect.logInfo(\n `[Flow] Continuing flow: jobId=${jobId}, nodeId=${nodeId}, client: ${clientId}`,\n );\n }\n\n if (newData === undefined) {\n throw new Error(\"Missing newData\");\n }\n\n const result = yield* flowServer.resumeFlow<TRequirements>({\n jobId,\n nodeId,\n newData,\n clientId,\n });\n\n // Clear cache if flow is completed or failed\n if (result.status === \"completed\" || result.status === \"failed\") {\n yield* authCache.delete(jobId);\n if (clientId) {\n yield* Effect.logInfo(\n `[Flow] Flow ${result.status}, cleared auth cache: ${jobId}`,\n );\n }\n }\n\n return {\n status: 200,\n body: result,\n } as ResumeFlowResponse;\n });\n};\nexport const handlePauseFlow = ({ jobId }: PauseFlowRequest) => {\n return Effect.gen(function* () {\n const flowServer = yield* FlowServer;\n // Try to get auth from current request or cached auth\n const authService = yield* AuthContextService;\n const authCache = yield* AuthCacheService;\n\n // Try current auth first, fallback to cached auth\n let clientId = yield* authService.getClientId();\n if (!clientId) {\n const cachedAuth = yield* authCache.get(jobId);\n clientId = cachedAuth?.clientId ?? null;\n }\n\n if (clientId) {\n yield* Effect.logInfo(\n `[Flow] Pausing flow: jobId=${jobId}, client: ${clientId}`,\n );\n }\n\n const result = yield* flowServer.pauseFlow(jobId, clientId);\n\n if (clientId) {\n yield* Effect.logInfo(\n `[Flow] Flow paused: ${jobId}, status: ${result.status}`,\n );\n }\n\n return {\n status: 200,\n body: result,\n } as PauseFlowResponse;\n });\n};\n\nexport const handleCancelFlow = ({ jobId }: CancelFlowRequest) => {\n return Effect.gen(function* () {\n const flowServer = yield* FlowServer;\n // Try to get auth from current request or cached auth\n const authService = yield* AuthContextService;\n const authCache = yield* AuthCacheService;\n\n if (!jobId) {\n throw new Error(\"No job id\");\n }\n\n // Try current auth first, fallback to cached auth\n let clientId = yield* authService.getClientId();\n if (!clientId) {\n const cachedAuth = yield* authCache.get(jobId);\n clientId = cachedAuth?.clientId ?? null;\n }\n\n if (clientId) {\n yield* Effect.logInfo(\n `[Flow] Cancelling flow: jobId=${jobId}, client: ${clientId}`,\n );\n }\n\n const result = yield* flowServer.cancelFlow(jobId, clientId);\n\n // Clear cache since flow is cancelled\n yield* authCache.delete(jobId);\n if (clientId) {\n yield* Effect.logInfo(\n `[Flow] Flow cancelled, cleared auth cache: ${jobId}`,\n );\n }\n\n return {\n status: 200,\n body: result,\n } as CancelFlowResponse;\n });\n};\n","import type { UploadistaError } from \"@uploadista/core/errors\";\n\n/**\n * Base adapter error class for HTTP adapters.\n * All adapter-specific errors should extend this class or one of its subclasses.\n *\n * @example\n * ```typescript\n * throw new AdapterError(\"Something went wrong\", 500, \"INTERNAL_ERROR\");\n * ```\n */\nexport class AdapterError extends Error {\n constructor(\n message: string,\n public readonly statusCode: number = 500,\n public readonly errorCode: string = \"INTERNAL_ERROR\",\n ) {\n super(message);\n this.name = \"AdapterError\";\n }\n}\n\n/**\n * Validation error - indicates invalid request data or parameters.\n * Returns HTTP 400 Bad Request status.\n *\n * @example\n * ```typescript\n * if (!isValidUploadId(id)) {\n * throw new ValidationError(\"Invalid upload ID format\");\n * }\n * ```\n */\nexport class ValidationError extends AdapterError {\n constructor(message: string) {\n super(message, 400, \"VALIDATION_ERROR\");\n this.name = \"ValidationError\";\n }\n}\n\n/**\n * Not found error - indicates a requested resource does not exist.\n * Returns HTTP 404 Not Found status.\n *\n * @example\n * ```typescript\n * if (!upload) {\n * throw new NotFoundError(\"Upload\");\n * }\n * ```\n */\nexport class NotFoundError extends AdapterError {\n constructor(resource: string) {\n super(`${resource} not found`, 404, \"NOT_FOUND\");\n this.name = \"NotFoundError\";\n }\n}\n\n/**\n * Bad request error - indicates a malformed request.\n * Returns HTTP 400 Bad Request status.\n * Similar to ValidationError but for request structure issues.\n *\n * @example\n * ```typescript\n * try {\n * const data = JSON.parse(body);\n * } catch {\n * throw new BadRequestError(\"Invalid JSON body\");\n * }\n * ```\n */\nexport class BadRequestError extends AdapterError {\n constructor(message: string) {\n super(message, 400, \"BAD_REQUEST\");\n this.name = \"BadRequestError\";\n }\n}\n\n/**\n * Creates a standardized error response object for AdapterError.\n * Includes error message, error code, and ISO timestamp.\n *\n * @param error - The AdapterError to format\n * @returns Standardized error response body\n *\n * @example\n * ```typescript\n * import { createErrorResponseBody } from \"@uploadista/server\";\n *\n * try {\n * // ... operation\n * } catch (err) {\n * const errorResponse = createErrorResponseBody(err);\n * res.status(err.statusCode).json(errorResponse);\n * }\n * ```\n */\nexport const createErrorResponseBody = (error: AdapterError) => ({\n error: error.message,\n code: error.errorCode,\n timestamp: new Date().toISOString(),\n});\n\n/**\n * Creates a standardized error response body from UploadistaError.\n * Formats core library errors for HTTP responses with optional details.\n *\n * @param error - The UploadistaError to format\n * @returns Standardized error response body with error, code, timestamp, and optional details\n *\n * @example\n * ```typescript\n * import { createUploadistaErrorResponseBody } from \"@uploadista/server\";\n *\n * try {\n * const result = yield* uploadServer.handleUpload(input);\n * } catch (err) {\n * if (err instanceof UploadistaError) {\n * const errorResponse = createUploadistaErrorResponseBody(err);\n * res.status(400).json(errorResponse);\n * }\n * }\n * ```\n */\nexport const createUploadistaErrorResponseBody = (error: UploadistaError) => {\n const response: {\n error: string;\n code: string;\n timestamp: string;\n details?: unknown;\n } = {\n error: error.body,\n code: error.code,\n timestamp: new Date().toISOString(),\n };\n\n if (error.details !== undefined) {\n response.details = error.details;\n }\n\n return response;\n};\n\n/**\n * Creates a generic error response body for unknown/unexpected errors.\n * Used as a fallback when error type cannot be determined.\n *\n * @param message - Error message to include in response (defaults to \"Internal server error\")\n * @returns Standardized error response body with generic INTERNAL_ERROR code\n *\n * @example\n * ```typescript\n * import { createGenericErrorResponseBody } from \"@uploadista/server\";\n *\n * try {\n * // ... operation\n * } catch (err) {\n * const errorResponse = createGenericErrorResponseBody(\n * err instanceof Error ? err.message : \"Unknown error\"\n * );\n * res.status(500).json(errorResponse);\n * }\n * ```\n */\nexport const createGenericErrorResponseBody = (\n message = \"Internal server error\",\n) => ({\n error: message,\n code: \"INTERNAL_ERROR\",\n timestamp: new Date().toISOString(),\n});\n","import { inputFileSchema } from \"@uploadista/core/types\";\nimport { UploadServer } from \"@uploadista/core/upload\";\nimport { isSupportedAlgorithm } from \"@uploadista/core/utils\";\nimport { MetricsService } from \"@uploadista/observability\";\nimport { Effect } from \"effect\";\nimport { AuthCacheService } from \"../../cache\";\nimport { ValidationError } from \"../../error-types\";\nimport { AuthContextService } from \"../../service\";\nimport type {\n CreateUploadRequest,\n CreateUploadResponse,\n GetCapabilitiesRequest,\n GetCapabilitiesResponse,\n GetUploadRequest,\n GetUploadResponse,\n UploadChunkRequest,\n UploadChunkResponse,\n} from \"../routes\";\n\nexport const handleCreateUpload = (req: CreateUploadRequest) =>\n Effect.gen(function* () {\n const server = yield* UploadServer;\n // Access auth context if available\n const authService = yield* AuthContextService;\n const authCache = yield* AuthCacheService;\n const clientId = yield* authService.getClientId();\n\n if (clientId) {\n yield* Effect.logInfo(`[Upload] Creating upload for client: ${clientId}`);\n }\n\n const parsedInputFile = yield* Effect.sync(() =>\n inputFileSchema.safeParse(req.data),\n );\n\n if (!parsedInputFile.success) {\n return yield* Effect.fail(\n new ValidationError(\"Invalid input file schema\"),\n );\n }\n\n // Validate checksum algorithm if provided\n if (\n parsedInputFile.data.checksumAlgorithm &&\n !isSupportedAlgorithm(parsedInputFile.data.checksumAlgorithm)\n ) {\n return yield* Effect.fail(\n new ValidationError(\n `Unsupported checksum algorithm: ${parsedInputFile.data.checksumAlgorithm}. Supported algorithms: sha256`,\n ),\n );\n }\n\n const fileCreated = yield* server.createUpload(\n parsedInputFile.data,\n clientId,\n );\n\n // Cache auth context for subsequent chunk uploads\n const authContext = yield* authService.getAuthContext();\n if (authContext) {\n yield* authCache.set(fileCreated.id, authContext);\n }\n\n if (clientId) {\n yield* Effect.logInfo(\n `[Upload] Upload created: ${fileCreated.id} for client: ${clientId}`,\n );\n }\n\n return {\n status: 200,\n body: fileCreated,\n } as CreateUploadResponse;\n });\n\nexport const handleGetCapabilities = ({ storageId }: GetCapabilitiesRequest) =>\n Effect.gen(function* () {\n const server = yield* UploadServer;\n const authService = yield* AuthContextService;\n const clientId = yield* authService.getClientId();\n\n const capabilities = yield* server.getCapabilities(storageId, clientId);\n\n return {\n status: 200,\n body: {\n storageId,\n capabilities,\n timestamp: new Date().toISOString(),\n },\n } as GetCapabilitiesResponse;\n });\n\nexport const handleGetUpload = ({ uploadId }: GetUploadRequest) =>\n Effect.gen(function* () {\n const server = yield* UploadServer;\n const fileResult = yield* server.getUpload(uploadId);\n\n return {\n status: 200,\n body: fileResult,\n } as GetUploadResponse;\n });\n\nexport const handleUploadChunk = (req: UploadChunkRequest) =>\n Effect.gen(function* () {\n const server = yield* UploadServer;\n // Try to get auth from current request or cached auth\n const authService = yield* AuthContextService;\n const authCache = yield* AuthCacheService;\n const metricsService = yield* MetricsService;\n\n const { uploadId, data } = req;\n\n // Try current auth first, fallback to cached auth\n let clientId = yield* authService.getClientId();\n let authMetadata = yield* authService.getMetadata();\n if (!clientId) {\n const cachedAuth = yield* authCache.get(uploadId);\n clientId = cachedAuth?.clientId ?? null;\n authMetadata = cachedAuth?.metadata ?? {};\n }\n\n if (clientId) {\n yield* Effect.logInfo(\n `[Upload] Uploading chunk for upload: ${uploadId}, client: ${clientId}`,\n );\n }\n\n const fileResult = yield* server.uploadChunk(uploadId, clientId, data);\n\n // Clear cache and record metrics if upload is complete\n if (fileResult.size && fileResult.offset >= fileResult.size) {\n yield* authCache.delete(uploadId);\n if (clientId) {\n yield* Effect.logInfo(\n `[Upload] Upload completed, cleared auth cache: ${uploadId}`,\n );\n }\n\n // Record upload metrics if we have organization ID\n\n if (clientId && fileResult.size) {\n yield* Effect.logInfo(\n `[Upload] Recording metrics for org: ${clientId}, size: ${fileResult.size}`,\n );\n yield* Effect.forkDaemon(\n metricsService.recordUpload(clientId, fileResult.size, authMetadata),\n );\n } else {\n yield* Effect.logWarning(\n `[Upload] Cannot record metrics - missing organizationId or size`,\n );\n }\n }\n\n if (clientId) {\n yield* Effect.logInfo(\n `[Upload] Chunk uploaded for upload: ${uploadId}, client: ${clientId}`,\n );\n }\n\n return {\n status: 200,\n body: fileResult,\n } as UploadChunkResponse;\n });\n","import { Effect } from \"effect\";\nimport type { UploadistaRequest, UploadistaResponse } from \"../routes\";\nimport {\n handleCancelFlow,\n handleGetFlow,\n handleJobStatus,\n handlePauseFlow,\n handleResumeFlow,\n handleRunFlow,\n} from \"./flow-http-handlers\";\nimport {\n handleCreateUpload,\n handleGetCapabilities,\n handleGetUpload,\n handleUploadChunk,\n} from \"./upload-http-handlers\";\n\nexport type { UploadistaRequest, UploadistaResponse } from \"../routes\";\n\nexport const handleUploadistaRequest = <TRequirements>(\n req: UploadistaRequest,\n) => {\n return Effect.gen(function* () {\n switch (req.type) {\n case \"create-upload\":\n return (yield* handleCreateUpload(req)) as UploadistaResponse;\n case \"get-capabilities\":\n return (yield* handleGetCapabilities(req)) as UploadistaResponse;\n case \"get-upload\":\n return (yield* handleGetUpload(req)) as UploadistaResponse;\n case \"upload-chunk\":\n return (yield* handleUploadChunk(req)) as UploadistaResponse;\n case \"get-flow\":\n return (yield* handleGetFlow(req)) as UploadistaResponse;\n case \"run-flow\":\n return (yield* handleRunFlow<TRequirements>(req)) as UploadistaResponse;\n case \"job-status\":\n return (yield* handleJobStatus(req)) as UploadistaResponse;\n case \"resume-flow\":\n return (yield* handleResumeFlow<TRequirements>(\n req,\n )) as UploadistaResponse;\n case \"pause-flow\":\n return (yield* handlePauseFlow(req)) as UploadistaResponse;\n case \"cancel-flow\":\n return (yield* handleCancelFlow(req)) as UploadistaResponse;\n case \"not-found\":\n return {\n status: 404,\n headers: { \"Content-Type\": \"application/json\" },\n body: { error: \"Not found\" },\n } as UploadistaResponse;\n case \"bad-request\":\n return {\n status: 400,\n body: { error: \"Bad request\", message: req.message },\n } as UploadistaResponse;\n case \"method-not-allowed\":\n return {\n status: 405,\n headers: { \"Content-Type\": \"application/json\" },\n body: { error: \"Method not allowed\" },\n } as UploadistaResponse;\n case \"unsupported-content-type\":\n return {\n status: 415,\n headers: { \"Content-Type\": \"application/json\" },\n body: { error: \"Unsupported content type\" },\n } as UploadistaResponse;\n }\n });\n};\n","import type { PluginLayer, UploadistaError } from \"@uploadista/core\";\nimport { type Flow, FlowProvider, FlowWaitUntil } from \"@uploadista/core/flow\";\nimport {\n createDataStoreLayer,\n type UploadFileDataStores,\n type UploadFileKVStore,\n} from \"@uploadista/core/types\";\nimport { GenerateIdLive } from \"@uploadista/core/utils\";\nimport { memoryEventBroadcaster } from \"@uploadista/event-broadcaster-memory\";\nimport { webSocketEventEmitter } from \"@uploadista/event-emitter-websocket\";\nimport { NodeSdkLive, NoOpMetricsServiceLive } from \"@uploadista/observability\";\nimport { Effect, Layer, ManagedRuntime } from \"effect\";\nimport type { z } from \"zod\";\nimport type { StandardResponse } from \"../adapter\";\nimport { AuthCacheServiceLive } from \"../cache\";\nimport { handleFlowError } from \"../http-utils\";\nimport { createFlowServerLayer, createUploadServerLayer } from \"../layer-utils\";\nimport { AuthContextServiceLive } from \"../service\";\nimport type { AuthContext } from \"../types\";\nimport { handleUploadistaRequest } from \"./http-handlers/http-handlers\";\nimport type { ExtractFlowPluginRequirements } from \"./plugin-types\";\nimport type { NotFoundResponse } from \"./routes\";\nimport type { UploadistaServer, UploadistaServerConfig } from \"./types\";\n\n/**\n * Creates the unified Uploadista server with framework-specific adapter.\n *\n * This is the single, unified API for creating an Uploadista server. It handles\n * all server initialization, layer composition, and runtime setup.\n *\n * ## Core Responsibilities\n *\n * The server handles:\n * - Layer composition (upload/flow servers, auth cache, metrics, plugins)\n * - Route parsing and matching\n * - Auth middleware execution with timeout protection\n * - Error handling and response formatting\n * - Effect program execution with optional tracing\n * - Plugin validation and dependency injection\n *\n * ## Plugin Validation\n *\n * The server supports two validation approaches:\n *\n * ### 1. Runtime Validation (Recommended for Most Cases)\n *\n * The server relies on Effect-TS's dependency injection to validate plugins\n * at runtime. If a required plugin is missing, Effect will fail with a clear\n * MissingService error.\n *\n * ```typescript\n * const server = await createUploadistaServer({\n * flows: getFlowById,\n * plugins: [sharpImagePlugin, zipPlugin],\n * dataStore: s3DataStore,\n * kvStore: redisKvStore,\n * adapter: honoAdapter({ ... })\n * });\n * // If plugins don't match flow requirements, Effect fails with clear error\n * ```\n *\n * ### 2. Compile-Time Validation (Optional)\n *\n * For IDE feedback during development, use the ValidatePlugins type utility:\n *\n * ```typescript\n * import {\n * createUploadistaServer,\n * ValidatePlugins,\n * ExtractFlowPluginRequirements\n * } from '@uploadista/server';\n *\n * // Extract requirements from flows\n * type Requirements = ExtractFlowPluginRequirements<typeof getFlowById>;\n *\n * // Define plugins\n * const plugins = [sharpImagePlugin, zipPlugin] as const;\n *\n * // Validate at compile time (optional, for IDE feedback)\n * type Validation = ValidatePlugins<typeof plugins, Requirements>;\n * // IDE shows error if plugins don't match requirements\n *\n * const server = await createUploadistaServer({\n * flows: getFlowById,\n * plugins,\n * // ...\n * });\n * ```\n *\n * ### 3. Early Runtime Validation (Optional)\n *\n * For better error messages before server starts:\n *\n * ```typescript\n * import { validatePluginsOrThrow } from '@uploadista/server/core';\n *\n * validatePluginsOrThrow({\n * plugins: [sharpImagePlugin],\n * expectedServices: ['ImagePlugin', 'ZipPlugin']\n * });\n * // Throws with helpful error message including import suggestions\n * ```\n *\n * ## Type Safety\n *\n * - Plugin requirements are inferred from flow definitions\n * - Effect-TS ensures dependencies are satisfied at runtime\n * - Type casting is intentional (see inline docs for rationale)\n * - Optional compile-time validation available via type utilities\n *\n * @template TContext - Framework-specific context type\n * @template TResponse - Framework-specific response type\n * @template TWebSocketHandler - WebSocket handler type (if supported)\n * @template TFlows - Flow function type with plugin requirements\n * @template TPlugins - Tuple of plugin layers provided\n *\n * @param config - Server configuration including adapter and business logic\n * @returns Promise resolving to server instance with handler and metadata\n *\n * @example Basic Usage\n * ```typescript\n * import { createUploadistaServer, honoAdapter } from \"@uploadista/server\";\n * import { sharpImagePlugin } from \"@uploadista/flow-images-sharp\";\n *\n * const server = await createUploadistaServer({\n * flows: getFlowById,\n * plugins: [sharpImagePlugin],\n * dataStore: { type: \"s3\", config: { bucket: \"uploads\" } },\n * kvStore: redisKvStore,\n * adapter: honoAdapter({\n * authMiddleware: async (c) => ({ clientId: \"user-123\" })\n * })\n * });\n *\n * // Use with Hono\n * app.all(\"/uploadista/*\", server.handler);\n * ```\n *\n * @example With Compile-Time Validation\n * ```typescript\n * import {\n * createUploadistaServer,\n * ValidatePlugins,\n * ExtractFlowPluginRequirements\n * } from \"@uploadista/server\";\n *\n * type Requirements = ExtractFlowPluginRequirements<typeof getFlowById>;\n * const plugins = [sharpImagePlugin, zipPlugin] as const;\n * type Validation = ValidatePlugins<typeof plugins, Requirements>;\n *\n * const server = await createUploadistaServer({\n * flows: getFlowById,\n * plugins,\n * // ... rest of config\n * });\n * ```\n *\n * @see ValidatePlugins - Compile-time plugin validation\n * @see ExtractFlowPluginRequirements - Extract requirements from flows\n * @see validatePluginRequirements - Runtime validation helper\n * @see API_DECISION_GUIDE.md - Complete guide for choosing validation approach\n */\nexport const createUploadistaServer = async <\n TContext,\n TResponse,\n TWebSocketHandler = unknown,\n TFlows extends (\n flowId: string,\n clientId: string | null,\n ) => Effect.Effect<\n // biome-ignore lint/suspicious/noExplicitAny: Flow requirements can be any plugin services\n Flow<z.ZodSchema<unknown>, z.ZodSchema<unknown>, any>,\n UploadistaError,\n // biome-ignore lint/suspicious/noExplicitAny: Flow return type allows any requirements\n any\n // biome-ignore lint/suspicious/noExplicitAny: Generic type constraint allows any flow function type with any requirements\n > = any,\n TPlugins extends readonly PluginLayer[] = readonly PluginLayer[],\n>({\n flows,\n dataStore,\n kvStore,\n // Default to an empty plugin list while preserving the generic type\n plugins = [] as unknown as TPlugins,\n eventEmitter,\n eventBroadcaster = memoryEventBroadcaster,\n withTracing = false,\n baseUrl: configBaseUrl = \"uploadista\",\n generateId = GenerateIdLive,\n metricsLayer,\n bufferedDataStore,\n adapter,\n authCacheConfig,\n}: UploadistaServerConfig<\n TContext,\n TResponse,\n TWebSocketHandler,\n TFlows,\n TPlugins\n>): Promise<UploadistaServer<TContext, TResponse, TWebSocketHandler>> => {\n // Default eventEmitter to webSocketEventEmitter with the provided eventBroadcaster\n const finalEventEmitter =\n eventEmitter ?? webSocketEventEmitter(eventBroadcaster);\n\n // Normalize baseUrl (remove trailing slash)\n const baseUrl = configBaseUrl.endsWith(\"/\")\n ? configBaseUrl.slice(0, -1)\n : configBaseUrl;\n\n type FlowReq = ExtractFlowPluginRequirements<TFlows>;\n\n // Create flow provider layer from flows function\n const flowProviderLayer = Layer.effect(\n FlowProvider,\n Effect.succeed({\n getFlow: (flowId: string, clientId: string | null) => {\n // Cast the flows function to match FlowProvider expectations\n // The context requirements will be provided at the layer level\n return flows(flowId, clientId) as Effect.Effect<\n Flow<z.ZodSchema<unknown>, z.ZodSchema<unknown>, FlowReq>,\n UploadistaError\n >;\n },\n }),\n );\n\n // Validate that eventEmitter is provided (required for upload/flow servers)\n if (!finalEventEmitter) {\n throw new Error(\n \"eventEmitter is required. Provide an event emitter layer in the configuration.\",\n );\n }\n\n // Create data store layer\n const dataStoreLayer: Layer.Layer<\n UploadFileDataStores,\n never,\n UploadFileKVStore\n > = await createDataStoreLayer(dataStore);\n\n // Create upload server layer\n const uploadServerLayer = createUploadServerLayer({\n kvStore,\n eventEmitter: finalEventEmitter,\n dataStore: dataStoreLayer,\n bufferedDataStore,\n generateId,\n });\n\n // Create flow server layer\n const flowServerLayer = createFlowServerLayer({\n kvStore,\n eventEmitter: finalEventEmitter,\n flowProvider: flowProviderLayer,\n uploadServer: uploadServerLayer,\n });\n\n // Create auth cache layer (always present, even if auth is not enabled)\n const authCacheLayer = AuthCacheServiceLive(authCacheConfig);\n\n // Metrics layer (defaults to NoOp if not provided)\n const effectiveMetricsLayer = metricsLayer ?? NoOpMetricsServiceLive;\n\n /**\n * Merge all server layers including plugins.\n *\n * This combines the core server infrastructure (upload server, flow server,\n * metrics, auth cache) with user-provided plugin layers.\n */\n const serverLayerRaw = Layer.mergeAll(\n uploadServerLayer,\n flowServerLayer,\n effectiveMetricsLayer,\n authCacheLayer,\n ...plugins,\n );\n\n /**\n * Type Casting Rationale for Plugin System\n *\n * The type assertion below is intentional and safe. This is not a bug or workaround,\n * but follows Effect-TS's design for dynamic dependency injection.\n *\n * ## Why Type Casting is Necessary\n *\n * 1. **Plugin Requirements are Dynamic**\n * Different flows require different plugins (ImagePlugin, ZipPlugin, etc.).\n * These requirements are only known when flows are loaded at runtime.\n * Flow A might need ImagePlugin, Flow B might need ZipPlugin.\n *\n * 2. **TypeScript's Static Limitation**\n * TypeScript cannot statically verify that all possible flow combinations\n * will have their requirements satisfied. The plugin array is typed as\n * `readonly PluginLayer[]` which could be any combination of plugins.\n *\n * 3. **Effect-TS Runtime Resolution**\n * Effect-TS is designed to resolve service requirements at runtime using\n * its dependency injection system. When a flow executes and accesses a service:\n *\n * ```typescript\n * const imagePlugin = yield* ImagePlugin;\n * ```\n *\n * Effect checks if ImagePlugin exists in the provided layer context.\n * If missing, Effect fails with a clear MissingService error.\n *\n * 4. **Layer Composition Guarantees**\n * Layer.mergeAll() combines all layers. At runtime, Effect ensures that\n * when a service is requested, it's either:\n * - Provided by one of the merged layers, OR\n * - Results in a MissingService error with the service name\n *\n * ## Safety Guarantees\n *\n * This pattern is safe because:\n *\n * 1. **Runtime Validation** (Optional but Recommended)\n * We provide validatePluginRequirements() that checks plugins before\n * server initialization, giving excellent error messages early.\n *\n * 2. **Effect's Built-in Validation**\n * If runtime validation is skipped, Effect will fail during flow execution\n * with a MissingService error containing the service identifier.\n *\n * 3. **Optional Compile-Time Validation**\n * Developers can use ValidatePlugins<> type utility for IDE feedback:\n *\n * ```typescript\n * type Validation = ValidatePlugins<typeof plugins, Requirements>;\n * // Shows compile error if plugins don't match requirements\n * ```\n *\n * 4. **No Silent Failures**\n * There's no scenario where missing plugins cause silent failures.\n * Either runtime validation catches it, or Effect fails with clear error.\n *\n * ## This is Effect-TS's Idiomatic Pattern\n *\n * Effect-TS separates compile-time structure from runtime resolution:\n * - Compile-time: Types ensure layer structure is correct\n * - Runtime: Effect resolves actual dependencies and fails if missing\n *\n * The type system provides structure and IDE support, while Effect's\n * runtime handles actual requirement resolution.\n *\n * ## Further Reading\n *\n * - Effect-TS Context Management: https://effect.website/docs/guides/context-management\n * - Runtime Validation: See plugin-validation.ts for helper functions\n * - Type Utilities: See plugin-types.ts for compile-time validation\n *\n * @see validatePluginRequirements - Runtime validation helper\n * @see ValidatePlugins - Compile-time validation type utility\n */\n const serverLayer = serverLayerRaw as unknown as Layer.Layer<\n // biome-ignore lint/suspicious/noExplicitAny: Dynamic plugin requirements require any - see comprehensive explanation above\n any,\n never,\n never\n >;\n\n // Create a shared managed runtime from the server layer\n // This ensures all requests use the same layer instances (including event broadcaster)\n // ManagedRuntime properly handles scoped resources and provides convenient run methods\n\n const managedRuntime = ManagedRuntime.make(serverLayer);\n\n /**\n * Main request handler that processes HTTP requests through the adapter.\n * Delegates to adapter's httpHandler if provided, otherwise uses standard flow.\n */\n const handler = async <TRequirements>(ctx: TContext) => {\n // Fallback: Standard routing logic (for adapters without httpHandler)\n const program = Effect.gen(function* () {\n // Extract standard request from framework-specific request\n const uploadistaRequest = yield* adapter.extractRequest(ctx, { baseUrl });\n\n // Run auth middleware if provided\n let authContext: AuthContext | null = null;\n if (adapter.runAuthMiddleware) {\n const authMiddlewareWithTimeout = adapter.runAuthMiddleware(ctx).pipe(\n Effect.timeout(\"5 seconds\"),\n Effect.catchAll(() => {\n // Timeout error\n console.error(\"Auth middleware timeout exceeded (5 seconds)\");\n return Effect.succeed({\n _tag: \"TimeoutError\" as const,\n } as const);\n }),\n Effect.catchAllCause((cause) => {\n // Other errors\n console.error(\"Auth middleware error:\", cause);\n return Effect.succeed({\n _tag: \"AuthError\" as const,\n error: cause,\n } as const);\n }),\n );\n\n const authResult:\n | AuthContext\n | null\n | { _tag: \"TimeoutError\" }\n | { _tag: \"AuthError\"; error: unknown } =\n yield* authMiddlewareWithTimeout;\n\n // Handle timeout\n if (\n authResult &&\n typeof authResult === \"object\" &&\n \"_tag\" in authResult &&\n authResult._tag === \"TimeoutError\"\n ) {\n const errorResponse: StandardResponse = {\n status: 503,\n headers: { \"Content-Type\": \"application/json\" },\n body: {\n error: \"Authentication service unavailable\",\n message:\n \"Authentication took too long to respond. Please try again.\",\n },\n };\n return yield* adapter.sendResponse(errorResponse, ctx);\n }\n\n // Handle auth error\n if (\n authResult &&\n typeof authResult === \"object\" &&\n \"_tag\" in authResult &&\n authResult._tag === \"AuthError\"\n ) {\n const errorResponse: StandardResponse = {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n body: {\n error: \"Internal Server Error\",\n message: \"An error occurred during authentication\",\n },\n };\n return yield* adapter.sendResponse(errorResponse, ctx);\n }\n\n // Handle authentication failure (null result)\n if (authResult === null) {\n const errorResponse: StandardResponse = {\n status: 401,\n headers: { \"Content-Type\": \"application/json\" },\n body: {\n error: \"Unauthorized\",\n message: \"Invalid credentials\",\n },\n };\n return yield* adapter.sendResponse(errorResponse, ctx);\n }\n\n authContext = authResult;\n }\n\n // Create auth context layer for this request\n const authContextLayer = AuthContextServiceLive(authContext);\n\n // Extract waitUntil callback if available (for Cloudflare Workers)\n // This must be extracted per-request since it comes from the framework context\n // biome-ignore lint/suspicious/noExplicitAny: Layer array needs to accept any service type from waitUntil\n const waitUntilLayers: Layer.Layer<any, never, never>[] = [];\n if (adapter.extractWaitUntil) {\n const waitUntilCallback = adapter.extractWaitUntil(ctx);\n if (waitUntilCallback) {\n waitUntilLayers.push(Layer.succeed(FlowWaitUntil, waitUntilCallback));\n }\n }\n\n // Combine auth context, auth cache, metrics layers, plugins, and waitUntil\n // This ensures that flow nodes have access to all required services\n const requestContextLayer = Layer.mergeAll(\n authContextLayer,\n authCacheLayer,\n effectiveMetricsLayer,\n ...plugins,\n ...waitUntilLayers,\n );\n\n // Check for baseUrl/api/ prefix\n if (uploadistaRequest.type === \"not-found\") {\n const notFoundResponse: NotFoundResponse = {\n type: \"not-found\",\n status: 404,\n headers: { \"Content-Type\": \"application/json\" },\n body: { error: \"Not found\" },\n };\n return yield* adapter.sendResponse(notFoundResponse, ctx);\n }\n\n // Handle the request\n const response = yield* handleUploadistaRequest<TRequirements>(\n uploadistaRequest,\n ).pipe(Effect.provide(requestContextLayer));\n\n return yield* adapter.sendResponse(response, ctx);\n }).pipe(\n // Catch all errors and format them appropriately\n Effect.catchAll((error: unknown) => {\n const errorInfo = handleFlowError(error);\n const errorBody: Record<string, unknown> = {\n code: errorInfo.code,\n message: errorInfo.message,\n };\n if (errorInfo.details !== undefined) {\n errorBody.details = errorInfo.details;\n }\n const errorResponse: StandardResponse = {\n status: errorInfo.status,\n headers: { \"Content-Type\": \"application/json\" },\n body: errorBody,\n };\n return adapter.sendResponse(errorResponse, ctx);\n }),\n );\n\n // Use the shared managed runtime instead of creating a new one per request\n if (withTracing) {\n return managedRuntime.runPromise(\n program.pipe(Effect.provide(NodeSdkLive)),\n );\n }\n return managedRuntime.runPromise(program);\n };\n\n // Create WebSocket handler using the shared managed runtime\n const websocketHandler = await managedRuntime.runPromise(\n adapter.webSocketHandler({\n baseUrl,\n }),\n );\n\n return {\n handler,\n websocketHandler,\n baseUrl,\n dispose: () => managedRuntime.dispose(),\n };\n};\n","import type {\n PluginServices,\n PluginTuple,\n TypeSafeFlowFunction,\n ValidatePlugins,\n} from \"./plugin-types\";\nimport { createUploadistaServer } from \"./server\";\nimport type { UploadistaServer, UploadistaServerConfig } from \"./types\";\n\n/**\n * Type-safe configuration for Uploadista server with compile-time plugin validation.\n *\n * This configuration extends the base UploadistaServerConfig with stricter typing\n * that validates plugins match flow requirements at compile time.\n *\n * @template TContext - Framework-specific request context type\n * @template TResponse - Framework-specific response type\n * @template TWebSocket - Framework-specific WebSocket handler type\n * @template TPlugins - Tuple of plugin layers provided to the server\n * @template TFlowRequirements - Union of plugin services required by flows\n */\nexport type TypeSafeServerConfig<\n TContext,\n TResponse,\n TWebSocket,\n TPlugins extends PluginTuple,\n TFlowRequirements = PluginServices<TPlugins>,\n> = Omit<\n UploadistaServerConfig<TContext, TResponse, TWebSocket>,\n \"flows\" | \"plugins\"\n> & {\n /**\n * Tuple of plugin layers that provide services to flows.\n * The plugins must satisfy all requirements declared by the flows.\n */\n plugins: TPlugins;\n\n /**\n * Type-safe flow function with explicit requirements.\n * TypeScript validates that all required plugins are provided.\n */\n flows: TypeSafeFlowFunction<TFlowRequirements>;\n\n /**\n * Compile-time validation that plugins satisfy flow requirements.\n * If this field has type errors, required plugins are missing.\n */\n __validate?: ValidatePlugins<TPlugins, TFlowRequirements>;\n};\n\n/**\n * @deprecated Use `createUploadistaServer` with optional type utilities instead.\n *\n * This function is deprecated in favor of the unified `createUploadistaServer` API.\n * The new approach separates validation concerns from server creation, making the\n * API simpler while still providing compile-time validation when desired.\n *\n * ## Migration Guide\n *\n * ### Old Approach (Deprecated)\n * ```typescript\n * import { createTypeSafeServer } from \"@uploadista/server\";\n *\n * const server = await createTypeSafeServer({\n * plugins: [sharpImagePlugin] as const,\n * flows: myFlowFunction,\n * // ...\n * });\n * ```\n *\n * ### New Approach (Recommended)\n *\n * **Option 1: Runtime validation only (simplest)**\n * ```typescript\n * import { createUploadistaServer } from \"@uploadista/server\";\n *\n * const server = await createUploadistaServer({\n * plugins: [sharpImagePlugin, zipPlugin],\n * flows: myFlowFunction,\n * // ... Effect validates at runtime\n * });\n * ```\n *\n * **Option 2: With compile-time validation (optional)**\n * ```typescript\n * import {\n * createUploadistaServer,\n * ValidatePlugins,\n * ExtractFlowPluginRequirements\n * } from \"@uploadista/server\";\n *\n * type Requirements = ExtractFlowPluginRequirements<typeof myFlowFunction>;\n * const plugins = [sharpImagePlugin, zipPlugin] as const;\n * type Validation = ValidatePlugins<typeof plugins, Requirements>;\n * // IDE shows error if plugins don't match requirements\n *\n * const server = await createUploadistaServer({\n * plugins,\n * flows: myFlowFunction,\n * // ...\n * });\n * ```\n *\n * ## Why This Changed\n *\n * 1. **Simpler API**: One function instead of two reduces confusion\n * 2. **Separation of Concerns**: Validation is now optional and separate\n * 3. **Better Flexibility**: Choose validation approach per use case\n * 4. **Clearer Intent**: Explicit validation via type utilities\n * 5. **Same Safety**: Effect-TS still validates at runtime\n *\n * The new approach trusts Effect-TS's design for dynamic dependency injection\n * while providing optional compile-time validation through type utilities.\n *\n * @see createUploadistaServer - The unified server creation API\n * @see ValidatePlugins - Compile-time validation type utility\n * @see ExtractFlowPluginRequirements - Extract requirements from flows\n * @see API_DECISION_GUIDE.md - Complete migration and usage guide\n *\n * @template TContext - Framework-specific request context type\n * @template TResponse - Framework-specific response type\n * @template TWebSocket - Framework-specific WebSocket handler type\n * @template TPlugins - Tuple of plugin layers\n * @template TFlowRequirements - Union of services required by flows\n *\n * @param config - Type-safe server configuration\n * @returns Promise resolving to UploadistaServer instance\n */\nexport async function createTypeSafeServer<\n TContext,\n TResponse,\n TWebSocket = unknown,\n TPlugins extends PluginTuple = PluginTuple,\n TFlowRequirements = PluginServices<TPlugins>,\n>(\n config: TypeSafeServerConfig<\n TContext,\n TResponse,\n TWebSocket,\n TPlugins,\n TFlowRequirements\n > &\n // Enforce validation at function call site\n (ValidatePlugins<TPlugins, TFlowRequirements> extends true\n ? object\n : ValidatePlugins<TPlugins, TFlowRequirements>),\n): Promise<UploadistaServer<TContext, TResponse, TWebSocket>> {\n return createUploadistaServer(config);\n}\n\n/**\n * Helper function to define flow functions with explicit type requirements.\n * Provides better type inference and autocomplete for plugin services.\n *\n * @template TRequirements - Union of plugin services this flow needs\n *\n * @param fn - The flow function implementation\n * @returns The same function with explicit type annotation\n *\n * @example\n * ```typescript\n * import { ImagePlugin } from \"@uploadista/core/flow\";\n * import { defineFlow } from \"@uploadista/server\";\n *\n * // Explicitly declare that this flow requires ImagePlugin\n * const imageProcessingFlow = defineFlow<ImagePlugin>((flowId, clientId) =>\n * Effect.gen(function* () {\n * const imageService = yield* ImagePlugin; // Autocomplete works!\n * const optimized = yield* imageService.optimize(data, { quality: 80 });\n * return createFlow({ ... });\n * })\n * );\n * ```\n */\nexport function defineFlow<TRequirements = never>(\n fn: TypeSafeFlowFunction<TRequirements>,\n): TypeSafeFlowFunction<TRequirements> {\n return fn;\n}\n\n/**\n * Helper to create a flow that requires no plugins.\n * Useful for simple flows that only use built-in functionality.\n *\n * @example\n * ```typescript\n * import { defineSimpleFlow } from \"@uploadista/server\";\n *\n * const simpleFlow = defineSimpleFlow((flowId, clientId) =>\n * Effect.succeed(createFlow({\n * id: \"simple\",\n * nodes: [],\n * edges: [],\n * inputSchema: myInputSchema,\n * outputSchema: myOutputSchema\n * }))\n * );\n * ```\n */\nexport function defineSimpleFlow(\n fn: TypeSafeFlowFunction<never>,\n): TypeSafeFlowFunction<never> {\n return fn;\n}\n","/**\n * Runtime plugin validation utilities.\n *\n * This module provides runtime validation to ensure that all plugins required\n * by flows are actually provided to the server. While Effect-TS will catch\n * missing dependencies at runtime, this validation provides better error messages\n * and fails fast during server initialization.\n *\n * @module plugin-validation\n */\n\nimport type { PluginLayer } from \"@uploadista/core\";\nimport { Effect } from \"effect\";\n\n/**\n * Result of plugin validation.\n */\nexport type PluginValidationResult =\n | {\n success: true;\n }\n | {\n success: false;\n required: string[];\n provided: string[];\n missing: string[];\n suggestions: Array<{\n name: string;\n packageName: string;\n importStatement: string;\n }>;\n };\n\n/**\n * Known plugin mapping for generating helpful error messages.\n *\n * This maps service identifiers to their package names and variable names\n * for generating import suggestions.\n */\nconst KNOWN_PLUGINS: Record<\n string,\n { packageName: string; variableName: string }\n> = {\n ImagePlugin: {\n packageName: \"@uploadista/flow-images-sharp\",\n variableName: \"sharpImagePlugin\",\n },\n ImageAiPlugin: {\n packageName: \"@uploadista/flow-images-replicate\",\n variableName: \"replicateImagePlugin\",\n },\n ZipPlugin: {\n packageName: \"@uploadista/flow-utility-zipjs\",\n variableName: \"zipPlugin\",\n },\n CredentialProvider: {\n packageName: \"@uploadista/core\",\n variableName: \"credentialProviderLayer\",\n },\n};\n\n/**\n * Extracts service identifier from a plugin layer.\n *\n * This attempts to identify the service provided by a layer using various\n * heuristics. The exact implementation depends on how Effect-TS exposes\n * layer metadata.\n *\n * @param layer - The plugin layer to inspect\n * @returns Service identifier string or null if not identifiable\n */\nfunction extractServiceIdentifier(layer: PluginLayer): string | null {\n // Attempt to extract service identifier from layer\n // Note: Effect-TS doesn't expose this information in a standard way,\n // so we use Symbol.toStringTag or constructor name as fallbacks\n\n try {\n // Try to get the service tag if available\n // biome-ignore lint/suspicious/noExplicitAny: Layer introspection requires accessing internal properties\n const layerAny = layer as any;\n\n // Check for common patterns in Effect layers\n if (layerAny._tag) {\n return layerAny._tag;\n }\n\n if (layerAny.constructor?.name) {\n return layerAny.constructor.name;\n }\n\n // Try to extract from the layer's context if available\n if (layerAny.context?.services) {\n const services = Array.from(layerAny.context.services.keys());\n if (services.length > 0) {\n // biome-ignore lint/suspicious/noExplicitAny: Service introspection requires accessing internal properties\n const firstService = services[0] as any;\n if (firstService.key) {\n return firstService.key;\n }\n }\n }\n\n return null;\n } catch {\n // If we can't extract the identifier, return null\n return null;\n }\n}\n\n/**\n * Extracts service identifiers from an array of plugin layers.\n *\n * @param plugins - Array of plugin layers\n * @returns Array of service identifier strings\n */\nexport function extractServiceIdentifiers(\n plugins: readonly PluginLayer[],\n): string[] {\n return plugins\n .map((plugin) => extractServiceIdentifier(plugin))\n .filter((id): id is string => id !== null);\n}\n\n/**\n * Validates that all required plugins are provided.\n *\n * This is a runtime validation function that checks if the plugins array\n * contains all services required by the flows. It's called during server\n * initialization to provide early, clear error messages.\n *\n * Note: This validation is best-effort because we can't reliably extract\n * requirements from flow functions at runtime without executing them.\n * The main validation happens via Effect-TS's dependency injection.\n *\n * @param config - Validation configuration\n * @returns Validation result with detailed error information if validation fails\n *\n * @example\n * ```typescript\n * const result = validatePluginRequirements({\n * plugins: [sharpImagePlugin, zipPlugin],\n * expectedServices: ['ImagePlugin', 'ZipPlugin']\n * });\n *\n * if (!result.success) {\n * console.error('Missing plugins:', result.missing);\n * console.error('Suggestions:', result.suggestions);\n * }\n * ```\n */\nexport function validatePluginRequirements(config: {\n plugins: readonly PluginLayer[];\n expectedServices?: string[];\n}): PluginValidationResult {\n const { plugins, expectedServices = [] } = config;\n\n // Extract identifiers from provided plugins\n const providedServices = extractServiceIdentifiers(plugins);\n\n // Check for missing services\n const missing = expectedServices.filter(\n (required) => !providedServices.includes(required),\n );\n\n if (missing.length === 0) {\n return { success: true };\n }\n\n // Generate suggestions for missing plugins\n const suggestions = missing\n .map((service) => {\n const knownPlugin = KNOWN_PLUGINS[service];\n if (!knownPlugin) {\n return null;\n }\n\n return {\n name: service,\n packageName: knownPlugin.packageName,\n importStatement: `import { ${knownPlugin.variableName} } from '${knownPlugin.packageName}';`,\n };\n })\n .filter((s): s is NonNullable<typeof s> => s !== null);\n\n return {\n success: false,\n required: expectedServices,\n provided: providedServices,\n missing,\n suggestions,\n };\n}\n\n/**\n * Creates a formatted error message for plugin validation failures.\n *\n * This generates a detailed, human-readable error message that includes:\n * - List of required plugins\n * - List of provided plugins\n * - List of missing plugins\n * - Import statements for missing plugins (if known)\n * - Example server configuration\n *\n * @param result - Failed validation result\n * @returns Formatted error message string\n *\n * @example\n * ```typescript\n * const result = validatePluginRequirements({ ... });\n * if (!result.success) {\n * const message = formatPluginValidationError(result);\n * throw new Error(message);\n * }\n * ```\n */\nexport function formatPluginValidationError(\n result: Extract<PluginValidationResult, { success: false }>,\n): string {\n const lines: string[] = [\n \"Server initialization failed: Missing required plugins\",\n \"\",\n `Required: ${result.required.join(\", \")}`,\n `Provided: ${result.provided.length > 0 ? result.provided.join(\", \") : \"(none)\"}`,\n `Missing: ${result.missing.join(\", \")}`,\n \"\",\n ];\n\n if (result.suggestions.length > 0) {\n lines.push(\"Add the missing plugins to your configuration:\");\n lines.push(\"\");\n for (const suggestion of result.suggestions) {\n lines.push(` ${suggestion.importStatement}`);\n }\n lines.push(\"\");\n lines.push(\" const server = await createUploadistaServer({\");\n lines.push(\n ` plugins: [${[...result.provided, ...result.missing.map((m) => KNOWN_PLUGINS[m]?.variableName || m)].join(\", \")}],`,\n );\n lines.push(\" // ...\");\n lines.push(\" });\");\n } else {\n lines.push(\"Note: Could not determine package names for missing plugins.\");\n lines.push(\"Please ensure all required plugin layers are provided.\");\n }\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Effect-based plugin validation that can be composed with other Effects.\n *\n * This provides an Effect-TS native way to validate plugins, allowing it\n * to be composed with other Effects in the server initialization pipeline.\n *\n * @param config - Validation configuration\n * @returns Effect that succeeds if validation passes, fails with UploadistaError if not\n *\n * @example\n * ```typescript\n * const validatedServer = Effect.gen(function* () {\n * yield* validatePluginRequirementsEffect({\n * plugins: [sharpImagePlugin],\n * expectedServices: ['ImagePlugin', 'ZipPlugin']\n * });\n *\n * return yield* createServerEffect(...);\n * });\n * ```\n */\nexport function validatePluginRequirementsEffect(config: {\n plugins: readonly PluginLayer[];\n expectedServices?: string[];\n}): Effect.Effect<void, Error> {\n return Effect.sync(() => {\n const result = validatePluginRequirements(config);\n\n if (!result.success) {\n const message = formatPluginValidationError(result);\n throw new Error(message);\n }\n });\n}\n\n/**\n * Validates plugin configuration at runtime during server initialization.\n *\n * This is a convenience function that performs validation and throws a\n * descriptive error if validation fails. Use this at the beginning of\n * createUploadistaServer to fail fast with clear error messages.\n *\n * @param config - Validation configuration\n * @throws Error with detailed message if validation fails\n *\n * @example\n * ```typescript\n * export const createUploadistaServer = async (config) => {\n * // Validate plugins early\n * validatePluginsOrThrow({\n * plugins: config.plugins,\n * expectedServices: ['ImagePlugin', 'ZipPlugin']\n * });\n *\n * // Continue with server creation...\n * };\n * ```\n */\nexport function validatePluginsOrThrow(config: {\n plugins: readonly PluginLayer[];\n expectedServices?: string[];\n}): void {\n const result = validatePluginRequirements(config);\n\n if (!result.success) {\n const message = formatPluginValidationError(result);\n throw new Error(message);\n }\n}\n","import type { FlowServerShape } from \"@uploadista/core/flow\";\nimport { Effect } from \"effect\";\nimport type { WebSocketConnection } from \"../websocket-routes\";\n\n/**\n * Handles subscription to flow events\n * Subscribes the WebSocket connection to receive real-time flow execution events\n */\nexport const handleSubscribeToFlowEvents = (\n flowServer: FlowServerShape,\n jobId: string | undefined,\n connection: WebSocketConnection,\n) => {\n return Effect.gen(function* () {\n if (!jobId) {\n yield* Effect.sync(() => {\n connection.send(\n JSON.stringify({\n type: \"error\",\n message: \"Job ID is required for flow event subscription\",\n code: \"MISSING_JOB_ID\",\n }),\n );\n });\n return;\n }\n\n yield* flowServer.subscribeToFlowEvents(jobId, connection);\n });\n};\n\n/**\n * Handles unsubscription from flow events\n * Removes the WebSocket connection from receiving flow events\n */\nexport const handleUnsubscribeFromFlowEvents = (\n flowServer: FlowServerShape,\n jobId: string | undefined,\n) => {\n return Effect.gen(function* () {\n if (!jobId) {\n return;\n }\n\n yield* flowServer.unsubscribeFromFlowEvents(jobId);\n });\n};\n","import type { UploadServerShape } from \"@uploadista/core/upload\";\nimport { Effect } from \"effect\";\nimport type { WebSocketConnection } from \"../websocket-routes\";\n\n/**\n * Handles subscription to upload events\n * Subscribes the WebSocket connection to receive real-time upload progress events\n */\nexport const handleSubscribeToUploadEvents = (\n uploadServer: UploadServerShape,\n uploadId: string | undefined,\n connection: WebSocketConnection,\n) => {\n return Effect.gen(function* () {\n if (!uploadId) {\n yield* Effect.sync(() => {\n connection.send(\n JSON.stringify({\n type: \"error\",\n message: \"Upload ID is required for upload event subscription\",\n code: \"MISSING_UPLOAD_ID\",\n }),\n );\n });\n return;\n }\n\n yield* uploadServer.subscribeToUploadEvents(uploadId, connection);\n });\n};\n\n/**\n * Handles unsubscription from upload events\n * Removes the WebSocket connection from receiving upload events\n */\nexport const handleUnsubscribeFromUploadEvents = (\n uploadServer: UploadServerShape,\n uploadId: string | undefined,\n) => {\n return Effect.gen(function* () {\n if (!uploadId) {\n return;\n }\n\n yield* uploadServer.unsubscribeFromUploadEvents(uploadId);\n });\n};\n","import { UploadistaError } from \"@uploadista/core/errors\";\nimport type { FlowServerShape } from \"@uploadista/core/flow\";\nimport type { UploadServerShape } from \"@uploadista/core/upload\";\nimport { Effect } from \"effect\";\nimport type {\n WebSocketConnection,\n WebSocketConnectionRequest,\n} from \"../websocket-routes\";\nimport {\n handleSubscribeToFlowEvents,\n handleUnsubscribeFromFlowEvents,\n} from \"./flow-websocket-handlers\";\nimport {\n handleSubscribeToUploadEvents,\n handleUnsubscribeFromUploadEvents,\n} from \"./upload-websocket-handlers\";\n\nexport type {\n WebSocketConnection,\n WebSocketConnectionRequest,\n} from \"../websocket-routes\";\n\n/**\n * Handles WebSocket connection opening\n * Subscribes to the appropriate events based on the connection request\n */\nexport const handleWebSocketOpen = (\n request: WebSocketConnectionRequest,\n uploadServer: UploadServerShape,\n flowServer: FlowServerShape,\n) => {\n const { connection, isFlowRoute, isUploadRoute, jobId, uploadId, eventId } =\n request;\n\n return Effect.gen(function* () {\n // Subscribe to flow events if this is a flow route\n if (isFlowRoute) {\n yield* handleSubscribeToFlowEvents(flowServer, jobId, connection);\n }\n\n // Subscribe to upload events if this is an upload route\n if (isUploadRoute) {\n yield* handleSubscribeToUploadEvents(uploadServer, uploadId, connection);\n }\n\n // Send connection confirmation\n connection.send(\n JSON.stringify({\n type: \"connection\",\n message: \"Uploadista WebSocket connected\",\n id: eventId,\n jobId,\n uploadId,\n timestamp: new Date().toISOString(),\n }),\n );\n }).pipe(\n Effect.catchAll((error) =>\n Effect.sync(() => {\n console.error(\"Error subscribing to events:\", error);\n const errorMessage =\n error instanceof UploadistaError\n ? error.body\n : \"Failed to subscribe to events\";\n connection.send(\n JSON.stringify({\n type: \"error\",\n message: errorMessage,\n code:\n error instanceof UploadistaError\n ? error.code\n : \"SUBSCRIPTION_ERROR\",\n }),\n );\n }),\n ),\n );\n};\n\n/**\n * Handles incoming WebSocket messages\n * Currently supports ping/pong for connection keep-alive\n */\nexport const handleWebSocketMessage = (\n message: string,\n connection: WebSocketConnection,\n) => {\n return Effect.sync(() => {\n try {\n const parsed = JSON.parse(message);\n if (parsed.type === \"ping\") {\n connection.send(\n JSON.stringify({\n type: \"pong\",\n timestamp: new Date().toISOString(),\n }),\n );\n }\n } catch (error) {\n console.error(\"Error handling WebSocket message:\", error);\n connection.send(\n JSON.stringify({\n type: \"error\",\n message: \"Invalid message format\",\n }),\n );\n }\n });\n};\n\n/**\n * Handles WebSocket connection closing\n * Unsubscribes from all events and cleans up resources\n */\nexport const handleWebSocketClose = (\n request: WebSocketConnectionRequest,\n uploadServer: UploadServerShape,\n flowServer: FlowServerShape,\n) => {\n const { isFlowRoute, isUploadRoute, jobId, uploadId } = request;\n\n return Effect.gen(function* () {\n // Unsubscribe from flow events if this was a flow route\n if (isFlowRoute) {\n yield* handleUnsubscribeFromFlowEvents(flowServer, jobId);\n }\n\n // Unsubscribe from upload events if this was an upload route\n if (isUploadRoute) {\n yield* handleUnsubscribeFromUploadEvents(uploadServer, uploadId);\n }\n }).pipe(\n Effect.catchAll((error) =>\n Effect.sync(() => {\n console.error(\n \"Error unsubscribing from events:\",\n error instanceof UploadistaError ? error.body : error,\n );\n }),\n ),\n );\n};\n\n/**\n * Handles WebSocket errors\n */\nexport const handleWebSocketError = (error: unknown, eventId?: string) => {\n return Effect.sync(() => {\n console.error(`WebSocket error for event ${eventId}:`, error);\n });\n};\n"],"mappings":"m2BA0DA,IAAa,EAAb,cAAsC,EAAQ,IAAI,mBAAmB,EAgClE,AAAC,GAQJ,MAAa,GACX,EAA0B,EAAE,GACM,CAClC,IAAM,EAAU,EAAO,SAAW,IAC5B,EAAM,EAAO,KAAO,KAGpB,EAAQ,IAAI,IAKZ,MAA2B,CAC/B,IAAM,EAAM,KAAK,KAAK,CACtB,IAAK,GAAM,CAAC,EAAO,KAAU,EAAM,SAAS,CACtC,EAAM,EAAM,UAAY,GAC1B,EAAM,OAAO,EAAM,EASn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,GAAI,CACa,KAAK,MAAM,EAAQ,CACvB,OAAS,QAClB,EAAW,KACT,KAAK,UAAU,CACb,KAAM,OACN,UAAW,IAAI,MAAM,CAAC,aAAa,CACpC,CAAC,CACH,OAEI,EAAO,CACd,QAAQ,MAAM,oCAAqC,EAAM,CACzD,EAAW,KACT,KAAK,UAAU,CACb,KAAM,QACN,QAAS,yBACV,CAAC,CACH,GAEH,CAOS,IACX,EACA,EACA,IACG,CACH,GAAM,CAAE,cAAa,gBAAe,QAAO,YAAa,EAExD,OAAO,EAAO,IAAI,WAAa,CAEzB,IACF,MAAO,GAAgCD,EAAY,EAAM,EAIvD,IACF,MAAO,GAAkCC,EAAc,EAAS,GAElE,CAAC,KACD,EAAO,SAAU,GACf,EAAO,SAAW,CAChB,QAAQ,MACN,mCACA,aAAiB,EAAkB,EAAM,KAAO,EACjD,EACD,CACH,CACF,EAMU,IAAwB,EAAgB,IAC5C,EAAO,SAAW,CACvB,QAAQ,MAAM,6BAA6B,EAAQ,GAAI,EAAM,EAC7D"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["oldestKey: string | null","NoAuthCacheServiceLive: Layer.Layer<AuthCacheService>","details: unknown","result: {\n status: number;\n code: string;\n message: string;\n details?: unknown;\n }","uploadServer","NoAuthContextServiceLive: Layer.Layer<AuthContextService>","flowServer","statusCode: number","errorCode: string","response: {\n error: string;\n code: string;\n timestamp: string;\n details?: unknown;\n }","authContext: AuthContext | null","authResult:\n | AuthContext\n | null\n | { _tag: \"TimeoutError\" }\n | { _tag: \"AuthError\"; error: unknown }","waitUntilLayers: Layer.Layer<any, never, never>[]","errorBody: Record<string, unknown>","errorResponse: StandardResponse","KNOWN_PLUGINS: Record<\n string,\n { packageName: string; variableName: string }\n>","lines: string[]","flowServer","uploadServer","flowServer","uploadServer"],"sources":["../src/cache.ts","../src/http-utils.ts","../src/layer-utils.ts","../src/service.ts","../src/core/http-handlers/flow-http-handlers.ts","../src/error-types.ts","../src/core/http-handlers/upload-http-handlers.ts","../src/core/http-handlers/http-handlers.ts","../src/core/server.ts","../src/core/create-type-safe-server.ts","../src/core/plugin-validation.ts","../src/core/websocket-handlers/flow-websocket-handlers.ts","../src/core/websocket-handlers/upload-websocket-handlers.ts","../src/core/websocket-handlers/websocket-handlers.ts"],"sourcesContent":["import { Context, Effect, Layer } from \"effect\";\nimport type { AuthContext } from \"./types\";\n\n/**\n * Configuration options for the auth cache.\n */\nexport type AuthCacheConfig = {\n /**\n * Maximum number of entries in the cache.\n * When exceeded, oldest entries are removed (LRU eviction).\n * @default 10000\n */\n maxSize?: number;\n\n /**\n * Time-to-live for cache entries in milliseconds.\n * Entries older than this will be automatically evicted.\n * @default 3600000 (1 hour)\n */\n ttl?: number;\n};\n\n/**\n * Cache entry with auth context and timestamp.\n */\ntype CacheEntry = {\n authContext: AuthContext;\n timestamp: number;\n};\n\n/**\n * Auth Cache Service\n *\n * Provides caching of authentication contexts for upload and flow jobs.\n * This allows subsequent operations (chunk uploads, flow continuations)\n * to reuse the auth context from the initial request without re-authenticating.\n *\n * @example\n * ```typescript\n * import { Effect } from \"effect\";\n * import { AuthCacheService } from \"@uploadista/server\";\n *\n * const handler = Effect.gen(function* () {\n * const authCache = yield* AuthCacheService;\n * const authContext = { userId: \"user-123\" };\n *\n * // Cache auth for upload\n * yield* authCache.set(\"upload-abc\", authContext);\n *\n * // Retrieve cached auth later\n * const cached = yield* authCache.get(\"upload-abc\");\n * console.log(cached?.userId); // \"user-123\"\n *\n * // Clear when done\n * yield* authCache.delete(\"upload-abc\");\n * });\n * ```\n */\nexport class AuthCacheService extends Context.Tag(\"AuthCacheService\")<\n AuthCacheService,\n {\n /**\n * Store an auth context for a job ID.\n */\n readonly set: (\n jobId: string,\n authContext: AuthContext,\n ) => Effect.Effect<void>;\n\n /**\n * Retrieve a cached auth context by job ID.\n * Returns null if not found or expired.\n */\n readonly get: (jobId: string) => Effect.Effect<AuthContext | null>;\n\n /**\n * Delete a cached auth context by job ID.\n */\n readonly delete: (jobId: string) => Effect.Effect<void>;\n\n /**\n * Clear all cached auth contexts.\n */\n readonly clear: () => Effect.Effect<void>;\n\n /**\n * Get the current number of cached entries.\n */\n readonly size: () => Effect.Effect<number>;\n }\n>() {}\n\n/**\n * Creates an AuthCacheService Layer with in-memory storage.\n *\n * @param config - Optional configuration for cache behavior\n * @returns Effect Layer providing AuthCacheService\n */\nexport const AuthCacheServiceLive = (\n config: AuthCacheConfig = {},\n): Layer.Layer<AuthCacheService> => {\n const maxSize = config.maxSize ?? 10000;\n const ttl = config.ttl ?? 3600000; // 1 hour default\n\n // In-memory cache storage\n const cache = new Map<string, CacheEntry>();\n\n /**\n * Evict expired entries based on TTL.\n */\n const evictExpired = (): void => {\n const now = Date.now();\n for (const [jobId, entry] of cache.entries()) {\n if (now - entry.timestamp > ttl) {\n cache.delete(jobId);\n }\n }\n };\n\n /**\n * Enforce max size limit using LRU eviction.\n * Removes oldest entry when cache exceeds max size.\n */\n const enforceSizeLimit = (): void => {\n if (cache.size <= maxSize) return;\n\n // Find and remove oldest entry\n let oldestKey: string | null = null;\n let oldestTime = Number.POSITIVE_INFINITY;\n\n for (const [jobId, entry] of cache.entries()) {\n if (entry.timestamp < oldestTime) {\n oldestTime = entry.timestamp;\n oldestKey = jobId;\n }\n }\n\n if (oldestKey) {\n cache.delete(oldestKey);\n }\n };\n\n return Layer.succeed(AuthCacheService, {\n set: (jobId: string, authContext: AuthContext) =>\n Effect.sync(() => {\n // Evict expired entries periodically\n if (cache.size % 100 === 0) {\n evictExpired();\n }\n\n cache.set(jobId, {\n authContext,\n timestamp: Date.now(),\n });\n\n // Enforce size limit after adding\n enforceSizeLimit();\n }),\n\n get: (jobId: string) =>\n Effect.sync(() => {\n const entry = cache.get(jobId);\n if (!entry) return null;\n\n // Check if expired\n const now = Date.now();\n if (now - entry.timestamp > ttl) {\n cache.delete(jobId);\n return null;\n }\n\n return entry.authContext;\n }),\n\n delete: (jobId: string) =>\n Effect.sync(() => {\n cache.delete(jobId);\n }),\n\n clear: () =>\n Effect.sync(() => {\n cache.clear();\n }),\n\n size: () =>\n Effect.sync(() => {\n return cache.size;\n }),\n });\n};\n\n/**\n * No-op implementation of AuthCacheService.\n * Does not cache anything - all operations are no-ops.\n * Used when caching is disabled or not needed.\n */\nexport const NoAuthCacheServiceLive: Layer.Layer<AuthCacheService> =\n Layer.succeed(AuthCacheService, {\n set: () => Effect.void,\n get: () => Effect.succeed(null),\n delete: () => Effect.void,\n clear: () => Effect.void,\n size: () => Effect.succeed(0),\n });\n","/**\n * Shared HTTP utilities for server adapters\n *\n * This module provides routing and error handling utilities used across\n * Hono, Express, and Fastify adapters for request parsing and response formatting.\n */\n\n/**\n * Parses URL segments from a pathname, filtering out empty segments.\n * Useful for extracting route components from request paths.\n *\n * @param pathname - The URL pathname (e.g., \"/uploadista/api/upload/abc123\")\n * @returns Array of non-empty path segments\n *\n * @example\n * ```typescript\n * const segments = parseUrlSegments(\"/uploadista/api/upload/abc123\");\n * // => [\"uploadista\", \"api\", \"upload\", \"abc123\"]\n * ```\n */\nexport const parseUrlSegments = (pathname: string): string[] => {\n return pathname.split(\"/\").filter(Boolean);\n};\n\n/**\n * Extracts the last segment from a URL pathname.\n *\n * @param pathname - The URL pathname to parse\n * @returns The last non-empty segment, or undefined if none exists\n *\n * @example\n * ```typescript\n * const id = getLastSegment(\"/uploadista/api/upload/abc123\");\n * // => \"abc123\"\n * ```\n */\nexport const getLastSegment = (pathname: string): string | undefined => {\n const segments = parseUrlSegments(pathname);\n return segments[segments.length - 1];\n};\n\n/**\n * Checks if a pathname includes a specific base path and API prefix.\n * Used to determine if a request should be handled by the Uploadista adapter.\n *\n * @param pathname - The request pathname\n * @param basePath - The base path configured for the adapter (e.g., \"uploadista\")\n * @returns true if the path includes `{basePath}/api/`\n *\n * @example\n * ```typescript\n * const isUploadistaPath = hasBasePath(\"/uploadista/api/upload\", \"uploadista\");\n * // => true\n * ```\n */\nexport const hasBasePath = (pathname: string, basePath: string): boolean => {\n return pathname.includes(`${basePath}/api/`);\n};\n\n/**\n * Removes the base path prefix and returns clean route segments.\n * Transforms \"/uploadista/api/upload/abc123\" → [\"upload\", \"abc123\"]\n *\n * @param pathname - The full request pathname\n * @param basePath - The base path to remove (e.g., \"uploadista\")\n * @returns Array of route segments without base path prefix\n *\n * @example\n * ```typescript\n * const route = getRouteSegments(\"/uploadista/api/upload/abc123\", \"uploadista\");\n * // => [\"upload\", \"abc123\"]\n * ```\n */\nexport const getRouteSegments = (\n pathname: string,\n basePath: string,\n): string[] => {\n return pathname.replace(`${basePath}/api/`, \"\").split(\"/\").filter(Boolean);\n};\n\n/**\n * Standard error handler for flow and job operations.\n * Maps application errors to appropriate HTTP status codes and error formats.\n *\n * Supports errors with `code`, `message`, `status`, and `details` properties.\n * Maps error codes to HTTP status codes (e.g., NOT_FOUND → 404, VALIDATION_ERROR → 400).\n *\n * @param error - The error object to handle (can be any type)\n * @returns Standardized error response with status, code, message, and optional details\n *\n * @example\n * ```typescript\n * import { handleFlowError } from \"@uploadista/server\";\n *\n * const response = handleFlowError({\n * code: \"FLOW_JOB_NOT_FOUND\",\n * message: \"Job not found\",\n * });\n * // => { status: 404, code: \"FLOW_JOB_NOT_FOUND\", message: \"Job not found\" }\n * ```\n */\nexport const handleFlowError = (\n error: unknown,\n): { status: number; code: string; message: string; details?: unknown } => {\n let status = 500;\n let code = \"UNKNOWN_ERROR\";\n let message = \"Internal server error\";\n let details: unknown;\n\n if (typeof error === \"object\" && error !== null) {\n const errorObj = error as Record<string, unknown>;\n\n // Extract error code\n if (\"code\" in errorObj && typeof errorObj.code === \"string\") {\n code = errorObj.code;\n }\n\n // Extract message\n if (\"message\" in errorObj && typeof errorObj.message === \"string\") {\n message = errorObj.message;\n } else if (\"body\" in errorObj && typeof errorObj.body === \"string\") {\n // Support UploadistaError's body property\n message = errorObj.body;\n }\n\n // Extract details if present\n if (\"details\" in errorObj) {\n details = errorObj.details;\n }\n\n // Map error codes to HTTP status codes\n if (\"status\" in errorObj && typeof errorObj.status === \"number\") {\n status = errorObj.status;\n } else if (\"code\" in errorObj) {\n // Fallback: derive status from common error codes\n switch (errorObj.code) {\n case \"FILE_NOT_FOUND\":\n case \"FLOW_JOB_NOT_FOUND\":\n case \"UPLOAD_ID_NOT_FOUND\":\n status = 404;\n break;\n case \"FLOW_JOB_ERROR\":\n case \"VALIDATION_ERROR\":\n case \"INVALID_METADATA\":\n case \"INVALID_LENGTH\":\n case \"ABORTED\":\n case \"INVALID_TERMINATION\":\n status = 400;\n break;\n case \"INVALID_OFFSET\":\n status = 409;\n break;\n case \"ERR_SIZE_EXCEEDED\":\n case \"ERR_MAX_SIZE_EXCEEDED\":\n status = 413;\n break;\n case \"FILE_NO_LONGER_EXISTS\":\n status = 410;\n break;\n case \"MISSING_OFFSET\":\n case \"INVALID_CONTENT_TYPE\":\n status = 403;\n break;\n default:\n status = 500;\n }\n }\n\n // Special handling for specific error messages\n if (\"message\" in errorObj && errorObj.message === \"Invalid JSON body\") {\n status = 400;\n code = \"VALIDATION_ERROR\";\n }\n }\n\n const result: {\n status: number;\n code: string;\n message: string;\n details?: unknown;\n } = {\n status,\n code,\n message,\n };\n\n if (details !== undefined) {\n result.details = details;\n }\n\n return result;\n};\n\n/**\n * Extracts job ID from URL segments for job status endpoint.\n * Expected URL format: `/uploadista/api/jobs/:jobId/status`\n *\n * @param urlSegments - Parsed URL segments (without base path)\n * @returns The job ID if found, or undefined\n *\n * @example\n * ```typescript\n * const jobId = extractJobIdFromStatus([\"jobs\", \"job-123\", \"status\"]);\n * // => \"job-123\"\n * ```\n */\nexport const extractJobIdFromStatus = (\n urlSegments: string[],\n): string | undefined => {\n return urlSegments[urlSegments.length - 2];\n};\n\n/**\n * Extracts job ID and node ID from URL segments for resume flow endpoint.\n * Expected URL format: `/uploadista/api/jobs/:jobId/resume/:nodeId`\n *\n * @param urlSegments - Parsed URL segments (without base path)\n * @returns Object with extracted jobId and nodeId (either can be undefined if not found)\n *\n * @example\n * ```typescript\n * const { jobId, nodeId } = extractJobAndNodeId([\n * \"jobs\",\n * \"job-123\",\n * \"resume\",\n * \"node-456\",\n * ]);\n * // => { jobId: \"job-123\", nodeId: \"node-456\" }\n * ```\n */\nexport const extractJobAndNodeId = (\n urlSegments: string[],\n): { jobId: string | undefined; nodeId: string | undefined } => {\n return {\n jobId: urlSegments[urlSegments.length - 3],\n nodeId: urlSegments[urlSegments.length - 1],\n };\n};\n\n/**\n * Extracts flow ID and storage ID from URL segments.\n * Expected URL format: `/uploadista/api/flow/:flowId/:storageId`\n *\n * Mutates the input array (removes last 2 elements).\n *\n * @param urlSegments - Parsed URL segments (will be mutated)\n * @returns Object with extracted flowId and storageId\n *\n * @example\n * ```typescript\n * const segments = [\"flow\", \"flow-123\", \"storage-456\"];\n * const { flowId, storageId } = extractFlowAndStorageId(segments);\n * // => { flowId: \"flow-123\", storageId: \"storage-456\" }\n * // segments is now [\"flow\"]\n * ```\n */\nexport const extractFlowAndStorageId = (\n urlSegments: string[],\n): { flowId: string | undefined; storageId: string | undefined } => {\n return {\n storageId: urlSegments.pop(),\n flowId: urlSegments.pop(),\n };\n};\n","import type { FlowProvider } from \"@uploadista/core/flow\";\nimport { flowServer } from \"@uploadista/core/flow\";\nimport {\n type BaseEventEmitterService,\n type BaseKvStoreService,\n flowEventEmitter,\n flowJobKvStore,\n type UploadFileDataStore,\n type UploadFileDataStores,\n type UploadFileKVStore,\n uploadEventEmitter,\n uploadFileKvStore,\n} from \"@uploadista/core/types\";\nimport { type UploadServer, uploadServer } from \"@uploadista/core/upload\";\nimport type { GenerateId } from \"@uploadista/core/utils\";\nimport { Layer } from \"effect\";\n\n/**\n * Configuration for creating upload server layers.\n * Specifies all dependencies needed by the upload server Effect Layer.\n *\n * @property kvStore - Key-value store for upload metadata\n * @property eventEmitter - Event emitter for upload progress events\n * @property dataStore - File data storage implementation\n * @property bufferedDataStore - Optional buffered storage for performance optimization\n * @property generateId - Optional custom ID generator (uses default if omitted)\n *\n * @example\n * ```typescript\n * import { createUploadServerLayer } from \"@uploadista/server\";\n *\n * const uploadLayerConfig: UploadServerLayerConfig = {\n * kvStore: redisKvStore,\n * eventEmitter: webSocketEventEmitter,\n * dataStore: s3DataStore,\n * };\n * ```\n */\nexport interface UploadServerLayerConfig {\n kvStore: Layer.Layer<BaseKvStoreService>;\n eventEmitter: Layer.Layer<BaseEventEmitterService>;\n dataStore: Layer.Layer<UploadFileDataStores, never, UploadFileKVStore>;\n bufferedDataStore?: Layer.Layer<\n UploadFileDataStore,\n never,\n UploadFileKVStore\n >;\n generateId?: Layer.Layer<GenerateId>;\n}\n\n/**\n * Configuration for creating flow server layers.\n * Specifies all dependencies needed by the flow processing server.\n *\n * @property kvStore - Key-value store for flow job metadata\n * @property eventEmitter - Event emitter for flow progress events\n * @property flowProvider - Factory function for creating flows\n * @property uploadServer - Upload server layer (used by flows for uploads)\n *\n * @example\n * ```typescript\n * import { createFlowServerLayer } from \"@uploadista/server\";\n *\n * const flowLayerConfig: FlowServerLayerConfig = {\n * kvStore: redisKvStore,\n * eventEmitter: webSocketEventEmitter,\n * flowProvider: createFlowsEffect,\n * uploadServer: uploadServerLayer,\n * };\n * ```\n */\nexport interface FlowServerLayerConfig {\n kvStore: Layer.Layer<BaseKvStoreService>;\n eventEmitter: Layer.Layer<BaseEventEmitterService>;\n flowProvider: Layer.Layer<FlowProvider>;\n uploadServer: Layer.Layer<UploadServer>;\n}\n\n/**\n * Creates the upload server layer with all dependencies composed.\n * This layer handles file uploads with chunked transfer, resumption, and metadata tracking.\n *\n * The created layer includes:\n * - Upload KV store (metadata tracking)\n * - Data store (file storage)\n * - Event emitter (progress notifications)\n * - Optional buffered data store (performance optimization)\n * - Optional custom ID generator\n *\n * @param config - Upload server layer configuration\n * @returns Effect Layer providing UploadServer\n *\n * @example\n * ```typescript\n * import { createUploadServerLayer } from \"@uploadista/server\";\n * import { Layer } from \"effect\";\n *\n * const uploadServerLayer = createUploadServerLayer({\n * kvStore: redisKvStore,\n * eventEmitter: webSocketEventEmitter,\n * dataStore: s3DataStore,\n * });\n *\n * // Use in application\n * const app = Layer.provide(appLogic, uploadServerLayer);\n * ```\n */\nexport const createUploadServerLayer = ({\n kvStore,\n eventEmitter,\n dataStore,\n bufferedDataStore,\n generateId,\n}: UploadServerLayerConfig) => {\n // Set up upload server dependencies\n const uploadFileKVStoreLayer = Layer.provide(uploadFileKvStore, kvStore);\n const uploadDataStoreLayer = Layer.provide(dataStore, uploadFileKVStoreLayer);\n const uploadBufferedDataStoreLayer = bufferedDataStore\n ? Layer.provide(bufferedDataStore, uploadFileKVStoreLayer)\n : Layer.empty;\n const uploadEventEmitterLayer = Layer.provide(\n uploadEventEmitter,\n eventEmitter,\n );\n\n const uploadServerLayers = Layer.mergeAll(\n uploadDataStoreLayer,\n uploadFileKVStoreLayer,\n uploadEventEmitterLayer,\n ...(generateId ? [generateId] : []),\n uploadBufferedDataStoreLayer,\n );\n\n return Layer.provide(uploadServer, uploadServerLayers);\n};\n\n/**\n * Creates the flow server layer with all dependencies composed.\n * This layer handles file processing workflows with multi-stage pipelines.\n *\n * The created layer includes:\n * - Flow job KV store (job metadata and state)\n * - Event emitter (progress notifications)\n * - Flow provider (flow definitions)\n * - Upload server (for uploads within flows)\n *\n * @param config - Flow server layer configuration\n * @returns Effect Layer providing FlowServer\n *\n * @example\n * ```typescript\n * import { createFlowServerLayer } from \"@uploadista/server\";\n * import { Layer } from \"effect\";\n *\n * const flowServerLayer = createFlowServerLayer({\n * kvStore: redisKvStore,\n * eventEmitter: webSocketEventEmitter,\n * flowProvider: createFlowsEffect,\n * uploadServer: uploadServerLayer,\n * });\n *\n * // Use in application\n * const app = Layer.provide(appLogic, flowServerLayer);\n * ```\n */\nexport const createFlowServerLayer = ({\n kvStore,\n eventEmitter,\n flowProvider,\n uploadServer,\n}: FlowServerLayerConfig) => {\n // Set up flow server dependencies\n const flowJobKVStoreLayer = Layer.provide(flowJobKvStore, kvStore);\n const flowEventEmitterLayer = Layer.provide(flowEventEmitter, eventEmitter);\n\n const flowServerLayers = Layer.mergeAll(\n flowProvider,\n flowEventEmitterLayer,\n flowJobKVStoreLayer,\n uploadServer,\n );\n\n return Layer.provide(flowServer, flowServerLayers);\n};\n","import { Context, Effect, Layer } from \"effect\";\nimport type { AuthContext } from \"./types\";\n\n/**\n * Authentication Context Service\n *\n * Provides access to the current authentication context throughout\n * the upload and flow processing pipeline. The service is provided\n * via Effect Layer and can be accessed using Effect.service().\n *\n * @example\n * ```typescript\n * import { Effect } from \"effect\";\n * import { AuthContextService } from \"@uploadista/server\";\n *\n * const uploadHandler = Effect.gen(function* () {\n * const authService = yield* AuthContextService;\n * const clientId = yield* authService.getClientId();\n * if (clientId) {\n * console.log(`Processing upload for client: ${clientId}`);\n * }\n * });\n * ```\n */\nexport class AuthContextService extends Context.Tag(\"AuthContextService\")<\n AuthContextService,\n {\n /**\n * Get the current client ID from auth context.\n * Returns null if no authentication context is available.\n */\n readonly getClientId: () => Effect.Effect<string | null>;\n\n /**\n * Get the current auth metadata.\n * Returns empty object if no authentication context or no metadata.\n */\n readonly getMetadata: () => Effect.Effect<Record<string, unknown>>;\n\n /**\n * Check if the current client has a specific permission.\n * Returns false if no authentication context or permission not found.\n */\n readonly hasPermission: (permission: string) => Effect.Effect<boolean>;\n\n /**\n * Get the full authentication context if available.\n * Returns null if no authentication context is available.\n */\n readonly getAuthContext: () => Effect.Effect<AuthContext | null>;\n }\n>() {}\n\n/**\n * Creates an AuthContextService Layer from an AuthContext.\n * This is typically called by adapters after successful authentication.\n *\n * @param authContext - The authentication context from middleware\n * @returns Effect Layer providing AuthContextService\n */\nexport const AuthContextServiceLive = (\n authContext: AuthContext | null,\n): Layer.Layer<AuthContextService> =>\n Layer.succeed(AuthContextService, {\n getClientId: () => Effect.succeed(authContext?.clientId ?? null),\n getMetadata: () => Effect.succeed(authContext?.metadata ?? {}),\n hasPermission: (permission: string) =>\n Effect.succeed(authContext?.permissions?.includes(permission) ?? false),\n getAuthContext: () => Effect.succeed(authContext),\n });\n\n/**\n * No-auth implementation of AuthContextService.\n * Returns null/empty values for all operations.\n * Used when no authentication middleware is configured (backward compatibility).\n */\nexport const NoAuthContextServiceLive: Layer.Layer<AuthContextService> =\n AuthContextServiceLive(null);\n","import { FlowServer } from \"@uploadista/core/flow\";\nimport { Effect } from \"effect\";\nimport { AuthCacheService } from \"../../cache\";\nimport { AuthContextService } from \"../../service\";\nimport type {\n CancelFlowRequest,\n CancelFlowResponse,\n GetFlowRequest,\n GetFlowResponse,\n GetJobStatusRequest,\n GetJobStatusResponse,\n PauseFlowRequest,\n PauseFlowResponse,\n ResumeFlowRequest,\n ResumeFlowResponse,\n RunFlowRequest,\n RunFlowResponse,\n} from \"../routes\";\n\nexport const handleGetFlow = ({ flowId }: GetFlowRequest) => {\n return Effect.gen(function* () {\n const flowServer = yield* FlowServer;\n // Access auth context if available\n const authService = yield* AuthContextService;\n const clientId = yield* authService.getClientId();\n\n if (clientId) {\n yield* Effect.logInfo(\n `[Flow] Getting flow data: ${flowId}, client: ${clientId}`,\n );\n }\n\n const flowData = yield* flowServer.getFlowData(flowId, clientId);\n\n return {\n status: 200,\n body: flowData,\n } as GetFlowResponse;\n });\n};\n\nexport const handleRunFlow = <TRequirements>({\n flowId,\n storageId,\n inputs,\n}: RunFlowRequest) => {\n return Effect.gen(function* () {\n const flowServer = yield* FlowServer;\n // Access auth context if available\n const authService = yield* AuthContextService;\n const authCache = yield* AuthCacheService;\n const clientId = yield* authService.getClientId();\n\n if (clientId) {\n yield* Effect.logInfo(\n `[Flow] Executing flow: ${flowId}, storage: ${storageId}, client: ${clientId}`,\n );\n yield* Effect.logInfo(JSON.stringify(inputs, null, 2));\n } else {\n yield* Effect.logInfo(\n `[Flow] Executing flow: ${flowId}, storage: ${storageId}`,\n );\n yield* Effect.logInfo(\n `[Flow] Inputs: ${JSON.stringify(inputs, null, 2)}`,\n );\n }\n\n // Run flow returns immediately with jobId\n yield* Effect.logInfo(`[Flow] Calling flowServer.runFlow...`);\n const result = yield* flowServer\n .runFlow<TRequirements>({\n flowId,\n storageId,\n clientId,\n inputs,\n })\n .pipe(\n Effect.tap(() =>\n Effect.logInfo(`[Flow] runFlow completed successfully`),\n ),\n Effect.tapError((error) =>\n Effect.logError(`[Flow] runFlow failed with error: ${error}`),\n ),\n );\n\n // Cache auth context for subsequent flow operations (continue, status)\n const authContext = yield* authService.getAuthContext();\n if (authContext) {\n yield* authCache.set(result.id, authContext);\n }\n\n yield* Effect.logInfo(`[Flow] Flow started with jobId: ${result.id}`);\n\n return {\n status: 200,\n body: result,\n } as RunFlowResponse;\n });\n};\n\nexport const handleJobStatus = ({ jobId }: GetJobStatusRequest) => {\n return Effect.gen(function* () {\n const flowServer = yield* FlowServer;\n // Access auth context if available\n const authService = yield* AuthContextService;\n const authCache = yield* AuthCacheService;\n const clientId = yield* authService.getClientId();\n\n if (!jobId) {\n throw new Error(\"No job id\");\n }\n\n if (clientId) {\n yield* Effect.logInfo(\n `[Flow] Getting job status: ${jobId}, client: ${clientId}`,\n );\n }\n\n const result = yield* flowServer.getJobStatus(jobId);\n\n // Clear cache if flow is completed or failed\n if (result.status === \"completed\" || result.status === \"failed\") {\n yield* authCache.delete(jobId);\n if (clientId) {\n yield* Effect.logInfo(\n `[Flow] Flow ${result.status}, cleared auth cache: ${jobId}`,\n );\n }\n }\n\n return {\n status: 200,\n body: result,\n } as GetJobStatusResponse;\n });\n};\n\nexport const handleResumeFlow = <TRequirements>({\n jobId,\n nodeId,\n newData,\n}: ResumeFlowRequest) => {\n return Effect.gen(function* () {\n const flowServer = yield* FlowServer;\n // Try to get auth from current request or cached auth\n const authService = yield* AuthContextService;\n const authCache = yield* AuthCacheService;\n\n // Try current auth first, fallback to cached auth\n let clientId = yield* authService.getClientId();\n if (!clientId) {\n const cachedAuth = yield* authCache.get(jobId);\n clientId = cachedAuth?.clientId ?? null;\n }\n\n if (clientId) {\n yield* Effect.logInfo(\n `[Flow] Continuing flow: jobId=${jobId}, nodeId=${nodeId}, client: ${clientId}`,\n );\n }\n\n if (newData === undefined) {\n throw new Error(\"Missing newData\");\n }\n\n const result = yield* flowServer.resumeFlow<TRequirements>({\n jobId,\n nodeId,\n newData,\n clientId,\n });\n\n // Clear cache if flow is completed or failed\n if (result.status === \"completed\" || result.status === \"failed\") {\n yield* authCache.delete(jobId);\n if (clientId) {\n yield* Effect.logInfo(\n `[Flow] Flow ${result.status}, cleared auth cache: ${jobId}`,\n );\n }\n }\n\n return {\n status: 200,\n body: result,\n } as ResumeFlowResponse;\n });\n};\nexport const handlePauseFlow = ({ jobId }: PauseFlowRequest) => {\n return Effect.gen(function* () {\n const flowServer = yield* FlowServer;\n // Try to get auth from current request or cached auth\n const authService = yield* AuthContextService;\n const authCache = yield* AuthCacheService;\n\n // Try current auth first, fallback to cached auth\n let clientId = yield* authService.getClientId();\n if (!clientId) {\n const cachedAuth = yield* authCache.get(jobId);\n clientId = cachedAuth?.clientId ?? null;\n }\n\n if (clientId) {\n yield* Effect.logInfo(\n `[Flow] Pausing flow: jobId=${jobId}, client: ${clientId}`,\n );\n }\n\n const result = yield* flowServer.pauseFlow(jobId, clientId);\n\n if (clientId) {\n yield* Effect.logInfo(\n `[Flow] Flow paused: ${jobId}, status: ${result.status}`,\n );\n }\n\n return {\n status: 200,\n body: result,\n } as PauseFlowResponse;\n });\n};\n\nexport const handleCancelFlow = ({ jobId }: CancelFlowRequest) => {\n return Effect.gen(function* () {\n const flowServer = yield* FlowServer;\n // Try to get auth from current request or cached auth\n const authService = yield* AuthContextService;\n const authCache = yield* AuthCacheService;\n\n if (!jobId) {\n throw new Error(\"No job id\");\n }\n\n // Try current auth first, fallback to cached auth\n let clientId = yield* authService.getClientId();\n if (!clientId) {\n const cachedAuth = yield* authCache.get(jobId);\n clientId = cachedAuth?.clientId ?? null;\n }\n\n if (clientId) {\n yield* Effect.logInfo(\n `[Flow] Cancelling flow: jobId=${jobId}, client: ${clientId}`,\n );\n }\n\n const result = yield* flowServer.cancelFlow(jobId, clientId);\n\n // Clear cache since flow is cancelled\n yield* authCache.delete(jobId);\n if (clientId) {\n yield* Effect.logInfo(\n `[Flow] Flow cancelled, cleared auth cache: ${jobId}`,\n );\n }\n\n return {\n status: 200,\n body: result,\n } as CancelFlowResponse;\n });\n};\n","import type { UploadistaError } from \"@uploadista/core/errors\";\n\n/**\n * Base adapter error class for HTTP adapters.\n * All adapter-specific errors should extend this class or one of its subclasses.\n *\n * @example\n * ```typescript\n * throw new AdapterError(\"Something went wrong\", 500, \"INTERNAL_ERROR\");\n * ```\n */\nexport class AdapterError extends Error {\n constructor(\n message: string,\n public readonly statusCode: number = 500,\n public readonly errorCode: string = \"INTERNAL_ERROR\",\n ) {\n super(message);\n this.name = \"AdapterError\";\n }\n}\n\n/**\n * Validation error - indicates invalid request data or parameters.\n * Returns HTTP 400 Bad Request status.\n *\n * @example\n * ```typescript\n * if (!isValidUploadId(id)) {\n * throw new ValidationError(\"Invalid upload ID format\");\n * }\n * ```\n */\nexport class ValidationError extends AdapterError {\n constructor(message: string) {\n super(message, 400, \"VALIDATION_ERROR\");\n this.name = \"ValidationError\";\n }\n}\n\n/**\n * Not found error - indicates a requested resource does not exist.\n * Returns HTTP 404 Not Found status.\n *\n * @example\n * ```typescript\n * if (!upload) {\n * throw new NotFoundError(\"Upload\");\n * }\n * ```\n */\nexport class NotFoundError extends AdapterError {\n constructor(resource: string) {\n super(`${resource} not found`, 404, \"NOT_FOUND\");\n this.name = \"NotFoundError\";\n }\n}\n\n/**\n * Bad request error - indicates a malformed request.\n * Returns HTTP 400 Bad Request status.\n * Similar to ValidationError but for request structure issues.\n *\n * @example\n * ```typescript\n * try {\n * const data = JSON.parse(body);\n * } catch {\n * throw new BadRequestError(\"Invalid JSON body\");\n * }\n * ```\n */\nexport class BadRequestError extends AdapterError {\n constructor(message: string) {\n super(message, 400, \"BAD_REQUEST\");\n this.name = \"BadRequestError\";\n }\n}\n\n/**\n * Creates a standardized error response object for AdapterError.\n * Includes error message, error code, and ISO timestamp.\n *\n * @param error - The AdapterError to format\n * @returns Standardized error response body\n *\n * @example\n * ```typescript\n * import { createErrorResponseBody } from \"@uploadista/server\";\n *\n * try {\n * // ... operation\n * } catch (err) {\n * const errorResponse = createErrorResponseBody(err);\n * res.status(err.statusCode).json(errorResponse);\n * }\n * ```\n */\nexport const createErrorResponseBody = (error: AdapterError) => ({\n error: error.message,\n code: error.errorCode,\n timestamp: new Date().toISOString(),\n});\n\n/**\n * Creates a standardized error response body from UploadistaError.\n * Formats core library errors for HTTP responses with optional details.\n *\n * @param error - The UploadistaError to format\n * @returns Standardized error response body with error, code, timestamp, and optional details\n *\n * @example\n * ```typescript\n * import { createUploadistaErrorResponseBody } from \"@uploadista/server\";\n *\n * try {\n * const result = yield* uploadServer.handleUpload(input);\n * } catch (err) {\n * if (err instanceof UploadistaError) {\n * const errorResponse = createUploadistaErrorResponseBody(err);\n * res.status(400).json(errorResponse);\n * }\n * }\n * ```\n */\nexport const createUploadistaErrorResponseBody = (error: UploadistaError) => {\n const response: {\n error: string;\n code: string;\n timestamp: string;\n details?: unknown;\n } = {\n error: error.body,\n code: error.code,\n timestamp: new Date().toISOString(),\n };\n\n if (error.details !== undefined) {\n response.details = error.details;\n }\n\n return response;\n};\n\n/**\n * Creates a generic error response body for unknown/unexpected errors.\n * Used as a fallback when error type cannot be determined.\n *\n * @param message - Error message to include in response (defaults to \"Internal server error\")\n * @returns Standardized error response body with generic INTERNAL_ERROR code\n *\n * @example\n * ```typescript\n * import { createGenericErrorResponseBody } from \"@uploadista/server\";\n *\n * try {\n * // ... operation\n * } catch (err) {\n * const errorResponse = createGenericErrorResponseBody(\n * err instanceof Error ? err.message : \"Unknown error\"\n * );\n * res.status(500).json(errorResponse);\n * }\n * ```\n */\nexport const createGenericErrorResponseBody = (\n message = \"Internal server error\",\n) => ({\n error: message,\n code: \"INTERNAL_ERROR\",\n timestamp: new Date().toISOString(),\n});\n","import { inputFileSchema } from \"@uploadista/core/types\";\nimport { UploadServer } from \"@uploadista/core/upload\";\nimport { isSupportedAlgorithm } from \"@uploadista/core/utils\";\nimport { MetricsService } from \"@uploadista/observability\";\nimport { Effect } from \"effect\";\nimport { AuthCacheService } from \"../../cache\";\nimport { ValidationError } from \"../../error-types\";\nimport { AuthContextService } from \"../../service\";\nimport type {\n CreateUploadRequest,\n CreateUploadResponse,\n GetCapabilitiesRequest,\n GetCapabilitiesResponse,\n GetUploadRequest,\n GetUploadResponse,\n UploadChunkRequest,\n UploadChunkResponse,\n} from \"../routes\";\n\nexport const handleCreateUpload = (req: CreateUploadRequest) =>\n Effect.gen(function* () {\n const server = yield* UploadServer;\n // Access auth context if available\n const authService = yield* AuthContextService;\n const authCache = yield* AuthCacheService;\n const clientId = yield* authService.getClientId();\n\n if (clientId) {\n yield* Effect.logInfo(`[Upload] Creating upload for client: ${clientId}`);\n }\n\n const parsedInputFile = yield* Effect.sync(() =>\n inputFileSchema.safeParse(req.data),\n );\n\n if (!parsedInputFile.success) {\n return yield* Effect.fail(\n new ValidationError(\"Invalid input file schema\"),\n );\n }\n\n // Validate checksum algorithm if provided\n if (\n parsedInputFile.data.checksumAlgorithm &&\n !isSupportedAlgorithm(parsedInputFile.data.checksumAlgorithm)\n ) {\n return yield* Effect.fail(\n new ValidationError(\n `Unsupported checksum algorithm: ${parsedInputFile.data.checksumAlgorithm}. Supported algorithms: sha256`,\n ),\n );\n }\n\n const fileCreated = yield* server.createUpload(\n parsedInputFile.data,\n clientId,\n );\n\n // Cache auth context for subsequent chunk uploads\n const authContext = yield* authService.getAuthContext();\n if (authContext) {\n yield* authCache.set(fileCreated.id, authContext);\n }\n\n if (clientId) {\n yield* Effect.logInfo(\n `[Upload] Upload created: ${fileCreated.id} for client: ${clientId}`,\n );\n }\n\n return {\n status: 200,\n body: fileCreated,\n } as CreateUploadResponse;\n });\n\nexport const handleGetCapabilities = ({ storageId }: GetCapabilitiesRequest) =>\n Effect.gen(function* () {\n const server = yield* UploadServer;\n const authService = yield* AuthContextService;\n const clientId = yield* authService.getClientId();\n\n const capabilities = yield* server.getCapabilities(storageId, clientId);\n\n return {\n status: 200,\n body: {\n storageId,\n capabilities,\n timestamp: new Date().toISOString(),\n },\n } as GetCapabilitiesResponse;\n });\n\nexport const handleGetUpload = ({ uploadId }: GetUploadRequest) =>\n Effect.gen(function* () {\n const server = yield* UploadServer;\n const fileResult = yield* server.getUpload(uploadId);\n\n return {\n status: 200,\n body: fileResult,\n } as GetUploadResponse;\n });\n\nexport const handleUploadChunk = (req: UploadChunkRequest) =>\n Effect.gen(function* () {\n const server = yield* UploadServer;\n // Try to get auth from current request or cached auth\n const authService = yield* AuthContextService;\n const authCache = yield* AuthCacheService;\n const metricsService = yield* MetricsService;\n\n const { uploadId, data } = req;\n\n // Try current auth first, fallback to cached auth\n let clientId = yield* authService.getClientId();\n let authMetadata = yield* authService.getMetadata();\n if (!clientId) {\n const cachedAuth = yield* authCache.get(uploadId);\n clientId = cachedAuth?.clientId ?? null;\n authMetadata = cachedAuth?.metadata ?? {};\n }\n\n if (clientId) {\n yield* Effect.logInfo(\n `[Upload] Uploading chunk for upload: ${uploadId}, client: ${clientId}`,\n );\n }\n\n const fileResult = yield* server.uploadChunk(uploadId, clientId, data);\n\n // Clear cache and record metrics if upload is complete\n if (fileResult.size && fileResult.offset >= fileResult.size) {\n yield* authCache.delete(uploadId);\n if (clientId) {\n yield* Effect.logInfo(\n `[Upload] Upload completed, cleared auth cache: ${uploadId}`,\n );\n }\n\n // Record upload metrics if we have organization ID\n\n if (clientId && fileResult.size) {\n yield* Effect.logInfo(\n `[Upload] Recording metrics for org: ${clientId}, size: ${fileResult.size}`,\n );\n yield* Effect.forkDaemon(\n metricsService.recordUpload(clientId, fileResult.size, authMetadata),\n );\n } else {\n yield* Effect.logWarning(\n `[Upload] Cannot record metrics - missing organizationId or size`,\n );\n }\n }\n\n if (clientId) {\n yield* Effect.logInfo(\n `[Upload] Chunk uploaded for upload: ${uploadId}, client: ${clientId}`,\n );\n }\n\n return {\n status: 200,\n body: fileResult,\n } as UploadChunkResponse;\n });\n","import { Effect } from \"effect\";\nimport type { UploadistaRequest, UploadistaResponse } from \"../routes\";\nimport {\n handleCancelFlow,\n handleGetFlow,\n handleJobStatus,\n handlePauseFlow,\n handleResumeFlow,\n handleRunFlow,\n} from \"./flow-http-handlers\";\nimport {\n handleCreateUpload,\n handleGetCapabilities,\n handleGetUpload,\n handleUploadChunk,\n} from \"./upload-http-handlers\";\n\nexport type { UploadistaRequest, UploadistaResponse } from \"../routes\";\n\nexport const handleUploadistaRequest = <TRequirements>(\n req: UploadistaRequest,\n) => {\n return Effect.gen(function* () {\n switch (req.type) {\n case \"create-upload\":\n return (yield* handleCreateUpload(req)) as UploadistaResponse;\n case \"get-capabilities\":\n return (yield* handleGetCapabilities(req)) as UploadistaResponse;\n case \"get-upload\":\n return (yield* handleGetUpload(req)) as UploadistaResponse;\n case \"upload-chunk\":\n return (yield* handleUploadChunk(req)) as UploadistaResponse;\n case \"get-flow\":\n return (yield* handleGetFlow(req)) as UploadistaResponse;\n case \"run-flow\":\n return (yield* handleRunFlow<TRequirements>(req)) as UploadistaResponse;\n case \"job-status\":\n return (yield* handleJobStatus(req)) as UploadistaResponse;\n case \"resume-flow\":\n return (yield* handleResumeFlow<TRequirements>(\n req,\n )) as UploadistaResponse;\n case \"pause-flow\":\n return (yield* handlePauseFlow(req)) as UploadistaResponse;\n case \"cancel-flow\":\n return (yield* handleCancelFlow(req)) as UploadistaResponse;\n case \"not-found\":\n return {\n status: 404,\n headers: { \"Content-Type\": \"application/json\" },\n body: { error: \"Not found\" },\n } as UploadistaResponse;\n case \"bad-request\":\n return {\n status: 400,\n body: { error: \"Bad request\", message: req.message },\n } as UploadistaResponse;\n case \"method-not-allowed\":\n return {\n status: 405,\n headers: { \"Content-Type\": \"application/json\" },\n body: { error: \"Method not allowed\" },\n } as UploadistaResponse;\n case \"unsupported-content-type\":\n return {\n status: 415,\n headers: { \"Content-Type\": \"application/json\" },\n body: { error: \"Unsupported content type\" },\n } as UploadistaResponse;\n }\n });\n};\n","import type { PluginLayer, UploadistaError } from \"@uploadista/core\";\nimport {\n type Flow,\n FlowProvider,\n FlowWaitUntil,\n kvCircuitBreakerStoreLayer,\n} from \"@uploadista/core/flow\";\nimport {\n createDataStoreLayer,\n type UploadFileDataStores,\n type UploadFileKVStore,\n} from \"@uploadista/core/types\";\nimport { GenerateIdLive } from \"@uploadista/core/utils\";\nimport { memoryEventBroadcaster } from \"@uploadista/event-broadcaster-memory\";\nimport { webSocketEventEmitter } from \"@uploadista/event-emitter-websocket\";\nimport { NodeSdkLive, NoOpMetricsServiceLive } from \"@uploadista/observability\";\nimport { Effect, Layer, ManagedRuntime } from \"effect\";\nimport type { z } from \"zod\";\nimport type { StandardResponse } from \"../adapter\";\nimport { AuthCacheServiceLive } from \"../cache\";\nimport { handleFlowError } from \"../http-utils\";\nimport { createFlowServerLayer, createUploadServerLayer } from \"../layer-utils\";\nimport { AuthContextServiceLive } from \"../service\";\nimport type { AuthContext } from \"../types\";\nimport { handleUploadistaRequest } from \"./http-handlers/http-handlers\";\nimport type { ExtractFlowPluginRequirements } from \"./plugin-types\";\nimport type { NotFoundResponse } from \"./routes\";\nimport type { UploadistaServer, UploadistaServerConfig } from \"./types\";\n\n/**\n * Creates the unified Uploadista server with framework-specific adapter.\n *\n * This is the single, unified API for creating an Uploadista server. It handles\n * all server initialization, layer composition, and runtime setup.\n *\n * ## Core Responsibilities\n *\n * The server handles:\n * - Layer composition (upload/flow servers, auth cache, metrics, plugins)\n * - Route parsing and matching\n * - Auth middleware execution with timeout protection\n * - Error handling and response formatting\n * - Effect program execution with optional tracing\n * - Plugin validation and dependency injection\n *\n * ## Plugin Validation\n *\n * The server supports two validation approaches:\n *\n * ### 1. Runtime Validation (Recommended for Most Cases)\n *\n * The server relies on Effect-TS's dependency injection to validate plugins\n * at runtime. If a required plugin is missing, Effect will fail with a clear\n * MissingService error.\n *\n * ```typescript\n * const server = await createUploadistaServer({\n * flows: getFlowById,\n * plugins: [sharpImagePlugin, zipPlugin],\n * dataStore: s3DataStore,\n * kvStore: redisKvStore,\n * adapter: honoAdapter({ ... })\n * });\n * // If plugins don't match flow requirements, Effect fails with clear error\n * ```\n *\n * ### 2. Compile-Time Validation (Optional)\n *\n * For IDE feedback during development, use the ValidatePlugins type utility:\n *\n * ```typescript\n * import {\n * createUploadistaServer,\n * ValidatePlugins,\n * ExtractFlowPluginRequirements\n * } from '@uploadista/server';\n *\n * // Extract requirements from flows\n * type Requirements = ExtractFlowPluginRequirements<typeof getFlowById>;\n *\n * // Define plugins\n * const plugins = [sharpImagePlugin, zipPlugin] as const;\n *\n * // Validate at compile time (optional, for IDE feedback)\n * type Validation = ValidatePlugins<typeof plugins, Requirements>;\n * // IDE shows error if plugins don't match requirements\n *\n * const server = await createUploadistaServer({\n * flows: getFlowById,\n * plugins,\n * // ...\n * });\n * ```\n *\n * ### 3. Early Runtime Validation (Optional)\n *\n * For better error messages before server starts:\n *\n * ```typescript\n * import { validatePluginsOrThrow } from '@uploadista/server/core';\n *\n * validatePluginsOrThrow({\n * plugins: [sharpImagePlugin],\n * expectedServices: ['ImagePlugin', 'ZipPlugin']\n * });\n * // Throws with helpful error message including import suggestions\n * ```\n *\n * ## Type Safety\n *\n * - Plugin requirements are inferred from flow definitions\n * - Effect-TS ensures dependencies are satisfied at runtime\n * - Type casting is intentional (see inline docs for rationale)\n * - Optional compile-time validation available via type utilities\n *\n * @template TContext - Framework-specific context type\n * @template TResponse - Framework-specific response type\n * @template TWebSocketHandler - WebSocket handler type (if supported)\n * @template TFlows - Flow function type with plugin requirements\n * @template TPlugins - Tuple of plugin layers provided\n *\n * @param config - Server configuration including adapter and business logic\n * @returns Promise resolving to server instance with handler and metadata\n *\n * @example Basic Usage\n * ```typescript\n * import { createUploadistaServer, honoAdapter } from \"@uploadista/server\";\n * import { sharpImagePlugin } from \"@uploadista/flow-images-sharp\";\n *\n * const server = await createUploadistaServer({\n * flows: getFlowById,\n * plugins: [sharpImagePlugin],\n * dataStore: { type: \"s3\", config: { bucket: \"uploads\" } },\n * kvStore: redisKvStore,\n * adapter: honoAdapter({\n * authMiddleware: async (c) => ({ clientId: \"user-123\" })\n * })\n * });\n *\n * // Use with Hono\n * app.all(\"/uploadista/*\", server.handler);\n * ```\n *\n * @example With Compile-Time Validation\n * ```typescript\n * import {\n * createUploadistaServer,\n * ValidatePlugins,\n * ExtractFlowPluginRequirements\n * } from \"@uploadista/server\";\n *\n * type Requirements = ExtractFlowPluginRequirements<typeof getFlowById>;\n * const plugins = [sharpImagePlugin, zipPlugin] as const;\n * type Validation = ValidatePlugins<typeof plugins, Requirements>;\n *\n * const server = await createUploadistaServer({\n * flows: getFlowById,\n * plugins,\n * // ... rest of config\n * });\n * ```\n *\n * @see ValidatePlugins - Compile-time plugin validation\n * @see ExtractFlowPluginRequirements - Extract requirements from flows\n * @see validatePluginRequirements - Runtime validation helper\n * @see API_DECISION_GUIDE.md - Complete guide for choosing validation approach\n */\nexport const createUploadistaServer = async <\n TContext,\n TResponse,\n TWebSocketHandler = unknown,\n TFlows extends (\n flowId: string,\n clientId: string | null,\n ) => Effect.Effect<\n // biome-ignore lint/suspicious/noExplicitAny: Flow requirements can be any plugin services\n Flow<z.ZodSchema<unknown>, z.ZodSchema<unknown>, any>,\n UploadistaError,\n // biome-ignore lint/suspicious/noExplicitAny: Flow return type allows any requirements\n any\n // biome-ignore lint/suspicious/noExplicitAny: Generic type constraint allows any flow function type with any requirements\n > = any,\n TPlugins extends readonly PluginLayer[] = readonly PluginLayer[],\n>({\n flows,\n dataStore,\n kvStore,\n // Default to an empty plugin list while preserving the generic type\n plugins = [] as unknown as TPlugins,\n eventEmitter,\n eventBroadcaster = memoryEventBroadcaster,\n withTracing = false,\n baseUrl: configBaseUrl = \"uploadista\",\n generateId = GenerateIdLive,\n metricsLayer,\n bufferedDataStore,\n adapter,\n authCacheConfig,\n circuitBreaker = true,\n}: UploadistaServerConfig<\n TContext,\n TResponse,\n TWebSocketHandler,\n TFlows,\n TPlugins\n>): Promise<UploadistaServer<TContext, TResponse, TWebSocketHandler>> => {\n // Default eventEmitter to webSocketEventEmitter with the provided eventBroadcaster\n const finalEventEmitter =\n eventEmitter ?? webSocketEventEmitter(eventBroadcaster);\n\n // Normalize baseUrl (remove trailing slash)\n const baseUrl = configBaseUrl.endsWith(\"/\")\n ? configBaseUrl.slice(0, -1)\n : configBaseUrl;\n\n type FlowReq = ExtractFlowPluginRequirements<TFlows>;\n\n // Create flow provider layer from flows function\n const flowProviderLayer = Layer.effect(\n FlowProvider,\n Effect.succeed({\n getFlow: (flowId: string, clientId: string | null) => {\n // Cast the flows function to match FlowProvider expectations\n // The context requirements will be provided at the layer level\n return flows(flowId, clientId) as Effect.Effect<\n Flow<z.ZodSchema<unknown>, z.ZodSchema<unknown>, FlowReq>,\n UploadistaError\n >;\n },\n }),\n );\n\n // Validate that eventEmitter is provided (required for upload/flow servers)\n if (!finalEventEmitter) {\n throw new Error(\n \"eventEmitter is required. Provide an event emitter layer in the configuration.\",\n );\n }\n\n // Create data store layer\n const dataStoreLayer: Layer.Layer<\n UploadFileDataStores,\n never,\n UploadFileKVStore\n > = await createDataStoreLayer(dataStore);\n\n // Create upload server layer\n const uploadServerLayer = createUploadServerLayer({\n kvStore,\n eventEmitter: finalEventEmitter,\n dataStore: dataStoreLayer,\n bufferedDataStore,\n generateId,\n });\n\n // Create flow server layer\n const flowServerLayer = createFlowServerLayer({\n kvStore,\n eventEmitter: finalEventEmitter,\n flowProvider: flowProviderLayer,\n uploadServer: uploadServerLayer,\n });\n\n // Create auth cache layer (always present, even if auth is not enabled)\n const authCacheLayer = AuthCacheServiceLive(authCacheConfig);\n\n // Metrics layer (defaults to NoOp if not provided)\n const effectiveMetricsLayer = metricsLayer ?? NoOpMetricsServiceLive;\n\n // Create circuit breaker store layer if enabled (uses the provided kvStore)\n const circuitBreakerStoreLayer = circuitBreaker\n ? kvCircuitBreakerStoreLayer.pipe(Layer.provide(kvStore))\n : null;\n\n /**\n * Merge all server layers including plugins.\n *\n * This combines the core server infrastructure (upload server, flow server,\n * metrics, auth cache, circuit breaker) with user-provided plugin layers.\n */\n const baseServerLayer = Layer.mergeAll(\n uploadServerLayer,\n flowServerLayer,\n effectiveMetricsLayer,\n authCacheLayer,\n ...plugins,\n );\n const serverLayerRaw = circuitBreakerStoreLayer\n ? Layer.merge(baseServerLayer, circuitBreakerStoreLayer)\n : baseServerLayer;\n\n /**\n * Type Casting Rationale for Plugin System\n *\n * The type assertion below is intentional and safe. This is not a bug or workaround,\n * but follows Effect-TS's design for dynamic dependency injection.\n *\n * ## Why Type Casting is Necessary\n *\n * 1. **Plugin Requirements are Dynamic**\n * Different flows require different plugins (ImagePlugin, ZipPlugin, etc.).\n * These requirements are only known when flows are loaded at runtime.\n * Flow A might need ImagePlugin, Flow B might need ZipPlugin.\n *\n * 2. **TypeScript's Static Limitation**\n * TypeScript cannot statically verify that all possible flow combinations\n * will have their requirements satisfied. The plugin array is typed as\n * `readonly PluginLayer[]` which could be any combination of plugins.\n *\n * 3. **Effect-TS Runtime Resolution**\n * Effect-TS is designed to resolve service requirements at runtime using\n * its dependency injection system. When a flow executes and accesses a service:\n *\n * ```typescript\n * const imagePlugin = yield* ImagePlugin;\n * ```\n *\n * Effect checks if ImagePlugin exists in the provided layer context.\n * If missing, Effect fails with a clear MissingService error.\n *\n * 4. **Layer Composition Guarantees**\n * Layer.mergeAll() combines all layers. At runtime, Effect ensures that\n * when a service is requested, it's either:\n * - Provided by one of the merged layers, OR\n * - Results in a MissingService error with the service name\n *\n * ## Safety Guarantees\n *\n * This pattern is safe because:\n *\n * 1. **Runtime Validation** (Optional but Recommended)\n * We provide validatePluginRequirements() that checks plugins before\n * server initialization, giving excellent error messages early.\n *\n * 2. **Effect's Built-in Validation**\n * If runtime validation is skipped, Effect will fail during flow execution\n * with a MissingService error containing the service identifier.\n *\n * 3. **Optional Compile-Time Validation**\n * Developers can use ValidatePlugins<> type utility for IDE feedback:\n *\n * ```typescript\n * type Validation = ValidatePlugins<typeof plugins, Requirements>;\n * // Shows compile error if plugins don't match requirements\n * ```\n *\n * 4. **No Silent Failures**\n * There's no scenario where missing plugins cause silent failures.\n * Either runtime validation catches it, or Effect fails with clear error.\n *\n * ## This is Effect-TS's Idiomatic Pattern\n *\n * Effect-TS separates compile-time structure from runtime resolution:\n * - Compile-time: Types ensure layer structure is correct\n * - Runtime: Effect resolves actual dependencies and fails if missing\n *\n * The type system provides structure and IDE support, while Effect's\n * runtime handles actual requirement resolution.\n *\n * ## Further Reading\n *\n * - Effect-TS Context Management: https://effect.website/docs/guides/context-management\n * - Runtime Validation: See plugin-validation.ts for helper functions\n * - Type Utilities: See plugin-types.ts for compile-time validation\n *\n * @see validatePluginRequirements - Runtime validation helper\n * @see ValidatePlugins - Compile-time validation type utility\n */\n const serverLayer = serverLayerRaw as unknown as Layer.Layer<\n // biome-ignore lint/suspicious/noExplicitAny: Dynamic plugin requirements require any - see comprehensive explanation above\n any,\n never,\n never\n >;\n\n // Create a shared managed runtime from the server layer\n // This ensures all requests use the same layer instances (including event broadcaster)\n // ManagedRuntime properly handles scoped resources and provides convenient run methods\n\n const managedRuntime = ManagedRuntime.make(serverLayer);\n\n /**\n * Main request handler that processes HTTP requests through the adapter.\n * Delegates to adapter's httpHandler if provided, otherwise uses standard flow.\n */\n const handler = async <TRequirements>(ctx: TContext) => {\n // Fallback: Standard routing logic (for adapters without httpHandler)\n const program = Effect.gen(function* () {\n // Extract standard request from framework-specific request\n const uploadistaRequest = yield* adapter.extractRequest(ctx, { baseUrl });\n\n // Run auth middleware if provided\n let authContext: AuthContext | null = null;\n if (adapter.runAuthMiddleware) {\n const authMiddlewareWithTimeout = adapter.runAuthMiddleware(ctx).pipe(\n Effect.timeout(\"5 seconds\"),\n Effect.catchAll(() => {\n // Timeout error\n console.error(\"Auth middleware timeout exceeded (5 seconds)\");\n return Effect.succeed({\n _tag: \"TimeoutError\" as const,\n } as const);\n }),\n Effect.catchAllCause((cause) => {\n // Other errors\n console.error(\"Auth middleware error:\", cause);\n return Effect.succeed({\n _tag: \"AuthError\" as const,\n error: cause,\n } as const);\n }),\n );\n\n const authResult:\n | AuthContext\n | null\n | { _tag: \"TimeoutError\" }\n | { _tag: \"AuthError\"; error: unknown } =\n yield* authMiddlewareWithTimeout;\n\n // Handle timeout\n if (\n authResult &&\n typeof authResult === \"object\" &&\n \"_tag\" in authResult &&\n authResult._tag === \"TimeoutError\"\n ) {\n const errorResponse: StandardResponse = {\n status: 503,\n headers: { \"Content-Type\": \"application/json\" },\n body: {\n error: \"Authentication service unavailable\",\n message:\n \"Authentication took too long to respond. Please try again.\",\n },\n };\n return yield* adapter.sendResponse(errorResponse, ctx);\n }\n\n // Handle auth error\n if (\n authResult &&\n typeof authResult === \"object\" &&\n \"_tag\" in authResult &&\n authResult._tag === \"AuthError\"\n ) {\n const errorResponse: StandardResponse = {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n body: {\n error: \"Internal Server Error\",\n message: \"An error occurred during authentication\",\n },\n };\n return yield* adapter.sendResponse(errorResponse, ctx);\n }\n\n // Handle authentication failure (null result)\n if (authResult === null) {\n const errorResponse: StandardResponse = {\n status: 401,\n headers: { \"Content-Type\": \"application/json\" },\n body: {\n error: \"Unauthorized\",\n message: \"Invalid credentials\",\n },\n };\n return yield* adapter.sendResponse(errorResponse, ctx);\n }\n\n authContext = authResult;\n }\n\n // Create auth context layer for this request\n const authContextLayer = AuthContextServiceLive(authContext);\n\n // Extract waitUntil callback if available (for Cloudflare Workers)\n // This must be extracted per-request since it comes from the framework context\n // biome-ignore lint/suspicious/noExplicitAny: Layer array needs to accept any service type from waitUntil\n const waitUntilLayers: Layer.Layer<any, never, never>[] = [];\n if (adapter.extractWaitUntil) {\n const waitUntilCallback = adapter.extractWaitUntil(ctx);\n if (waitUntilCallback) {\n waitUntilLayers.push(Layer.succeed(FlowWaitUntil, waitUntilCallback));\n }\n }\n\n // Combine auth context, auth cache, metrics layers, plugins, circuit breaker, and waitUntil\n // This ensures that flow nodes have access to all required services\n const baseRequestContextLayer = Layer.mergeAll(\n authContextLayer,\n authCacheLayer,\n effectiveMetricsLayer,\n ...plugins,\n ...waitUntilLayers,\n );\n const requestContextLayer = circuitBreakerStoreLayer\n ? Layer.merge(baseRequestContextLayer, circuitBreakerStoreLayer)\n : baseRequestContextLayer;\n\n // Check for baseUrl/api/ prefix\n if (uploadistaRequest.type === \"not-found\") {\n const notFoundResponse: NotFoundResponse = {\n type: \"not-found\",\n status: 404,\n headers: { \"Content-Type\": \"application/json\" },\n body: { error: \"Not found\" },\n };\n return yield* adapter.sendResponse(notFoundResponse, ctx);\n }\n\n // Handle the request\n const response = yield* handleUploadistaRequest<TRequirements>(\n uploadistaRequest,\n ).pipe(Effect.provide(requestContextLayer));\n\n return yield* adapter.sendResponse(response, ctx);\n }).pipe(\n // Catch all errors and format them appropriately\n Effect.catchAll((error: unknown) => {\n const errorInfo = handleFlowError(error);\n const errorBody: Record<string, unknown> = {\n code: errorInfo.code,\n message: errorInfo.message,\n };\n if (errorInfo.details !== undefined) {\n errorBody.details = errorInfo.details;\n }\n const errorResponse: StandardResponse = {\n status: errorInfo.status,\n headers: { \"Content-Type\": \"application/json\" },\n body: errorBody,\n };\n return adapter.sendResponse(errorResponse, ctx);\n }),\n );\n\n // Use the shared managed runtime instead of creating a new one per request\n if (withTracing) {\n return managedRuntime.runPromise(\n program.pipe(Effect.provide(NodeSdkLive)),\n );\n }\n return managedRuntime.runPromise(program);\n };\n\n // Create WebSocket handler using the shared managed runtime\n const websocketHandler = await managedRuntime.runPromise(\n adapter.webSocketHandler({\n baseUrl,\n }),\n );\n\n return {\n handler,\n websocketHandler,\n baseUrl,\n dispose: () => managedRuntime.dispose(),\n };\n};\n","import type {\n PluginServices,\n PluginTuple,\n TypeSafeFlowFunction,\n ValidatePlugins,\n} from \"./plugin-types\";\nimport { createUploadistaServer } from \"./server\";\nimport type { UploadistaServer, UploadistaServerConfig } from \"./types\";\n\n/**\n * Type-safe configuration for Uploadista server with compile-time plugin validation.\n *\n * This configuration extends the base UploadistaServerConfig with stricter typing\n * that validates plugins match flow requirements at compile time.\n *\n * @template TContext - Framework-specific request context type\n * @template TResponse - Framework-specific response type\n * @template TWebSocket - Framework-specific WebSocket handler type\n * @template TPlugins - Tuple of plugin layers provided to the server\n * @template TFlowRequirements - Union of plugin services required by flows\n */\nexport type TypeSafeServerConfig<\n TContext,\n TResponse,\n TWebSocket,\n TPlugins extends PluginTuple,\n TFlowRequirements = PluginServices<TPlugins>,\n> = Omit<\n UploadistaServerConfig<TContext, TResponse, TWebSocket>,\n \"flows\" | \"plugins\"\n> & {\n /**\n * Tuple of plugin layers that provide services to flows.\n * The plugins must satisfy all requirements declared by the flows.\n */\n plugins: TPlugins;\n\n /**\n * Type-safe flow function with explicit requirements.\n * TypeScript validates that all required plugins are provided.\n */\n flows: TypeSafeFlowFunction<TFlowRequirements>;\n\n /**\n * Compile-time validation that plugins satisfy flow requirements.\n * If this field has type errors, required plugins are missing.\n */\n __validate?: ValidatePlugins<TPlugins, TFlowRequirements>;\n};\n\n/**\n * @deprecated Use `createUploadistaServer` with optional type utilities instead.\n *\n * This function is deprecated in favor of the unified `createUploadistaServer` API.\n * The new approach separates validation concerns from server creation, making the\n * API simpler while still providing compile-time validation when desired.\n *\n * ## Migration Guide\n *\n * ### Old Approach (Deprecated)\n * ```typescript\n * import { createTypeSafeServer } from \"@uploadista/server\";\n *\n * const server = await createTypeSafeServer({\n * plugins: [sharpImagePlugin] as const,\n * flows: myFlowFunction,\n * // ...\n * });\n * ```\n *\n * ### New Approach (Recommended)\n *\n * **Option 1: Runtime validation only (simplest)**\n * ```typescript\n * import { createUploadistaServer } from \"@uploadista/server\";\n *\n * const server = await createUploadistaServer({\n * plugins: [sharpImagePlugin, zipPlugin],\n * flows: myFlowFunction,\n * // ... Effect validates at runtime\n * });\n * ```\n *\n * **Option 2: With compile-time validation (optional)**\n * ```typescript\n * import {\n * createUploadistaServer,\n * ValidatePlugins,\n * ExtractFlowPluginRequirements\n * } from \"@uploadista/server\";\n *\n * type Requirements = ExtractFlowPluginRequirements<typeof myFlowFunction>;\n * const plugins = [sharpImagePlugin, zipPlugin] as const;\n * type Validation = ValidatePlugins<typeof plugins, Requirements>;\n * // IDE shows error if plugins don't match requirements\n *\n * const server = await createUploadistaServer({\n * plugins,\n * flows: myFlowFunction,\n * // ...\n * });\n * ```\n *\n * ## Why This Changed\n *\n * 1. **Simpler API**: One function instead of two reduces confusion\n * 2. **Separation of Concerns**: Validation is now optional and separate\n * 3. **Better Flexibility**: Choose validation approach per use case\n * 4. **Clearer Intent**: Explicit validation via type utilities\n * 5. **Same Safety**: Effect-TS still validates at runtime\n *\n * The new approach trusts Effect-TS's design for dynamic dependency injection\n * while providing optional compile-time validation through type utilities.\n *\n * @see createUploadistaServer - The unified server creation API\n * @see ValidatePlugins - Compile-time validation type utility\n * @see ExtractFlowPluginRequirements - Extract requirements from flows\n * @see API_DECISION_GUIDE.md - Complete migration and usage guide\n *\n * @template TContext - Framework-specific request context type\n * @template TResponse - Framework-specific response type\n * @template TWebSocket - Framework-specific WebSocket handler type\n * @template TPlugins - Tuple of plugin layers\n * @template TFlowRequirements - Union of services required by flows\n *\n * @param config - Type-safe server configuration\n * @returns Promise resolving to UploadistaServer instance\n */\nexport async function createTypeSafeServer<\n TContext,\n TResponse,\n TWebSocket = unknown,\n TPlugins extends PluginTuple = PluginTuple,\n TFlowRequirements = PluginServices<TPlugins>,\n>(\n config: TypeSafeServerConfig<\n TContext,\n TResponse,\n TWebSocket,\n TPlugins,\n TFlowRequirements\n > &\n // Enforce validation at function call site\n (ValidatePlugins<TPlugins, TFlowRequirements> extends true\n ? object\n : ValidatePlugins<TPlugins, TFlowRequirements>),\n): Promise<UploadistaServer<TContext, TResponse, TWebSocket>> {\n return createUploadistaServer(config);\n}\n\n/**\n * Helper function to define flow functions with explicit type requirements.\n * Provides better type inference and autocomplete for plugin services.\n *\n * @template TRequirements - Union of plugin services this flow needs\n *\n * @param fn - The flow function implementation\n * @returns The same function with explicit type annotation\n *\n * @example\n * ```typescript\n * import { ImagePlugin } from \"@uploadista/core/flow\";\n * import { defineFlow } from \"@uploadista/server\";\n *\n * // Explicitly declare that this flow requires ImagePlugin\n * const imageProcessingFlow = defineFlow<ImagePlugin>((flowId, clientId) =>\n * Effect.gen(function* () {\n * const imageService = yield* ImagePlugin; // Autocomplete works!\n * const optimized = yield* imageService.optimize(data, { quality: 80 });\n * return createFlow({ ... });\n * })\n * );\n * ```\n */\nexport function defineFlow<TRequirements = never>(\n fn: TypeSafeFlowFunction<TRequirements>,\n): TypeSafeFlowFunction<TRequirements> {\n return fn;\n}\n\n/**\n * Helper to create a flow that requires no plugins.\n * Useful for simple flows that only use built-in functionality.\n *\n * @example\n * ```typescript\n * import { defineSimpleFlow } from \"@uploadista/server\";\n *\n * const simpleFlow = defineSimpleFlow((flowId, clientId) =>\n * Effect.succeed(createFlow({\n * id: \"simple\",\n * nodes: [],\n * edges: [],\n * inputSchema: myInputSchema,\n * outputSchema: myOutputSchema\n * }))\n * );\n * ```\n */\nexport function defineSimpleFlow(\n fn: TypeSafeFlowFunction<never>,\n): TypeSafeFlowFunction<never> {\n return fn;\n}\n","/**\n * Runtime plugin validation utilities.\n *\n * This module provides runtime validation to ensure that all plugins required\n * by flows are actually provided to the server. While Effect-TS will catch\n * missing dependencies at runtime, this validation provides better error messages\n * and fails fast during server initialization.\n *\n * @module plugin-validation\n */\n\nimport type { PluginLayer } from \"@uploadista/core\";\nimport { Effect } from \"effect\";\n\n/**\n * Result of plugin validation.\n */\nexport type PluginValidationResult =\n | {\n success: true;\n }\n | {\n success: false;\n required: string[];\n provided: string[];\n missing: string[];\n suggestions: Array<{\n name: string;\n packageName: string;\n importStatement: string;\n }>;\n };\n\n/**\n * Known plugin mapping for generating helpful error messages.\n *\n * This maps service identifiers to their package names and variable names\n * for generating import suggestions.\n */\nconst KNOWN_PLUGINS: Record<\n string,\n { packageName: string; variableName: string }\n> = {\n ImagePlugin: {\n packageName: \"@uploadista/flow-images-sharp\",\n variableName: \"sharpImagePlugin\",\n },\n ImageAiPlugin: {\n packageName: \"@uploadista/flow-images-replicate\",\n variableName: \"replicateImagePlugin\",\n },\n ZipPlugin: {\n packageName: \"@uploadista/flow-utility-zipjs\",\n variableName: \"zipPlugin\",\n },\n CredentialProvider: {\n packageName: \"@uploadista/core\",\n variableName: \"credentialProviderLayer\",\n },\n};\n\n/**\n * Extracts service identifier from a plugin layer.\n *\n * This attempts to identify the service provided by a layer using various\n * heuristics. The exact implementation depends on how Effect-TS exposes\n * layer metadata.\n *\n * @param layer - The plugin layer to inspect\n * @returns Service identifier string or null if not identifiable\n */\nfunction extractServiceIdentifier(layer: PluginLayer): string | null {\n // Attempt to extract service identifier from layer\n // Note: Effect-TS doesn't expose this information in a standard way,\n // so we use Symbol.toStringTag or constructor name as fallbacks\n\n try {\n // Try to get the service tag if available\n // biome-ignore lint/suspicious/noExplicitAny: Layer introspection requires accessing internal properties\n const layerAny = layer as any;\n\n // Check for common patterns in Effect layers\n if (layerAny._tag) {\n return layerAny._tag;\n }\n\n if (layerAny.constructor?.name) {\n return layerAny.constructor.name;\n }\n\n // Try to extract from the layer's context if available\n if (layerAny.context?.services) {\n const services = Array.from(layerAny.context.services.keys());\n if (services.length > 0) {\n // biome-ignore lint/suspicious/noExplicitAny: Service introspection requires accessing internal properties\n const firstService = services[0] as any;\n if (firstService.key) {\n return firstService.key;\n }\n }\n }\n\n return null;\n } catch {\n // If we can't extract the identifier, return null\n return null;\n }\n}\n\n/**\n * Extracts service identifiers from an array of plugin layers.\n *\n * @param plugins - Array of plugin layers\n * @returns Array of service identifier strings\n */\nexport function extractServiceIdentifiers(\n plugins: readonly PluginLayer[],\n): string[] {\n return plugins\n .map((plugin) => extractServiceIdentifier(plugin))\n .filter((id): id is string => id !== null);\n}\n\n/**\n * Validates that all required plugins are provided.\n *\n * This is a runtime validation function that checks if the plugins array\n * contains all services required by the flows. It's called during server\n * initialization to provide early, clear error messages.\n *\n * Note: This validation is best-effort because we can't reliably extract\n * requirements from flow functions at runtime without executing them.\n * The main validation happens via Effect-TS's dependency injection.\n *\n * @param config - Validation configuration\n * @returns Validation result with detailed error information if validation fails\n *\n * @example\n * ```typescript\n * const result = validatePluginRequirements({\n * plugins: [sharpImagePlugin, zipPlugin],\n * expectedServices: ['ImagePlugin', 'ZipPlugin']\n * });\n *\n * if (!result.success) {\n * console.error('Missing plugins:', result.missing);\n * console.error('Suggestions:', result.suggestions);\n * }\n * ```\n */\nexport function validatePluginRequirements(config: {\n plugins: readonly PluginLayer[];\n expectedServices?: string[];\n}): PluginValidationResult {\n const { plugins, expectedServices = [] } = config;\n\n // Extract identifiers from provided plugins\n const providedServices = extractServiceIdentifiers(plugins);\n\n // Check for missing services\n const missing = expectedServices.filter(\n (required) => !providedServices.includes(required),\n );\n\n if (missing.length === 0) {\n return { success: true };\n }\n\n // Generate suggestions for missing plugins\n const suggestions = missing\n .map((service) => {\n const knownPlugin = KNOWN_PLUGINS[service];\n if (!knownPlugin) {\n return null;\n }\n\n return {\n name: service,\n packageName: knownPlugin.packageName,\n importStatement: `import { ${knownPlugin.variableName} } from '${knownPlugin.packageName}';`,\n };\n })\n .filter((s): s is NonNullable<typeof s> => s !== null);\n\n return {\n success: false,\n required: expectedServices,\n provided: providedServices,\n missing,\n suggestions,\n };\n}\n\n/**\n * Creates a formatted error message for plugin validation failures.\n *\n * This generates a detailed, human-readable error message that includes:\n * - List of required plugins\n * - List of provided plugins\n * - List of missing plugins\n * - Import statements for missing plugins (if known)\n * - Example server configuration\n *\n * @param result - Failed validation result\n * @returns Formatted error message string\n *\n * @example\n * ```typescript\n * const result = validatePluginRequirements({ ... });\n * if (!result.success) {\n * const message = formatPluginValidationError(result);\n * throw new Error(message);\n * }\n * ```\n */\nexport function formatPluginValidationError(\n result: Extract<PluginValidationResult, { success: false }>,\n): string {\n const lines: string[] = [\n \"Server initialization failed: Missing required plugins\",\n \"\",\n `Required: ${result.required.join(\", \")}`,\n `Provided: ${result.provided.length > 0 ? result.provided.join(\", \") : \"(none)\"}`,\n `Missing: ${result.missing.join(\", \")}`,\n \"\",\n ];\n\n if (result.suggestions.length > 0) {\n lines.push(\"Add the missing plugins to your configuration:\");\n lines.push(\"\");\n for (const suggestion of result.suggestions) {\n lines.push(` ${suggestion.importStatement}`);\n }\n lines.push(\"\");\n lines.push(\" const server = await createUploadistaServer({\");\n lines.push(\n ` plugins: [${[...result.provided, ...result.missing.map((m) => KNOWN_PLUGINS[m]?.variableName || m)].join(\", \")}],`,\n );\n lines.push(\" // ...\");\n lines.push(\" });\");\n } else {\n lines.push(\"Note: Could not determine package names for missing plugins.\");\n lines.push(\"Please ensure all required plugin layers are provided.\");\n }\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Effect-based plugin validation that can be composed with other Effects.\n *\n * This provides an Effect-TS native way to validate plugins, allowing it\n * to be composed with other Effects in the server initialization pipeline.\n *\n * @param config - Validation configuration\n * @returns Effect that succeeds if validation passes, fails with UploadistaError if not\n *\n * @example\n * ```typescript\n * const validatedServer = Effect.gen(function* () {\n * yield* validatePluginRequirementsEffect({\n * plugins: [sharpImagePlugin],\n * expectedServices: ['ImagePlugin', 'ZipPlugin']\n * });\n *\n * return yield* createServerEffect(...);\n * });\n * ```\n */\nexport function validatePluginRequirementsEffect(config: {\n plugins: readonly PluginLayer[];\n expectedServices?: string[];\n}): Effect.Effect<void, Error> {\n return Effect.sync(() => {\n const result = validatePluginRequirements(config);\n\n if (!result.success) {\n const message = formatPluginValidationError(result);\n throw new Error(message);\n }\n });\n}\n\n/**\n * Validates plugin configuration at runtime during server initialization.\n *\n * This is a convenience function that performs validation and throws a\n * descriptive error if validation fails. Use this at the beginning of\n * createUploadistaServer to fail fast with clear error messages.\n *\n * @param config - Validation configuration\n * @throws Error with detailed message if validation fails\n *\n * @example\n * ```typescript\n * export const createUploadistaServer = async (config) => {\n * // Validate plugins early\n * validatePluginsOrThrow({\n * plugins: config.plugins,\n * expectedServices: ['ImagePlugin', 'ZipPlugin']\n * });\n *\n * // Continue with server creation...\n * };\n * ```\n */\nexport function validatePluginsOrThrow(config: {\n plugins: readonly PluginLayer[];\n expectedServices?: string[];\n}): void {\n const result = validatePluginRequirements(config);\n\n if (!result.success) {\n const message = formatPluginValidationError(result);\n throw new Error(message);\n }\n}\n","import type { FlowServerShape } from \"@uploadista/core/flow\";\nimport { Effect } from \"effect\";\nimport type { WebSocketConnection } from \"../websocket-routes\";\n\n/**\n * Handles subscription to flow events\n * Subscribes the WebSocket connection to receive real-time flow execution events\n */\nexport const handleSubscribeToFlowEvents = (\n flowServer: FlowServerShape,\n jobId: string | undefined,\n connection: WebSocketConnection,\n) => {\n return Effect.gen(function* () {\n if (!jobId) {\n yield* Effect.sync(() => {\n connection.send(\n JSON.stringify({\n type: \"error\",\n message: \"Job ID is required for flow event subscription\",\n code: \"MISSING_JOB_ID\",\n }),\n );\n });\n return;\n }\n\n yield* flowServer.subscribeToFlowEvents(jobId, connection);\n });\n};\n\n/**\n * Handles unsubscription from flow events\n * Removes the WebSocket connection from receiving flow events\n */\nexport const handleUnsubscribeFromFlowEvents = (\n flowServer: FlowServerShape,\n jobId: string | undefined,\n) => {\n return Effect.gen(function* () {\n if (!jobId) {\n return;\n }\n\n yield* flowServer.unsubscribeFromFlowEvents(jobId);\n });\n};\n","import type { UploadServerShape } from \"@uploadista/core/upload\";\nimport { Effect } from \"effect\";\nimport type { WebSocketConnection } from \"../websocket-routes\";\n\n/**\n * Handles subscription to upload events\n * Subscribes the WebSocket connection to receive real-time upload progress events\n */\nexport const handleSubscribeToUploadEvents = (\n uploadServer: UploadServerShape,\n uploadId: string | undefined,\n connection: WebSocketConnection,\n) => {\n return Effect.gen(function* () {\n if (!uploadId) {\n yield* Effect.sync(() => {\n connection.send(\n JSON.stringify({\n type: \"error\",\n message: \"Upload ID is required for upload event subscription\",\n code: \"MISSING_UPLOAD_ID\",\n }),\n );\n });\n return;\n }\n\n yield* uploadServer.subscribeToUploadEvents(uploadId, connection);\n });\n};\n\n/**\n * Handles unsubscription from upload events\n * Removes the WebSocket connection from receiving upload events\n */\nexport const handleUnsubscribeFromUploadEvents = (\n uploadServer: UploadServerShape,\n uploadId: string | undefined,\n) => {\n return Effect.gen(function* () {\n if (!uploadId) {\n return;\n }\n\n yield* uploadServer.unsubscribeFromUploadEvents(uploadId);\n });\n};\n","import { UploadistaError } from \"@uploadista/core/errors\";\nimport type { FlowServerShape } from \"@uploadista/core/flow\";\nimport type { UploadServerShape } from \"@uploadista/core/upload\";\nimport { Effect } from \"effect\";\nimport type {\n WebSocketConnection,\n WebSocketConnectionRequest,\n} from \"../websocket-routes\";\nimport {\n handleSubscribeToFlowEvents,\n handleUnsubscribeFromFlowEvents,\n} from \"./flow-websocket-handlers\";\nimport {\n handleSubscribeToUploadEvents,\n handleUnsubscribeFromUploadEvents,\n} from \"./upload-websocket-handlers\";\n\nexport type {\n WebSocketConnection,\n WebSocketConnectionRequest,\n} from \"../websocket-routes\";\n\n/**\n * Handles WebSocket connection opening\n * Subscribes to the appropriate events based on the connection request\n */\nexport const handleWebSocketOpen = (\n request: WebSocketConnectionRequest,\n uploadServer: UploadServerShape,\n flowServer: FlowServerShape,\n) => {\n const { connection, isFlowRoute, isUploadRoute, jobId, uploadId, eventId } =\n request;\n\n return Effect.gen(function* () {\n // Subscribe to flow events if this is a flow route\n if (isFlowRoute) {\n yield* handleSubscribeToFlowEvents(flowServer, jobId, connection);\n }\n\n // Subscribe to upload events if this is an upload route\n if (isUploadRoute) {\n yield* handleSubscribeToUploadEvents(uploadServer, uploadId, connection);\n }\n\n // Send connection confirmation\n connection.send(\n JSON.stringify({\n type: \"connection\",\n message: \"Uploadista WebSocket connected\",\n id: eventId,\n jobId,\n uploadId,\n timestamp: new Date().toISOString(),\n }),\n );\n }).pipe(\n Effect.catchAll((error) =>\n Effect.sync(() => {\n console.error(\"Error subscribing to events:\", error);\n const errorMessage =\n error instanceof UploadistaError\n ? error.body\n : \"Failed to subscribe to events\";\n connection.send(\n JSON.stringify({\n type: \"error\",\n message: errorMessage,\n code:\n error instanceof UploadistaError\n ? error.code\n : \"SUBSCRIPTION_ERROR\",\n }),\n );\n }),\n ),\n );\n};\n\n/**\n * Handles incoming WebSocket messages\n * Currently supports ping/pong for connection keep-alive\n */\nexport const handleWebSocketMessage = (\n message: string,\n connection: WebSocketConnection,\n) => {\n return Effect.sync(() => {\n try {\n const parsed = JSON.parse(message);\n if (parsed.type === \"ping\") {\n connection.send(\n JSON.stringify({\n type: \"pong\",\n timestamp: new Date().toISOString(),\n }),\n );\n }\n } catch (error) {\n console.error(\"Error handling WebSocket message:\", error);\n connection.send(\n JSON.stringify({\n type: \"error\",\n message: \"Invalid message format\",\n }),\n );\n }\n });\n};\n\n/**\n * Handles WebSocket connection closing\n * Unsubscribes from all events and cleans up resources\n */\nexport const handleWebSocketClose = (\n request: WebSocketConnectionRequest,\n uploadServer: UploadServerShape,\n flowServer: FlowServerShape,\n) => {\n const { isFlowRoute, isUploadRoute, jobId, uploadId } = request;\n\n return Effect.gen(function* () {\n // Unsubscribe from flow events if this was a flow route\n if (isFlowRoute) {\n yield* handleUnsubscribeFromFlowEvents(flowServer, jobId);\n }\n\n // Unsubscribe from upload events if this was an upload route\n if (isUploadRoute) {\n yield* handleUnsubscribeFromUploadEvents(uploadServer, uploadId);\n }\n }).pipe(\n Effect.catchAll((error) =>\n Effect.sync(() => {\n console.error(\n \"Error unsubscribing from events:\",\n error instanceof UploadistaError ? error.body : error,\n );\n }),\n ),\n );\n};\n\n/**\n * Handles WebSocket errors\n */\nexport const handleWebSocketError = (error: unknown, eventId?: string) => {\n return Effect.sync(() => {\n console.error(`WebSocket error for event ${eventId}:`, error);\n });\n};\n"],"mappings":"k4BA0DA,IAAa,EAAb,cAAsC,EAAQ,IAAI,mBAAmB,EAgClE,AAAC,GAQJ,MAAa,GACX,EAA0B,EAAE,GACM,CAClC,IAAM,EAAU,EAAO,SAAW,IAC5B,EAAM,EAAO,KAAO,KAGpB,EAAQ,IAAI,IAKZ,MAA2B,CAC/B,IAA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AAM,CAAC,aAAa,CACpC,CAAC,CACH,EACD,CAAC,KACD,EAAO,SAAU,GACf,EAAO,SAAW,CAChB,QAAQ,MAAM,+BAAgC,EAAM,CACpD,IAAM,EACJ,aAAiB,EACb,EAAM,KACN,gCACN,EAAW,KACT,KAAK,UAAU,CACb,KAAM,QACN,QAAS,EACT,KACE,aAAiB,EACb,EAAM,KACN,qBACP,CAAC,CACH,EACD,CACH,CACF,EAOU,IACX,EACA,IAEO,EAAO,SAAW,CACvB,GAAI,CACa,KAAK,MAAM,EAAQ,CACvB,OAAS,QAClB,EAAW,KACT,KAAK,UAAU,CACb,KAAM,OACN,UAAW,IAAI,MAAM,CAAC,aAAa,CACpC,CAAC,CACH,OAEI,EAAO,CACd,QAAQ,MAAM,oCAAqC,EAAM,CACzD,EAAW,KACT,KAAK,UAAU,CACb,KAAM,QACN,QAAS,yBACV,CAAC,CACH,GAEH,CAOS,IACX,EACA,EACA,IACG,CACH,GAAM,CAAE,cAAa,gBAAe,QAAO,YAAa,EAExD,OAAO,EAAO,IAAI,WAAa,CAEzB,IACF,MAAO,GAAgCD,EAAY,EAAM,EAIvD,IACF,MAAO,GAAkCC,EAAc,EAAS,GAElE,CAAC,KACD,EAAO,SAAU,GACf,EAAO,SAAW,CAChB,QAAQ,MACN,mCACA,aAAiB,EAAkB,EAAM,KAAO,EACjD,EACD,CACH,CACF,EAMU,IAAwB,EAAgB,IAC5C,EAAO,SAAW,CACvB,QAAQ,MAAM,6BAA6B,EAAQ,GAAI,EAAM,EAC7D"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@uploadista/server",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.0.18-beta.
|
|
4
|
+
"version": "0.0.18-beta.4",
|
|
5
5
|
"description": "Core Server package for Uploadista",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"author": "Uploadista",
|
|
@@ -20,23 +20,23 @@
|
|
|
20
20
|
}
|
|
21
21
|
},
|
|
22
22
|
"dependencies": {
|
|
23
|
-
"@uploadista/core": "0.0.18-beta.
|
|
24
|
-
"@uploadista/
|
|
25
|
-
"@uploadista/event-
|
|
26
|
-
"@uploadista/
|
|
23
|
+
"@uploadista/core": "0.0.18-beta.4",
|
|
24
|
+
"@uploadista/observability": "0.0.18-beta.4",
|
|
25
|
+
"@uploadista/event-broadcaster-memory": "0.0.18-beta.4",
|
|
26
|
+
"@uploadista/event-emitter-websocket": "0.0.18-beta.4"
|
|
27
27
|
},
|
|
28
28
|
"devDependencies": {
|
|
29
|
-
"@cloudflare/workers-types": "4.
|
|
29
|
+
"@cloudflare/workers-types": "4.20251126.0",
|
|
30
30
|
"@effect/vitest": "0.27.0",
|
|
31
31
|
"@types/express": "^5.0.0",
|
|
32
32
|
"@types/node": "24.10.1",
|
|
33
33
|
"effect": "3.19.6",
|
|
34
34
|
"tsd": "0.33.0",
|
|
35
|
-
"tsdown": "0.16.
|
|
35
|
+
"tsdown": "0.16.7",
|
|
36
36
|
"typescript": "5.9.3",
|
|
37
|
-
"vitest": "4.0.
|
|
37
|
+
"vitest": "4.0.14",
|
|
38
38
|
"zod": "4.1.13",
|
|
39
|
-
"@uploadista/typescript-config": "0.0.18-beta.
|
|
39
|
+
"@uploadista/typescript-config": "0.0.18-beta.4"
|
|
40
40
|
},
|
|
41
41
|
"peerDependencies": {
|
|
42
42
|
"effect": "^3.0.0",
|
package/src/core/server.ts
CHANGED
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
import type { PluginLayer, UploadistaError } from "@uploadista/core";
|
|
2
|
-
import {
|
|
2
|
+
import {
|
|
3
|
+
type Flow,
|
|
4
|
+
FlowProvider,
|
|
5
|
+
FlowWaitUntil,
|
|
6
|
+
kvCircuitBreakerStoreLayer,
|
|
7
|
+
} from "@uploadista/core/flow";
|
|
3
8
|
import {
|
|
4
9
|
createDataStoreLayer,
|
|
5
10
|
type UploadFileDataStores,
|
|
@@ -191,6 +196,7 @@ export const createUploadistaServer = async <
|
|
|
191
196
|
bufferedDataStore,
|
|
192
197
|
adapter,
|
|
193
198
|
authCacheConfig,
|
|
199
|
+
circuitBreaker = true,
|
|
194
200
|
}: UploadistaServerConfig<
|
|
195
201
|
TContext,
|
|
196
202
|
TResponse,
|
|
@@ -261,19 +267,27 @@ export const createUploadistaServer = async <
|
|
|
261
267
|
// Metrics layer (defaults to NoOp if not provided)
|
|
262
268
|
const effectiveMetricsLayer = metricsLayer ?? NoOpMetricsServiceLive;
|
|
263
269
|
|
|
270
|
+
// Create circuit breaker store layer if enabled (uses the provided kvStore)
|
|
271
|
+
const circuitBreakerStoreLayer = circuitBreaker
|
|
272
|
+
? kvCircuitBreakerStoreLayer.pipe(Layer.provide(kvStore))
|
|
273
|
+
: null;
|
|
274
|
+
|
|
264
275
|
/**
|
|
265
276
|
* Merge all server layers including plugins.
|
|
266
277
|
*
|
|
267
278
|
* This combines the core server infrastructure (upload server, flow server,
|
|
268
|
-
* metrics, auth cache) with user-provided plugin layers.
|
|
279
|
+
* metrics, auth cache, circuit breaker) with user-provided plugin layers.
|
|
269
280
|
*/
|
|
270
|
-
const
|
|
281
|
+
const baseServerLayer = Layer.mergeAll(
|
|
271
282
|
uploadServerLayer,
|
|
272
283
|
flowServerLayer,
|
|
273
284
|
effectiveMetricsLayer,
|
|
274
285
|
authCacheLayer,
|
|
275
286
|
...plugins,
|
|
276
287
|
);
|
|
288
|
+
const serverLayerRaw = circuitBreakerStoreLayer
|
|
289
|
+
? Layer.merge(baseServerLayer, circuitBreakerStoreLayer)
|
|
290
|
+
: baseServerLayer;
|
|
277
291
|
|
|
278
292
|
/**
|
|
279
293
|
* Type Casting Rationale for Plugin System
|
|
@@ -471,15 +485,18 @@ export const createUploadistaServer = async <
|
|
|
471
485
|
}
|
|
472
486
|
}
|
|
473
487
|
|
|
474
|
-
// Combine auth context, auth cache, metrics layers, plugins, and waitUntil
|
|
488
|
+
// Combine auth context, auth cache, metrics layers, plugins, circuit breaker, and waitUntil
|
|
475
489
|
// This ensures that flow nodes have access to all required services
|
|
476
|
-
const
|
|
490
|
+
const baseRequestContextLayer = Layer.mergeAll(
|
|
477
491
|
authContextLayer,
|
|
478
492
|
authCacheLayer,
|
|
479
493
|
effectiveMetricsLayer,
|
|
480
494
|
...plugins,
|
|
481
495
|
...waitUntilLayers,
|
|
482
496
|
);
|
|
497
|
+
const requestContextLayer = circuitBreakerStoreLayer
|
|
498
|
+
? Layer.merge(baseRequestContextLayer, circuitBreakerStoreLayer)
|
|
499
|
+
: baseRequestContextLayer;
|
|
483
500
|
|
|
484
501
|
// Check for baseUrl/api/ prefix
|
|
485
502
|
if (uploadistaRequest.type === "not-found") {
|
package/src/core/types.ts
CHANGED
|
@@ -295,6 +295,34 @@ export interface UploadistaServerConfig<
|
|
|
295
295
|
* ```
|
|
296
296
|
*/
|
|
297
297
|
authCacheConfig?: AuthCacheConfig;
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* Optional: Enable circuit breakers for flow nodes.
|
|
301
|
+
*
|
|
302
|
+
* When enabled (default), circuit breaker state is stored in the KV store,
|
|
303
|
+
* allowing circuit breaker state to be shared across multiple server instances
|
|
304
|
+
* in a cluster deployment.
|
|
305
|
+
*
|
|
306
|
+
* Set to `false` to disable circuit breakers entirely.
|
|
307
|
+
*
|
|
308
|
+
* @default true
|
|
309
|
+
*
|
|
310
|
+
* @example
|
|
311
|
+
* ```typescript
|
|
312
|
+
* // Circuit breakers enabled by default (uses the provided kvStore)
|
|
313
|
+
* const server = await createUploadistaServer({
|
|
314
|
+
* kvStore: redisKvStore,
|
|
315
|
+
* // circuitBreaker: true (default)
|
|
316
|
+
* });
|
|
317
|
+
*
|
|
318
|
+
* // Disable circuit breakers
|
|
319
|
+
* const server = await createUploadistaServer({
|
|
320
|
+
* kvStore: redisKvStore,
|
|
321
|
+
* circuitBreaker: false
|
|
322
|
+
* });
|
|
323
|
+
* ```
|
|
324
|
+
*/
|
|
325
|
+
circuitBreaker?: boolean;
|
|
298
326
|
}
|
|
299
327
|
|
|
300
328
|
/**
|
package/src/plugins-typing.ts
CHANGED
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
17
|
import type { Flow, UploadServer } from "@uploadista/core";
|
|
18
|
-
import type { ExtractLayerServices } from "@uploadista/core/flow
|
|
18
|
+
import type { ExtractLayerServices } from "@uploadista/core/flow";
|
|
19
19
|
import type { Effect, Layer } from "effect";
|
|
20
20
|
import type z from "zod";
|
|
21
21
|
|