@5minds/processcube_app_sdk 8.2.2 → 8.2.3-alpha.1

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.
@@ -1 +1 @@
1
- var U=Object.defineProperty;var me=Object.getOwnPropertyDescriptor;var Te=Object.getOwnPropertyNames;var ke=Object.prototype.hasOwnProperty;var ge=(e,t)=>{for(var s in t)U(e,s,{get:t[s],enumerable:!0})},we=(e,t,s,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Te(t))!ke.call(e,o)&&o!==s&&U(e,o,{get:()=>t[o],enumerable:!(n=me(t,o))||n.enumerable});return e};var Ee=e=>we(U({},"__esModule",{value:!0}),e);var tt={};ge(tt,{cancelReservedUserTask:()=>Ke,finishManualTask:()=>G,finishTask:()=>Ve,finishUntypedTask:()=>j,finishUserTask:()=>H,finishUserTaskAndGetNext:()=>ve,getActiveProcessInstances:()=>Ae,getAssignedUserTasksByIdentity:()=>Xe,getEngineClient:()=>Fe,getFlowNodeInstances:()=>ze,getFlowNodeInstancesByProcessInstanceId:()=>W,getFlowNodeInstancesTriggeredByFlowNodeInstanceIds:()=>q,getIdentity:()=>a,getProcessInstance:()=>Je,getProcessInstanceById:()=>L,getReservedUserTasksByIdentity:()=>qe,getTriggeredFlowNodeInstances:()=>et,getUserTasks:()=>ue,getWaitingUserTaskByFlowNodeInstanceId:()=>pe,getWaitingUserTasks:()=>Be,getWaitingUserTasksByCorrelationId:()=>We,getWaitingUserTasksByFlowNodeId:()=>Le,getWaitingUserTasksByProcessInstanceId:()=>De,navigateToUrl:()=>He,reserveUserTask:()=>$e,retryProcess:()=>Ze,retryProcessInstance:()=>$,startProcess:()=>je,terminateProcess:()=>Qe,terminateProcessInstance:()=>K,waitForProcessEnd:()=>Me,waitForUserTask:()=>Oe,withApplicationSdk:()=>Ge});module.exports=Ee(tt);var vt=require("only-server"),Bt=require("../common/index.cjs");var Z=require("chokidar"),J=require("esbuild"),z=require("jwt-decode"),ee=require("node:child_process"),x=require("node:fs"),p=require("node:path"),b=require("openid-client"),te=require("@5minds/processcube_engine_sdk");var V=require("@5minds/processcube_engine_client"),F=process.env.PROCESSCUBE_ENGINE_URL??"http://localhost:10560",r=new V.EngineClient(F);var Ce={token:"ZHVtbXlfdG9rZW4=",userId:"dummy_token"},_e=.85,R=["external_task.ts","external_task.js"],h=process.env.PROCESSCUBE_AUTHORITY_URL!==void 0,u=new te.Logger("processcube_app_sdk:external_task_adapter"),k={},M={},w,O=!1,se=6,Pe=3e5,Se=3e4,A=10,xe=3e4,Q=10,he=6e4;async function ne(e){if(e&&!(0,x.existsSync)(e))throw new Error(`Invalid customExternalTasksDirPath. The given path '${e}' does not exist`);b.custom.setHttpOptionsDefaults({timeout:1e5});let t=await ie();w=B(t),await ae(t);let s=be(e);(0,Z.watch)(s).on("add",async n=>{if(R.includes((0,p.basename)(n)))return v(n,s)}).on("change",async n=>{if(R.includes((0,p.basename)(n)))return Ne(n,s)}).on("unlink",async n=>{R.includes((0,p.basename)(n))&&re(n)}).on("error",n=>u.error(`Watcher error: ${n}`))}async function v(e,t){let s=(0,p.dirname)(e);if((await x.promises.readdir(s)).filter(l=>R.includes(l)).length>1){u.error(`Multiple external task files found in directory ${s}. Stopping all external task workers for this directory.`),k[s]&&re(e);return}let i=await ce(e),c=(0,p.relative)(t,s),d=de(c),f=(0,p.join)(__dirname,"lib/ExternalTaskWorkerProcess.cjs"),y=(0,ee.fork)(f,{env:{...process.env,PROCESSCUBE_ENGINE_URL:F}});k[s]=y,y.once("disconnect",()=>{delete k[s]}),y.on("error",l=>{u.error(`External Task Worker process error for ${d}`,{error:l,topic:d,workerDirectory:s})}),y.on("exit",(l,_)=>{if(u.info(`External Task Worker process exited for ${d}`,{code:l,signal:_,topic:d,workerDirectory:s}),delete k[s],l===3||l===4)if(Ue(s)){let P=M[s]?.count??1,S=Math.min(1e3*Math.pow(2,P-1),Se);u.info(`Scheduling restart for ${d} in ${S}ms (attempt ${P}/${se})`,{delay:S,restartCount:P,exitCode:l,topic:d,workerDirectory:s}),setTimeout(async()=>{try{if(h&&!O){u.info("Token refresh cycle is not active, restarting it before worker restart");let g=await ie();w=B(g),await ae(g)}await v(e,t)}catch(g){u.error(`Failed to restart External Task Worker process for ${d}`,{error:g,topic:d,workerDirectory:s})}},S)}else u.error(`External Task Worker process for ${d} reached maximum restart attempts`,{exitCode:l,topic:d,workerDirectory:s})}),y.send({action:"create",payload:{topic:d,identity:w,moduleString:i,workerPath:e}})}async function Ne(e,t){let s=(0,p.dirname)(e),n=k[s];if(!n)return v(e,t);let o=await ce(e),i=(0,p.relative)(t,s),c=de(i);n.send({action:"restart",payload:{topic:c,identity:w,moduleString:o,workerPath:e}})}function re(e){let t=(0,p.dirname)(e),s=k[t];s&&s.kill()}async function oe(){if(!h)return null;if(!process.env.PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_ID||!process.env.PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_SECRET){let n=new Error("Required environment variables PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_ID and PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_SECRET are missing. For help, please refer to our documentation on environment variables at: https://processcube.io/docs/app-sdk/samples/nextjs/external-task-adapter-with-nextjs#authority");throw u.error("Required environment variables PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_ID and PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_SECRET are missing",{err:n}),n}let e=await b.Issuer.discover(process.env.PROCESSCUBE_AUTHORITY_URL);return await new e.Client({client_id:process.env.PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_ID,client_secret:process.env.PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_SECRET}).grant({grant_type:"client_credentials",scope:"engine_etw"})}async function ie(){if(!h)return null;for(let e=1;e<=A;e++)try{return await oe()}catch(t){let s=Math.min(1e3*Math.pow(2,e-1),xe);if(u.error(`Failed to fetch initial token set (attempt ${e}/${A}), retrying in ${s}ms`,{error:t,attempt:e,delay:s}),e===A)throw t;await new Promise(n=>setTimeout(n,s))}return null}function B(e){if(!h||e===null)return Ce;let t=e.access_token,s=(0,z.jwtDecode)(t);return{token:e.access_token,userId:s.sub}}async function ae(e){if(!h||e===null||O)return;O=!0;let t=0,n=await Re(e)*_e*1e3,o=async()=>{try{let i=await oe();w=B(i);for(let[c,d]of Object.entries(k))try{d.send({action:"updateIdentity",payload:{identity:w}})}catch(f){u.warn(`Failed to send identity update to worker process ${c}`,{sendError:f})}t=0,setTimeout(o,n)}catch(i){t++;let c=Math.min(1e3*Math.pow(2,t-1),he);t<=Q?u.error(`Could not refresh identity (attempt ${t}/${Q}), retrying in ${c}ms`,{error:i,attempt:t,delay:c}):u.error(`Could not refresh identity (attempt ${t}), continuing to retry every ${c}ms`,{error:i,attempt:t,delay:c}),setTimeout(o,c)}};setTimeout(o,n)}async function ce(e){let t=await(0,J.build)({entryPoints:[e],write:!1,bundle:!0,platform:"node",target:"node18",format:"cjs",external:["@opentelemetry/api"]});if(t.errors.length>0)throw u.error(`Could not transpile file at '${e}'`,{errors:t.errors}),new Error(`Could not transpile file at '${e}'`);return t.warnings.length>0&&u.warn(`Transpiled file at '${e}' with warnings`,{warnings:t.warnings}),t.outputFiles[0].text}async function Re(e){let t=e.expires_in;if(!t&&e.expires_at&&(t=Math.floor(e.expires_at-Date.now()/1e3)),t===void 0)throw new Error("Could not determine the time until the access token for external task workers expires");return t}function de(e){return e.replace(/^\.\/+|\([^)]+\)|^\/*|\/*$/g,"").replace(/[\/]{2,}/g,"/")}function be(e){let t,s=[e,(0,p.join)(process.cwd(),"app"),(0,p.join)(process.cwd(),"src","app")];for(let n of s)if(n&&(0,x.existsSync)(n)){t=n;break}if(!t)throw new Error("Could not find external tasks directory");return t}function Ue(e){let t=Date.now(),s=M[e];return!s||t-s.timestamp>Pe?(M[e]={count:1,timestamp:t},!0):s.count>=se?!1:(s.count++,!0)}function Fe(){return r}var D=require("next-auth/jwt"),le=require("next/dist/compiled/@edge-runtime/cookies/index.js"),T=require("next/headers");async function a(){let e=await(0,D.getToken)({req:{cookies:await(0,T.cookies)(),headers:await(0,T.headers)()}});if(e?.expiresAt&&Date.now()>=e.expiresAt*1e3){let s=await fetch(`${process.env.NEXTAUTH_URL}/api/auth/session`,{method:"GET",headers:{"Content-Type":"application/json",cookie:(await(0,T.cookies)()).toString()}}),n=new le.ResponseCookies(s.headers);if(n.getAll().length){let o=!1;try{for(let i of n.getAll())(await(0,T.cookies)()).set(i.name,i.value,{...i})}catch{o=!0}if(e=await(0,D.getToken)({req:{cookies:o?n:await(0,T.cookies)(),headers:await(0,T.headers)()}}),e?.error)throw e.error}}if(!e?.accessToken||!e?.sub)throw new Error("AccessToken or Sub could not be determined!");return{token:e?.accessToken,userId:e?.sub}}var E=require("@5minds/processcube_engine_client");async function N(){try{return a()}catch{return}}async function L(e){let t=await N();return(await r.processInstances.query({processInstanceId:e},{identity:t,includeXml:!0})).processInstances[0]}async function W(e,t={sortSettings:{sortBy:E.DataModels.FlowNodeInstances.FlowNodeInstanceSortableColumns.createdAt,sortDir:"ASC"}}){return(await r.flowNodeInstances.query({processInstanceId:e},{...t,identity:t.identity??await N()})).flowNodeInstances}async function q(e){let t=await N();return(await r.flowNodeInstances.query({triggeredByFlowNodeInstance:e},{identity:t})).flowNodeInstances}async function $(e,t,s){let n=await N();await r.processInstances.retryProcessInstance(e,{flowNodeInstanceId:t,newStartToken:s,identity:n})}async function K(e){let t=await N();await r.processInstances.terminateProcessInstance(e,t)}async function Ae(e={options:{identity:!0}}){switch(e.options.identity){case!0:e.options.identity=await a();break;case!1:e.options.identity=void 0;break;case void 0:e.options.identity=await a();break}return await r.processInstances.query({...e?.query,state:E.DataModels.ProcessInstances.ProcessInstanceState.running},e?.options)}async function Me(e={},t=!0){let{processInstanceId:s}=e,n=typeof t=="boolean"?t==!0?await a():void 0:t;return new Promise(async(o,i)=>{let c=[],d=async f=>{if(s!==void 0&&f.processInstanceId!==s)return;let l=await r.processInstances.query({processInstanceId:f.processInstanceId},{identity:n});for(let _ of c)r.notification.removeSubscription(_,n);return l.totalCount===0?i(new Error(`Process with instance ID "${f.processInstanceId}" does not exist.`)):o(l.processInstances[0])};if(c.push(await r.notification.onProcessEnded(d,{identity:n})),c.push(await r.notification.onProcessError(d,{identity:n})),c.push(await r.notification.onProcessTerminated(d,{identity:n})),s){let f=await r.processInstances.query({processInstanceId:s,state:[E.DataModels.ProcessInstances.ProcessInstanceState.finished,E.DataModels.ProcessInstances.ProcessInstanceState.terminated,E.DataModels.ProcessInstances.ProcessInstanceState.error]},{identity:n});if(f.totalCount>0){for(let y of c)r.notification.removeSubscription(y,n);o(f.processInstances[0])}}})}var m=require("@5minds/processcube_engine_client"),I=require("../common/index.cjs");async function Oe(e={},t=!0){let{correlationId:s,processInstanceId:n,flowNodeId:o}=e,i=typeof t=="boolean"?t==!0?await a():void 0:t;return new Promise(async(c,d)=>{let f=await r.userTasks.onUserTaskWaiting(async l=>{let _=s!==void 0&&l.correlationId!==s,P=l.flowNodeInstanceId===void 0,S=n!==void 0&&l.processInstanceId!==n,g=o!==void 0&&l.flowNodeId!==o;if(_||P||S||g)return;let Y=await pe(l.flowNodeInstanceId,{identity:i});return r.notification.removeSubscription(f,i),Y===null?d(new Error(`UserTask with instance ID "${l.flowNodeInstanceId}" does not exist.`)):c(Y)},{identity:i}),y=await ue({correlationId:s,processInstanceId:n,flowNodeId:o,state:m.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:i});y.userTasks.length>0&&(r.notification.removeSubscription(f,i),c(y.userTasks[0]))})}async function ve(e,t={},s={},n=!0){let o=typeof n=="boolean"?n==!0?await a():void 0:n;await r.userTasks.finishUserTask(e,s,o);let i={state:m.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended,...t},c=await r.userTasks.query(i,{identity:o});return(0,I.mapUserTask)(c.userTasks[0])}async function ue(e,t={identity:!0}){switch(t?.identity){case!0:t.identity=await a();break;case!1:t.identity=void 0;break;case void 0:t.identity=await a();break}let s=await r.userTasks.query(e,t);return(0,I.mapUserTaskList)(s)}async function Be(e={identity:!0}){switch(e?.identity){case!0:e.identity=await a();break;case!1:e.identity=void 0;break;case void 0:e.identity=await a();break}let t=await r.userTasks.query({state:m.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},e);return(0,I.mapUserTaskList)(t)}async function De(e,t={identity:!0}){switch(t?.identity){case!0:t.identity=await a();break;case!1:t.identity=void 0;break;case void 0:t.identity=await a();break}let s=await r.userTasks.query({processInstanceId:e,state:m.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},t);return(0,I.mapUserTaskList)(s)}async function Le(e,t={identity:!0}){switch(t?.identity){case!0:t.identity=await a();break;case!1:t.identity=void 0;break;case void 0:t.identity=await a();break}let s=await r.userTasks.query({flowNodeId:e,state:m.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},t);return(0,I.mapUserTaskList)(s)}async function pe(e,t={identity:!0}){switch(t?.identity){case!0:t.identity=await a();break;case!1:t.identity=void 0;break;case void 0:t.identity=await a();break}let s=await r.userTasks.query({flowNodeInstanceId:e,state:m.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},{...t,limit:1});return s.userTasks.length===0?null:(0,I.mapUserTask)(s.userTasks[0])}async function We(e,t={identity:!0}){switch(t?.identity){case!0:t.identity=await a();break;case!1:t.identity=void 0;break;case void 0:t.identity=await a();break}let s=await r.userTasks.query({correlationId:e,state:m.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},t);return(0,I.mapUserTaskList)(s)}async function qe(e,t){let s=e||await a(),n=await r.userTasks.query({state:m.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:s,...t}),o=n.userTasks.filter(i=>i.actualOwnerId===s.userId);return n.userTasks=o,(0,I.mapUserTaskList)(n)}async function $e(e,t,s){await r.userTasks.reserveUserTaskInstance(e,t,s||e.userId)}async function Ke(e,t){await r.userTasks.cancelUserTaskInstanceReservation(e,t)}async function Xe(e,t){let s=e||await a(),n=await r.userTasks.query({state:m.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:s,...t}),o=n.userTasks.filter(i=>i.assignedUserIds?.includes(s.userId));return n.userTasks=o,(0,I.mapUserTaskList)(n)}var C=require("next/dist/shared/lib/constants");var fe=!1,X=!1;function Ge(e={}){let{applicationSdk:t,...s}=e;return async(n,o)=>{X=X||n===C.PHASE_PRODUCTION_BUILD;let i=n===C.PHASE_DEVELOPMENT_SERVER||n===C.PHASE_PRODUCTION_SERVER;return t?.useExternalTasks&&i&&!fe&&!X&&(fe=!0,await ne(t?.customExternalTasksDirPath)),{...s,experimental:{...s.experimental,serverComponentsExternalPackages:[...s.experimental?.serverComponentsExternalPackages||[],"esbuild"]}}}}var ye=require("next/navigation");function He(e){(0,ye.redirect)(e)}async function je(...e){return await r.processModels.startProcessInstance(...e)}async function G(...e){await r.manualTasks.finishManualTask(...e)}async function H(...e){await r.userTasks.finishUserTask(...e)}async function j(...e){await r.untypedTasks.finishTask(...e)}var Ie=require("@5minds/processcube_engine_client");async function Ye(){try{return a()}catch{return}}var Ve=async(e,t)=>{let s=await Ye();t==="bpmn:UserTask"?await H(e,{},s):t==="bpmn:ManualTask"?await G(e,s):t==="bpmn:Task"?await j(e,s):console.error(`[@5minds/processcube_app_sdk:handlePlay] Unsupported flow node type: ${t}`)},Qe=async e=>{await K(e)},Ze=async(e,t,s)=>{await $(e,t,s)},Je=async e=>L(e),ze=async e=>W(e,{sortSettings:{sortBy:Ie.DataModels.FlowNodeInstances.FlowNodeInstanceSortableColumns.createdAt,sortDir:"DESC"}}),et=async e=>q(e);0&&(module.exports={cancelReservedUserTask,finishManualTask,finishTask,finishUntypedTask,finishUserTask,finishUserTaskAndGetNext,getActiveProcessInstances,getAssignedUserTasksByIdentity,getEngineClient,getFlowNodeInstances,getFlowNodeInstancesByProcessInstanceId,getFlowNodeInstancesTriggeredByFlowNodeInstanceIds,getIdentity,getProcessInstance,getProcessInstanceById,getReservedUserTasksByIdentity,getTriggeredFlowNodeInstances,getUserTasks,getWaitingUserTaskByFlowNodeInstanceId,getWaitingUserTasks,getWaitingUserTasksByCorrelationId,getWaitingUserTasksByFlowNodeId,getWaitingUserTasksByProcessInstanceId,navigateToUrl,reserveUserTask,retryProcess,retryProcessInstance,startProcess,terminateProcess,terminateProcessInstance,waitForProcessEnd,waitForUserTask,withApplicationSdk});
1
+ var U=Object.defineProperty;var me=Object.getOwnPropertyDescriptor;var Te=Object.getOwnPropertyNames;var ke=Object.prototype.hasOwnProperty;var ge=(e,t)=>{for(var s in t)U(e,s,{get:t[s],enumerable:!0})},we=(e,t,s,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Te(t))!ke.call(e,o)&&o!==s&&U(e,o,{get:()=>t[o],enumerable:!(n=me(t,o))||n.enumerable});return e};var Ee=e=>we(U({},"__esModule",{value:!0}),e);var tt={};ge(tt,{cancelReservedUserTask:()=>Ke,finishManualTask:()=>G,finishTask:()=>Ve,finishUntypedTask:()=>j,finishUserTask:()=>H,finishUserTaskAndGetNext:()=>ve,getActiveProcessInstances:()=>Ae,getAssignedUserTasksByIdentity:()=>Xe,getEngineClient:()=>Fe,getFlowNodeInstances:()=>ze,getFlowNodeInstancesByProcessInstanceId:()=>W,getFlowNodeInstancesTriggeredByFlowNodeInstanceIds:()=>q,getIdentity:()=>a,getProcessInstance:()=>Je,getProcessInstanceById:()=>L,getReservedUserTasksByIdentity:()=>qe,getTriggeredFlowNodeInstances:()=>et,getUserTasks:()=>ue,getWaitingUserTaskByFlowNodeInstanceId:()=>pe,getWaitingUserTasks:()=>Be,getWaitingUserTasksByCorrelationId:()=>We,getWaitingUserTasksByFlowNodeId:()=>Le,getWaitingUserTasksByProcessInstanceId:()=>De,navigateToUrl:()=>He,reserveUserTask:()=>$e,retryProcess:()=>Ze,retryProcessInstance:()=>$,startProcess:()=>je,terminateProcess:()=>Qe,terminateProcessInstance:()=>K,waitForProcessEnd:()=>Me,waitForUserTask:()=>Oe,withApplicationSdk:()=>Ge});module.exports=Ee(tt);var vt=require("only-server"),Bt=require("../common/index.cjs");var Z=require("chokidar"),J=require("esbuild"),z=require("jwt-decode"),ee=require("node:child_process"),h=require("node:fs"),p=require("node:path"),b=require("openid-client"),te=require("@5minds/processcube_engine_sdk");var V=require("@5minds/processcube_engine_client"),F=process.env.PROCESSCUBE_ENGINE_URL??"http://localhost:10560",r=new V.EngineClient(F);var Ce={token:"ZHVtbXlfdG9rZW4=",userId:"dummy_token"},_e=.85,R=["external_task.ts","external_task.js"],x=process.env.PROCESSCUBE_AUTHORITY_URL!==void 0,u=new te.Logger("processcube_app_sdk:external_task_adapter"),k={},M={},w,O=!1,se=6,Pe=3e5,Se=3e4,A=10,he=3e4,Q=10,xe=6e4;async function ne(e){if(e&&!(0,h.existsSync)(e))throw new Error(`Invalid customExternalTasksDirPath. The given path '${e}' does not exist`);b.custom.setHttpOptionsDefaults({timeout:1e5});let t=await ie();w=B(t),await ae(t);let s=be(e);(0,Z.watch)(s).on("add",async n=>{if(R.includes((0,p.basename)(n)))return v(n,s)}).on("change",async n=>{if(R.includes((0,p.basename)(n)))return Ne(n,s)}).on("unlink",async n=>{R.includes((0,p.basename)(n))&&re(n)}).on("error",n=>u.error(`Watcher error: ${n}`))}async function v(e,t){let s=(0,p.dirname)(e);if((await h.promises.readdir(s)).filter(l=>R.includes(l)).length>1){u.error(`Multiple external task files found in directory ${s}. Stopping all external task workers for this directory.`),k[s]&&re(e);return}let i=await ce(e),c=(0,p.relative)(t,s),d=de(c),f=(0,p.join)(__dirname,"lib/ExternalTaskWorkerProcess.cjs"),y=(0,ee.fork)(f,{stdio:["pipe","inherit","inherit","ipc"],env:{...process.env,PROCESSCUBE_ENGINE_URL:F}});k[s]=y,y.once("disconnect",()=>{delete k[s]}),y.on("error",l=>{u.error(`External Task Worker process error for ${d}`,{error:l,topic:d,workerDirectory:s})}),y.on("exit",(l,_)=>{if(u.info(`External Task Worker process exited for ${d}`,{code:l,signal:_,topic:d,workerDirectory:s}),delete k[s],l===3||l===4)if(Ue(s)){let P=M[s]?.count??1,S=Math.min(1e3*Math.pow(2,P-1),Se);u.info(`Scheduling restart for ${d} in ${S}ms (attempt ${P}/${se})`,{delay:S,restartCount:P,exitCode:l,topic:d,workerDirectory:s}),setTimeout(async()=>{try{if(x&&!O){u.info("Token refresh cycle is not active, restarting it before worker restart");let g=await ie();w=B(g),await ae(g)}await v(e,t)}catch(g){u.error(`Failed to restart External Task Worker process for ${d}`,{error:g,topic:d,workerDirectory:s})}},S)}else u.error(`External Task Worker process for ${d} reached maximum restart attempts`,{exitCode:l,topic:d,workerDirectory:s})}),y.send({action:"create",payload:{topic:d,identity:w,moduleString:i,workerPath:e}})}async function Ne(e,t){let s=(0,p.dirname)(e),n=k[s];if(!n)return v(e,t);let o=await ce(e),i=(0,p.relative)(t,s),c=de(i);n.send({action:"restart",payload:{topic:c,identity:w,moduleString:o,workerPath:e}})}function re(e){let t=(0,p.dirname)(e),s=k[t];s&&s.kill()}async function oe(){if(!x)return null;if(!process.env.PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_ID||!process.env.PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_SECRET){let n=new Error("Required environment variables PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_ID and PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_SECRET are missing. For help, please refer to our documentation on environment variables at: https://processcube.io/docs/app-sdk/samples/nextjs/external-task-adapter-with-nextjs#authority");throw u.error("Required environment variables PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_ID and PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_SECRET are missing",{err:n}),n}let e=await b.Issuer.discover(process.env.PROCESSCUBE_AUTHORITY_URL);return await new e.Client({client_id:process.env.PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_ID,client_secret:process.env.PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_SECRET}).grant({grant_type:"client_credentials",scope:"engine_etw"})}async function ie(){if(!x)return null;for(let e=1;e<=A;e++)try{return await oe()}catch(t){let s=Math.min(1e3*Math.pow(2,e-1),he);if(u.error(`Failed to fetch initial token set (attempt ${e}/${A}), retrying in ${s}ms`,{error:t,attempt:e,delay:s}),e===A)throw t;await new Promise(n=>setTimeout(n,s))}return null}function B(e){if(!x||e===null)return Ce;let t=e.access_token,s=(0,z.jwtDecode)(t);return{token:e.access_token,userId:s.sub}}async function ae(e){if(!x||e===null||O)return;O=!0;let t=0,n=await Re(e)*_e*1e3,o=async()=>{try{let i=await oe();w=B(i);for(let[c,d]of Object.entries(k))try{d.send({action:"updateIdentity",payload:{identity:w}})}catch(f){u.warn(`Failed to send identity update to worker process ${c}`,{sendError:f})}t=0,setTimeout(o,n)}catch(i){t++;let c=Math.min(1e3*Math.pow(2,t-1),xe);t<=Q?u.error(`Could not refresh identity (attempt ${t}/${Q}), retrying in ${c}ms`,{error:i,attempt:t,delay:c}):u.error(`Could not refresh identity (attempt ${t}), continuing to retry every ${c}ms`,{error:i,attempt:t,delay:c}),setTimeout(o,c)}};setTimeout(o,n)}async function ce(e){let t=await(0,J.build)({entryPoints:[e],write:!1,bundle:!0,platform:"node",target:"node18",format:"cjs",external:["@opentelemetry/api"]});if(t.errors.length>0)throw u.error(`Could not transpile file at '${e}'`,{errors:t.errors}),new Error(`Could not transpile file at '${e}'`);return t.warnings.length>0&&u.warn(`Transpiled file at '${e}' with warnings`,{warnings:t.warnings}),t.outputFiles[0].text}async function Re(e){let t=e.expires_in;if(!t&&e.expires_at&&(t=Math.floor(e.expires_at-Date.now()/1e3)),t===void 0)throw new Error("Could not determine the time until the access token for external task workers expires");return t}function de(e){return e.replace(/^\.\/+|\([^)]+\)|^\/*|\/*$/g,"").replace(/[\/]{2,}/g,"/")}function be(e){let t,s=[e,(0,p.join)(process.cwd(),"app"),(0,p.join)(process.cwd(),"src","app")];for(let n of s)if(n&&(0,h.existsSync)(n)){t=n;break}if(!t)throw new Error("Could not find external tasks directory");return t}function Ue(e){let t=Date.now(),s=M[e];return!s||t-s.timestamp>Pe?(M[e]={count:1,timestamp:t},!0):s.count>=se?!1:(s.count++,!0)}function Fe(){return r}var D=require("next-auth/jwt"),le=require("next/dist/compiled/@edge-runtime/cookies/index.js"),T=require("next/headers");async function a(){let e=await(0,D.getToken)({req:{cookies:await(0,T.cookies)(),headers:await(0,T.headers)()}});if(e?.expiresAt&&Date.now()>=e.expiresAt*1e3){let s=await fetch(`${process.env.NEXTAUTH_URL}/api/auth/session`,{method:"GET",headers:{"Content-Type":"application/json",cookie:(await(0,T.cookies)()).toString()}}),n=new le.ResponseCookies(s.headers);if(n.getAll().length){let o=!1;try{for(let i of n.getAll())(await(0,T.cookies)()).set(i.name,i.value,{...i})}catch{o=!0}if(e=await(0,D.getToken)({req:{cookies:o?n:await(0,T.cookies)(),headers:await(0,T.headers)()}}),e?.error)throw e.error}}if(!e?.accessToken||!e?.sub)throw new Error("AccessToken or Sub could not be determined!");return{token:e?.accessToken,userId:e?.sub}}var E=require("@5minds/processcube_engine_client");async function N(){try{return a()}catch{return}}async function L(e){let t=await N();return(await r.processInstances.query({processInstanceId:e},{identity:t,includeXml:!0})).processInstances[0]}async function W(e,t={sortSettings:{sortBy:E.DataModels.FlowNodeInstances.FlowNodeInstanceSortableColumns.createdAt,sortDir:"ASC"}}){return(await r.flowNodeInstances.query({processInstanceId:e},{...t,identity:t.identity??await N()})).flowNodeInstances}async function q(e){let t=await N();return(await r.flowNodeInstances.query({triggeredByFlowNodeInstance:e},{identity:t})).flowNodeInstances}async function $(e,t,s){let n=await N();await r.processInstances.retryProcessInstance(e,{flowNodeInstanceId:t,newStartToken:s,identity:n})}async function K(e){let t=await N();await r.processInstances.terminateProcessInstance(e,t)}async function Ae(e={options:{identity:!0}}){switch(e.options.identity){case!0:e.options.identity=await a();break;case!1:e.options.identity=void 0;break;case void 0:e.options.identity=await a();break}return await r.processInstances.query({...e?.query,state:E.DataModels.ProcessInstances.ProcessInstanceState.running},e?.options)}async function Me(e={},t=!0){let{processInstanceId:s}=e,n=typeof t=="boolean"?t==!0?await a():void 0:t;return new Promise(async(o,i)=>{let c=[],d=async f=>{if(s!==void 0&&f.processInstanceId!==s)return;let l=await r.processInstances.query({processInstanceId:f.processInstanceId},{identity:n});for(let _ of c)r.notification.removeSubscription(_,n);return l.totalCount===0?i(new Error(`Process with instance ID "${f.processInstanceId}" does not exist.`)):o(l.processInstances[0])};if(c.push(await r.notification.onProcessEnded(d,{identity:n})),c.push(await r.notification.onProcessError(d,{identity:n})),c.push(await r.notification.onProcessTerminated(d,{identity:n})),s){let f=await r.processInstances.query({processInstanceId:s,state:[E.DataModels.ProcessInstances.ProcessInstanceState.finished,E.DataModels.ProcessInstances.ProcessInstanceState.terminated,E.DataModels.ProcessInstances.ProcessInstanceState.error]},{identity:n});if(f.totalCount>0){for(let y of c)r.notification.removeSubscription(y,n);o(f.processInstances[0])}}})}var m=require("@5minds/processcube_engine_client"),I=require("../common/index.cjs");async function Oe(e={},t=!0){let{correlationId:s,processInstanceId:n,flowNodeId:o}=e,i=typeof t=="boolean"?t==!0?await a():void 0:t;return new Promise(async(c,d)=>{let f=await r.userTasks.onUserTaskWaiting(async l=>{let _=s!==void 0&&l.correlationId!==s,P=l.flowNodeInstanceId===void 0,S=n!==void 0&&l.processInstanceId!==n,g=o!==void 0&&l.flowNodeId!==o;if(_||P||S||g)return;let Y=await pe(l.flowNodeInstanceId,{identity:i});return r.notification.removeSubscription(f,i),Y===null?d(new Error(`UserTask with instance ID "${l.flowNodeInstanceId}" does not exist.`)):c(Y)},{identity:i}),y=await ue({correlationId:s,processInstanceId:n,flowNodeId:o,state:m.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:i});y.userTasks.length>0&&(r.notification.removeSubscription(f,i),c(y.userTasks[0]))})}async function ve(e,t={},s={},n=!0){let o=typeof n=="boolean"?n==!0?await a():void 0:n;await r.userTasks.finishUserTask(e,s,o);let i={state:m.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended,...t},c=await r.userTasks.query(i,{identity:o});return(0,I.mapUserTask)(c.userTasks[0])}async function ue(e,t={identity:!0}){switch(t?.identity){case!0:t.identity=await a();break;case!1:t.identity=void 0;break;case void 0:t.identity=await a();break}let s=await r.userTasks.query(e,t);return(0,I.mapUserTaskList)(s)}async function Be(e={identity:!0}){switch(e?.identity){case!0:e.identity=await a();break;case!1:e.identity=void 0;break;case void 0:e.identity=await a();break}let t=await r.userTasks.query({state:m.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},e);return(0,I.mapUserTaskList)(t)}async function De(e,t={identity:!0}){switch(t?.identity){case!0:t.identity=await a();break;case!1:t.identity=void 0;break;case void 0:t.identity=await a();break}let s=await r.userTasks.query({processInstanceId:e,state:m.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},t);return(0,I.mapUserTaskList)(s)}async function Le(e,t={identity:!0}){switch(t?.identity){case!0:t.identity=await a();break;case!1:t.identity=void 0;break;case void 0:t.identity=await a();break}let s=await r.userTasks.query({flowNodeId:e,state:m.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},t);return(0,I.mapUserTaskList)(s)}async function pe(e,t={identity:!0}){switch(t?.identity){case!0:t.identity=await a();break;case!1:t.identity=void 0;break;case void 0:t.identity=await a();break}let s=await r.userTasks.query({flowNodeInstanceId:e,state:m.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},{...t,limit:1});return s.userTasks.length===0?null:(0,I.mapUserTask)(s.userTasks[0])}async function We(e,t={identity:!0}){switch(t?.identity){case!0:t.identity=await a();break;case!1:t.identity=void 0;break;case void 0:t.identity=await a();break}let s=await r.userTasks.query({correlationId:e,state:m.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},t);return(0,I.mapUserTaskList)(s)}async function qe(e,t){let s=e||await a(),n=await r.userTasks.query({state:m.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:s,...t}),o=n.userTasks.filter(i=>i.actualOwnerId===s.userId);return n.userTasks=o,(0,I.mapUserTaskList)(n)}async function $e(e,t,s){await r.userTasks.reserveUserTaskInstance(e,t,s||e.userId)}async function Ke(e,t){await r.userTasks.cancelUserTaskInstanceReservation(e,t)}async function Xe(e,t){let s=e||await a(),n=await r.userTasks.query({state:m.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:s,...t}),o=n.userTasks.filter(i=>i.assignedUserIds?.includes(s.userId));return n.userTasks=o,(0,I.mapUserTaskList)(n)}var C=require("next/dist/shared/lib/constants");var fe=!1,X=!1;function Ge(e={}){let{applicationSdk:t,...s}=e;return async(n,o)=>{X=X||n===C.PHASE_PRODUCTION_BUILD;let i=n===C.PHASE_DEVELOPMENT_SERVER||n===C.PHASE_PRODUCTION_SERVER;return t?.useExternalTasks&&i&&!fe&&!X&&(fe=!0,await ne(t?.customExternalTasksDirPath)),{...s,experimental:{...s.experimental,serverComponentsExternalPackages:[...s.experimental?.serverComponentsExternalPackages||[],"esbuild"]}}}}var ye=require("next/navigation");function He(e){(0,ye.redirect)(e)}async function je(...e){return await r.processModels.startProcessInstance(...e)}async function G(...e){await r.manualTasks.finishManualTask(...e)}async function H(...e){await r.userTasks.finishUserTask(...e)}async function j(...e){await r.untypedTasks.finishTask(...e)}var Ie=require("@5minds/processcube_engine_client");async function Ye(){try{return a()}catch{return}}var Ve=async(e,t)=>{let s=await Ye();t==="bpmn:UserTask"?await H(e,{},s):t==="bpmn:ManualTask"?await G(e,s):t==="bpmn:Task"?await j(e,s):console.error(`[@5minds/processcube_app_sdk:handlePlay] Unsupported flow node type: ${t}`)},Qe=async e=>{await K(e)},Ze=async(e,t,s)=>{await $(e,t,s)},Je=async e=>L(e),ze=async e=>W(e,{sortSettings:{sortBy:Ie.DataModels.FlowNodeInstances.FlowNodeInstanceSortableColumns.createdAt,sortDir:"DESC"}}),et=async e=>q(e);0&&(module.exports={cancelReservedUserTask,finishManualTask,finishTask,finishUntypedTask,finishUserTask,finishUserTaskAndGetNext,getActiveProcessInstances,getAssignedUserTasksByIdentity,getEngineClient,getFlowNodeInstances,getFlowNodeInstancesByProcessInstanceId,getFlowNodeInstancesTriggeredByFlowNodeInstanceIds,getIdentity,getProcessInstance,getProcessInstanceById,getReservedUserTasksByIdentity,getTriggeredFlowNodeInstances,getUserTasks,getWaitingUserTaskByFlowNodeInstanceId,getWaitingUserTasks,getWaitingUserTasksByCorrelationId,getWaitingUserTasksByFlowNodeId,getWaitingUserTasksByProcessInstanceId,navigateToUrl,reserveUserTask,retryProcess,retryProcessInstance,startProcess,terminateProcess,terminateProcessInstance,waitForProcessEnd,waitForUserTask,withApplicationSdk});
@@ -1,4 +1,4 @@
1
- import"only-server";import"../common/index.mjs";import{stat as Fe}from"fs";import{stat as Ae,readdir as ve}from"fs/promises";import{EventEmitter as Le}from"events";import*as p from"path";import{stat as ne,lstat as ut,readdir as re,realpath as ie}from"node:fs/promises";import{Readable as oe}from"node:stream";import{resolve as ht,relative as ae,join as ce,sep as de}from"node:path";var I={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},z={root:".",fileFilter:s=>!0,directoryFilter:s=>!0,type:I.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(z);var wt="READDIRP_RECURSIVE_ERROR",le=new Set(["ENOENT","EPERM","EACCES","ELOOP",wt]),pt=[I.DIR_TYPE,I.EVERYTHING_TYPE,I.FILE_DIR_TYPE,I.FILE_TYPE],fe=new Set([I.DIR_TYPE,I.EVERYTHING_TYPE,I.FILE_DIR_TYPE]),ue=new Set([I.EVERYTHING_TYPE,I.FILE_DIR_TYPE,I.FILE_TYPE]),he=s=>le.has(s.code),pe=process.platform==="win32",mt=s=>!0,yt=s=>{if(s===void 0)return mt;if(typeof s=="function")return s;if(typeof s=="string"){let t=s.trim();return e=>e.basename===t}if(Array.isArray(s)){let t=s.map(e=>e.trim());return e=>t.some(n=>e.basename===n)}return mt},K=class extends oe{constructor(t={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:t.highWaterMark});let e={...z,...t},{root:n,type:r}=e;this._fileFilter=yt(e.fileFilter),this._directoryFilter=yt(e.directoryFilter);let i=e.lstat?ut:ne;pe?this._stat=a=>i(a,{bigint:!0}):this._stat=i,this._maxDepth=e.depth??z.depth,this._wantsDir=r?fe.has(r):!1,this._wantsFile=r?ue.has(r):!1,this._wantsEverything=r===I.EVERYTHING_TYPE,this._root=ht(n),this._isDirent=!e.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent},this.parents=[this._exploreDir(n,1)],this.reading=!1,this.parent=void 0}async _read(t){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&t>0;){let e=this.parent,n=e&&e.files;if(n&&n.length>0){let{path:r,depth:i}=e,a=n.splice(0,t).map(c=>this._formatEntry(c,r)),o=await Promise.all(a);for(let c of o){if(!c)continue;if(this.destroyed)return;let l=await this._getEntryType(c);l==="directory"&&this._directoryFilter(c)?(i<=this._maxDepth&&this.parents.push(this._exploreDir(c.fullPath,i+1)),this._wantsDir&&(this.push(c),t--)):(l==="file"||this._includeAsFile(c))&&this._fileFilter(c)&&this._wantsFile&&(this.push(c),t--)}}else{let r=this.parents.pop();if(!r){this.push(null);break}if(this.parent=await r,this.destroyed)return}}}catch(e){this.destroy(e)}finally{this.reading=!1}}}async _exploreDir(t,e){let n;try{n=await re(t,this._rdOptions)}catch(r){this._onError(r)}return{files:n,depth:e,path:t}}async _formatEntry(t,e){let n,r=this._isDirent?t.name:t;try{let i=ht(ce(e,r));n={path:ae(this._root,i),fullPath:i,basename:r},n[this._statsProp]=this._isDirent?t:await this._stat(i)}catch(i){this._onError(i);return}return n}_onError(t){he(t)&&!this.destroyed?this.emit("warn",t):this.destroy(t)}async _getEntryType(t){if(!t&&this._statsProp in t)return"";let e=t[this._statsProp];if(e.isFile())return"file";if(e.isDirectory())return"directory";if(e&&e.isSymbolicLink()){let n=t.fullPath;try{let r=await ie(n),i=await ut(r);if(i.isFile())return"file";if(i.isDirectory()){let a=r.length;if(n.startsWith(r)&&n.substr(a,1)===de){let o=new Error(`Circular symlink detected: "${n}" points to "${r}"`);return o.code=wt,this._onError(o)}return"directory"}}catch(r){return this._onError(r),""}}}_includeAsFile(t){let e=t&&t[this._statsProp];return e&&this._wantsEverything&&!e.isDirectory()}};function _t(s,t={}){let e=t.entryType||t.type;if(e==="both"&&(e=I.FILE_DIR_TYPE),e&&(t.type=e),s){if(typeof s!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(e&&!pt.includes(e))throw new Error(`readdirp: Invalid type passed. Use one of ${pt.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return t.root=s,new K(t)}import{watchFile as me,unwatchFile as gt,watch as ye}from"fs";import{open as we,stat as It,lstat as _e,realpath as $}from"fs/promises";import*as y from"path";import{type as ge}from"os";var Ee="data",X="end",Tt="close",M=()=>{};var B=process.platform,V=B==="win32",Ie=B==="darwin",Te=B==="linux",Pe=B==="freebsd",Pt=ge()==="OS400",_={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},T=_,ke="watch",Re={lstat:_e,stat:It},R="listeners",L="errHandlers",S="rawEmitters",xe=[R,L,S],be=new Set(["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]),Se=s=>be.has(y.extname(s).slice(1).toLowerCase()),G=(s,t)=>{s instanceof Set?s.forEach(t):t(s)},N=(s,t,e)=>{let n=s[t];n instanceof Set||(s[t]=n=new Set([n])),n.add(e)},Ce=s=>t=>{let e=s[t];e instanceof Set?e.clear():delete s[t]},D=(s,t,e)=>{let n=s[t];n instanceof Set?n.delete(e):n===e&&delete s[t]},kt=s=>s instanceof Set?s.size===0:!s,O=new Map;function Et(s,t,e,n,r){let i=(a,o)=>{e(s),r(a,o,{watchedPath:s}),o&&s!==o&&U(y.resolve(s,o),R,y.join(s,o))};try{return ye(s,{persistent:t.persistent},i)}catch(a){n(a);return}}var U=(s,t,e,n,r)=>{let i=O.get(s);i&&G(i[t],a=>{a(e,n,r)})},Ne=(s,t,e,n)=>{let{listener:r,errHandler:i,rawEmitter:a}=n,o=O.get(t),c;if(!e.persistent)return c=Et(s,e,r,i,a),c?c.close.bind(c):void 0;if(o)N(o,R,r),N(o,L,i),N(o,S,a);else{if(c=Et(s,e,U.bind(null,t,R),i,U.bind(null,t,S)),!c)return;c.on(T.ERROR,async l=>{let d=U.bind(null,t,L);if(o&&(o.watcherUnusable=!0),V&&l.code==="EPERM")try{await(await we(s,"r")).close(),d(l)}catch{}else d(l)}),o={listeners:r,errHandlers:i,rawEmitters:a,watcher:c},O.set(t,o)}return()=>{D(o,R,r),D(o,L,i),D(o,S,a),kt(o.listeners)&&(o.watcher.close(),O.delete(t),xe.forEach(Ce(o)),o.watcher=void 0,Object.freeze(o))}},q=new Map,De=(s,t,e,n)=>{let{listener:r,rawEmitter:i}=n,a=q.get(t),o=a&&a.options;return o&&(o.persistent<e.persistent||o.interval>e.interval)&&(gt(t),a=void 0),a?(N(a,R,r),N(a,S,i)):(a={listeners:r,rawEmitters:i,options:e,watcher:me(t,e,(c,l)=>{G(a.rawEmitters,f=>{f(T.CHANGE,t,{curr:c,prev:l})});let d=c.mtimeMs;(c.size!==l.size||d>l.mtimeMs||d===0)&&G(a.listeners,f=>f(s,c))})},q.set(t,a)),()=>{D(a,R,r),D(a,S,i),kt(a.listeners)&&(q.delete(t),gt(t),a.options=a.watcher=void 0,Object.freeze(a))}},W=class{constructor(t){this.fsw=t,this._boundHandleError=e=>t._handleError(e)}_watchWithNodeFs(t,e){let n=this.fsw.options,r=y.dirname(t),i=y.basename(t);this.fsw._getWatchedDir(r).add(i);let o=y.resolve(t),c={persistent:n.persistent};e||(e=M);let l;if(n.usePolling){let d=n.interval!==n.binaryInterval;c.interval=d&&Se(i)?n.binaryInterval:n.interval,l=De(t,o,c,{listener:e,rawEmitter:this.fsw._emitRaw})}else l=Ne(t,o,c,{listener:e,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return l}_handleFile(t,e,n){if(this.fsw.closed)return;let r=y.dirname(t),i=y.basename(t),a=this.fsw._getWatchedDir(r),o=e;if(a.has(i))return;let c=async(d,f)=>{if(this.fsw._throttle(ke,t,5)){if(!f||f.mtimeMs===0)try{let u=await It(t);if(this.fsw.closed)return;let m=u.atimeMs,g=u.mtimeMs;if((!m||m<=g||g!==o.mtimeMs)&&this.fsw._emit(T.CHANGE,t,u),(Ie||Te||Pe)&&o.ino!==u.ino){this.fsw._closeFile(d),o=u;let k=this._watchWithNodeFs(t,c);k&&this.fsw._addPathCloser(d,k)}else o=u}catch{this.fsw._remove(r,i)}else if(a.has(i)){let u=f.atimeMs,m=f.mtimeMs;(!u||u<=m||m!==o.mtimeMs)&&this.fsw._emit(T.CHANGE,t,f),o=f}}},l=this._watchWithNodeFs(t,c);if(!(n&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(t)){if(!this.fsw._throttle(T.ADD,t,0))return;this.fsw._emit(T.ADD,t,e)}return l}async _handleSymlink(t,e,n,r){if(this.fsw.closed)return;let i=t.fullPath,a=this.fsw._getWatchedDir(e);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let o;try{o=await $(n)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(a.has(r)?this.fsw._symlinkPaths.get(i)!==o&&(this.fsw._symlinkPaths.set(i,o),this.fsw._emit(T.CHANGE,n,t.stats)):(a.add(r),this.fsw._symlinkPaths.set(i,o),this.fsw._emit(T.ADD,n,t.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(i))return!0;this.fsw._symlinkPaths.set(i,!0)}_handleRead(t,e,n,r,i,a,o){if(t=y.join(t,""),o=this.fsw._throttle("readdir",t,1e3),!o)return;let c=this.fsw._getWatchedDir(n.path),l=new Set,d=this.fsw._readdirp(t,{fileFilter:f=>n.filterPath(f),directoryFilter:f=>n.filterDir(f)});if(d)return d.on(Ee,async f=>{if(this.fsw.closed){d=void 0;return}let u=f.path,m=y.join(t,u);if(l.add(u),!(f.stats.isSymbolicLink()&&await this._handleSymlink(f,t,m,u))){if(this.fsw.closed){d=void 0;return}(u===r||!r&&!c.has(u))&&(this.fsw._incrReadyCount(),m=y.join(i,y.relative(i,m)),this._addToNodeFs(m,e,n,a+1))}}).on(T.ERROR,this._boundHandleError),new Promise((f,u)=>{if(!d)return u();d.once(X,()=>{if(this.fsw.closed){d=void 0;return}let m=o?o.clear():!1;f(void 0),c.getChildren().filter(g=>g!==t&&!l.has(g)).forEach(g=>{this.fsw._remove(t,g)}),d=void 0,m&&this._handleRead(t,!1,n,r,i,a,o)})})}async _handleDir(t,e,n,r,i,a,o){let c=this.fsw._getWatchedDir(y.dirname(t)),l=c.has(y.basename(t));!(n&&this.fsw.options.ignoreInitial)&&!i&&!l&&this.fsw._emit(T.ADD_DIR,t,e),c.add(y.basename(t)),this.fsw._getWatchedDir(t);let d,f,u=this.fsw.options.depth;if((u==null||r<=u)&&!this.fsw._symlinkPaths.has(o)){if(!i&&(await this._handleRead(t,n,a,i,t,r,d),this.fsw.closed))return;f=this._watchWithNodeFs(t,(m,g)=>{g&&g.mtimeMs===0||this._handleRead(m,!1,a,i,t,r,d)})}return f}async _addToNodeFs(t,e,n,r,i){let a=this.fsw._emitReady;if(this.fsw._isIgnored(t)||this.fsw.closed)return a(),!1;let o=this.fsw._getWatchHelpers(t);n&&(o.filterPath=c=>n.filterPath(c),o.filterDir=c=>n.filterDir(c));try{let c=await Re[o.statMethod](o.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(o.watchPath,c))return a(),!1;let l=this.fsw.options.followSymlinks,d;if(c.isDirectory()){let f=y.resolve(t),u=l?await $(t):t;if(this.fsw.closed||(d=await this._handleDir(o.watchPath,c,e,r,i,o,u),this.fsw.closed))return;f!==u&&u!==void 0&&this.fsw._symlinkPaths.set(f,u)}else if(c.isSymbolicLink()){let f=l?await $(t):t;if(this.fsw.closed)return;let u=y.dirname(o.watchPath);if(this.fsw._getWatchedDir(u).add(o.watchPath),this.fsw._emit(T.ADD,o.watchPath,c),d=await this._handleDir(u,c,e,r,t,o,f),this.fsw.closed)return;f!==void 0&&this.fsw._symlinkPaths.set(y.resolve(t),f)}else d=this._handleFile(o.watchPath,c,e);return a(),d&&this.fsw._addPathCloser(t,d),!1}catch(c){if(this.fsw._handleError(c))return a(),t}}};var Q="/",Oe="//",Nt=".",Ue="..",We="string",Me=/\\/g,Rt=/\/\//,Be=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,He=/^\.[/\\]/;function H(s){return Array.isArray(s)?s:[s]}var Z=s=>typeof s=="object"&&s!==null&&!(s instanceof RegExp);function je(s){return typeof s=="function"?s:typeof s=="string"?t=>s===t:s instanceof RegExp?t=>s.test(t):typeof s=="object"&&s!==null?t=>{if(s.path===t)return!0;if(s.recursive){let e=p.relative(s.path,t);return e?!e.startsWith("..")&&!p.isAbsolute(e):!1}return!1}:()=>!1}function Ye(s){if(typeof s!="string")throw new Error("string expected");s=p.normalize(s),s=s.replace(/\\/g,"/");let t=!1;s.startsWith("//")&&(t=!0);let e=/\/\//;for(;s.match(e);)s=s.replace(e,"/");return t&&(s="/"+s),s}function xt(s,t,e){let n=Ye(t);for(let r=0;r<s.length;r++){let i=s[r];if(i(n,e))return!0}return!1}function ze(s,t){if(s==null)throw new TypeError("anymatch: specify first argument");let n=H(s).map(r=>je(r));return t==null?(r,i)=>xt(n,r,i):xt(n,t)}var bt=s=>{let t=H(s).flat();if(!t.every(e=>typeof e===We))throw new TypeError(`Non-string provided as watch path: ${t}`);return t.map(Dt)},St=s=>{let t=s.replace(Me,Q),e=!1;for(t.startsWith(Oe)&&(e=!0);t.match(Rt);)t=t.replace(Rt,Q);return e&&(t=Q+t),t},Dt=s=>St(p.normalize(St(s))),Ct=(s="")=>t=>typeof t=="string"?Dt(p.isAbsolute(t)?t:p.join(s,t)):t,Ke=(s,t)=>p.isAbsolute(s)?s:p.join(t,s),$e=Object.freeze(new Set),J=class{constructor(t,e){this.path=t,this._removeWatcher=e,this.items=new Set}add(t){let{items:e}=this;e&&t!==Nt&&t!==Ue&&e.add(t)}async remove(t){let{items:e}=this;if(!e||(e.delete(t),e.size>0))return;let n=this.path;try{await ve(n)}catch{this._removeWatcher&&this._removeWatcher(p.dirname(n),p.basename(n))}}has(t){let{items:e}=this;if(e)return e.has(t)}getChildren(){let{items:t}=this;return t?[...t.values()]:[]}dispose(){this.items.clear(),this.path="",this._removeWatcher=M,this.items=$e,Object.freeze(this)}},qe="stat",Ge="lstat",tt=class{constructor(t,e,n){this.fsw=n;let r=t;this.path=t=t.replace(He,""),this.watchPath=r,this.fullWatchPath=p.resolve(r),this.dirParts=[],this.dirParts.forEach(i=>{i.length>1&&i.pop()}),this.followSymlinks=e,this.statMethod=e?qe:Ge}entryPath(t){return p.join(this.watchPath,p.relative(this.watchPath,t.fullPath))}filterPath(t){let{stats:e}=t;if(e&&e.isSymbolicLink())return this.filterDir(t);let n=this.entryPath(t);return this.fsw._isntIgnored(n,e)&&this.fsw._hasReadPermissions(e)}filterDir(t){return this.fsw._isntIgnored(this.entryPath(t),t.stats)}},et=class extends Le{constructor(t={}){super(),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let e=t.awaitWriteFinish,n={stabilityThreshold:2e3,pollInterval:100},r={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...t,ignored:t.ignored?H(t.ignored):H([]),awaitWriteFinish:e===!0?n:typeof e=="object"?{...n,...e}:!1};Pt&&(r.usePolling=!0),r.atomic===void 0&&(r.atomic=!r.usePolling);let i=process.env.CHOKIDAR_USEPOLLING;if(i!==void 0){let c=i.toLowerCase();c==="false"||c==="0"?r.usePolling=!1:c==="true"||c==="1"?r.usePolling=!0:r.usePolling=!!c}let a=process.env.CHOKIDAR_INTERVAL;a&&(r.interval=Number.parseInt(a,10));let o=0;this._emitReady=()=>{o++,o>=this._readyCount&&(this._emitReady=M,this._readyEmitted=!0,process.nextTick(()=>this.emit(_.READY)))},this._emitRaw=(...c)=>this.emit(_.RAW,...c),this._boundRemove=this._remove.bind(this),this.options=r,this._nodeFsHandler=new W(this),Object.freeze(r)}_addIgnoredPath(t){if(Z(t)){for(let e of this._ignoredPaths)if(Z(e)&&e.path===t.path&&e.recursive===t.recursive)return}this._ignoredPaths.add(t)}_removeIgnoredPath(t){if(this._ignoredPaths.delete(t),typeof t=="string")for(let e of this._ignoredPaths)Z(e)&&e.path===t&&this._ignoredPaths.delete(e)}add(t,e,n){let{cwd:r}=this.options;this.closed=!1,this._closePromise=void 0;let i=bt(t);return r&&(i=i.map(a=>Ke(a,r))),i.forEach(a=>{this._removeIgnoredPath(a)}),this._userIgnored=void 0,this._readyCount||(this._readyCount=0),this._readyCount+=i.length,Promise.all(i.map(async a=>{let o=await this._nodeFsHandler._addToNodeFs(a,!n,void 0,0,e);return o&&this._emitReady(),o})).then(a=>{this.closed||a.forEach(o=>{o&&this.add(p.dirname(o),p.basename(e||o))})}),this}unwatch(t){if(this.closed)return this;let e=bt(t),{cwd:n}=this.options;return e.forEach(r=>{!p.isAbsolute(r)&&!this._closers.has(r)&&(n&&(r=p.join(n,r)),r=p.resolve(r)),this._closePath(r),this._addIgnoredPath(r),this._watched.has(r)&&this._addIgnoredPath({path:r,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let t=[];return this._closers.forEach(e=>e.forEach(n=>{let r=n();r instanceof Promise&&t.push(r)})),this._streams.forEach(e=>e.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(e=>e.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=t.length?Promise.all(t).then(()=>{}):Promise.resolve(),this._closePromise}getWatched(){let t={};return this._watched.forEach((e,n)=>{let i=(this.options.cwd?p.relative(this.options.cwd,n):n)||Nt;t[i]=e.getChildren().sort()}),t}emitWithAll(t,e){this.emit(t,...e),t!==_.ERROR&&this.emit(_.ALL,t,...e)}async _emit(t,e,n){if(this.closed)return;let r=this.options;V&&(e=p.normalize(e)),r.cwd&&(e=p.relative(r.cwd,e));let i=[e];n!=null&&i.push(n);let a=r.awaitWriteFinish,o;if(a&&(o=this._pendingWrites.get(e)))return o.lastChange=new Date,this;if(r.atomic){if(t===_.UNLINK)return this._pendingUnlinks.set(e,[t,...i]),setTimeout(()=>{this._pendingUnlinks.forEach((c,l)=>{this.emit(...c),this.emit(_.ALL,...c),this._pendingUnlinks.delete(l)})},typeof r.atomic=="number"?r.atomic:100),this;t===_.ADD&&this._pendingUnlinks.has(e)&&(t=_.CHANGE,this._pendingUnlinks.delete(e))}if(a&&(t===_.ADD||t===_.CHANGE)&&this._readyEmitted){let c=(l,d)=>{l?(t=_.ERROR,i[0]=l,this.emitWithAll(t,i)):d&&(i.length>1?i[1]=d:i.push(d),this.emitWithAll(t,i))};return this._awaitWriteFinish(e,a.stabilityThreshold,t,c),this}if(t===_.CHANGE&&!this._throttle(_.CHANGE,e,50))return this;if(r.alwaysStat&&n===void 0&&(t===_.ADD||t===_.ADD_DIR||t===_.CHANGE)){let c=r.cwd?p.join(r.cwd,e):e,l;try{l=await Ae(c)}catch{}if(!l||this.closed)return;i.push(l)}return this.emitWithAll(t,i),this}_handleError(t){let e=t&&t.code;return t&&e!=="ENOENT"&&e!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||e!=="EPERM"&&e!=="EACCES")&&this.emit(_.ERROR,t),t||this.closed}_throttle(t,e,n){this._throttled.has(t)||this._throttled.set(t,new Map);let r=this._throttled.get(t);if(!r)throw new Error("invalid throttle");let i=r.get(e);if(i)return i.count++,!1;let a,o=()=>{let l=r.get(e),d=l?l.count:0;return r.delete(e),clearTimeout(a),l&&clearTimeout(l.timeoutObject),d};a=setTimeout(o,n);let c={timeoutObject:a,clear:o,count:0};return r.set(e,c),c}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(t,e,n,r){let i=this.options.awaitWriteFinish;if(typeof i!="object")return;let a=i.pollInterval,o,c=t;this.options.cwd&&!p.isAbsolute(t)&&(c=p.join(this.options.cwd,t));let l=new Date,d=this._pendingWrites;function f(u){Fe(c,(m,g)=>{if(m||!d.has(t)){m&&m.code!=="ENOENT"&&r(m);return}let k=Number(new Date);u&&g.size!==u.size&&(d.get(t).lastChange=k);let se=d.get(t);k-se.lastChange>=e?(d.delete(t),r(void 0,g)):o=setTimeout(f,a,g)})}d.has(t)||(d.set(t,{lastChange:l,cancelWait:()=>(d.delete(t),clearTimeout(o),n)}),o=setTimeout(f,a))}_isIgnored(t,e){if(this.options.atomic&&Be.test(t))return!0;if(!this._userIgnored){let{cwd:n}=this.options,i=(this.options.ignored||[]).map(Ct(n)),o=[...[...this._ignoredPaths].map(Ct(n)),...i];this._userIgnored=ze(o,void 0)}return this._userIgnored(t,e)}_isntIgnored(t,e){return!this._isIgnored(t,e)}_getWatchHelpers(t){return new tt(t,this.options.followSymlinks,this)}_getWatchedDir(t){let e=p.resolve(t);return this._watched.has(e)||this._watched.set(e,new J(e,this._boundRemove)),this._watched.get(e)}_hasReadPermissions(t){return this.options.ignorePermissionErrors?!0:!!(Number(t.mode)&256)}_remove(t,e,n){let r=p.join(t,e),i=p.resolve(r);if(n=n??(this._watched.has(r)||this._watched.has(i)),!this._throttle("remove",r,100))return;!n&&this._watched.size===1&&this.add(t,e,!0),this._getWatchedDir(r).getChildren().forEach(u=>this._remove(r,u));let c=this._getWatchedDir(t),l=c.has(e);c.remove(e),this._symlinkPaths.has(i)&&this._symlinkPaths.delete(i);let d=r;if(this.options.cwd&&(d=p.relative(this.options.cwd,r)),this.options.awaitWriteFinish&&this._pendingWrites.has(d)&&this._pendingWrites.get(d).cancelWait()===_.ADD)return;this._watched.delete(r),this._watched.delete(i);let f=n?_.UNLINK_DIR:_.UNLINK;l&&!this._isIgnored(r)&&this._emit(f,r),this._closePath(r)}_closePath(t){this._closeFile(t);let e=p.dirname(t);this._getWatchedDir(e).remove(p.basename(t))}_closeFile(t){let e=this._closers.get(t);e&&(e.forEach(n=>n()),this._closers.delete(t))}_addPathCloser(t,e){if(!e)return;let n=this._closers.get(t);n||(n=[],this._closers.set(t,n)),n.push(e)}_readdirp(t,e){if(this.closed)return;let n={type:_.ALL,alwaysStat:!0,lstat:!0,...e,depth:0},r=_t(t,n);return this._streams.add(r),r.once(Tt,()=>{r=void 0}),r.once(X,()=>{r&&(this._streams.delete(r),r=void 0)}),r}};function Ft(s,t={}){let e=new et(t);return e.add(s),e}import{build as Ve}from"esbuild";import{jwtDecode as Qe}from"jwt-decode";import{fork as Ze}from"node:child_process";import{existsSync as vt,promises as Je}from"node:fs";import{basename as nt,dirname as ct,join as it,relative as Lt}from"node:path";import{Issuer as ts,custom as es}from"openid-client";import{Logger as ss}from"@5minds/processcube_engine_sdk";import{EngineClient as Xe}from"@5minds/processcube_engine_client";var st=process.env.PROCESSCUBE_ENGINE_URL??"http://localhost:10560",h=new Xe(st);var ns={token:"ZHVtbXlfdG9rZW4=",userId:"dummy_token"},rs=.85,j=["external_task.ts","external_task.js"],F=process.env.PROCESSCUBE_AUTHORITY_URL!==void 0,E=new ss("processcube_app_sdk:external_task_adapter"),x={},ot={},C,at=!1,Ot=6,is=3e5,os=3e4,rt=10,as=3e4,At=10,cs=6e4;async function Ut(s){if(s&&!vt(s))throw new Error(`Invalid customExternalTasksDirPath. The given path '${s}' does not exist`);es.setHttpOptionsDefaults({timeout:1e5});let t=await Bt();C=lt(t),await Ht(t);let e=fs(s);Ft(e).on("add",async n=>{if(j.includes(nt(n)))return dt(n,e)}).on("change",async n=>{if(j.includes(nt(n)))return ds(n,e)}).on("unlink",async n=>{j.includes(nt(n))&&Wt(n)}).on("error",n=>E.error(`Watcher error: ${n}`))}async function dt(s,t){let e=ct(s);if((await Je.readdir(e)).filter(d=>j.includes(d)).length>1){E.error(`Multiple external task files found in directory ${e}. Stopping all external task workers for this directory.`),x[e]&&Wt(s);return}let i=await jt(s),a=Lt(t,e),o=Yt(a),c=it(__dirname,"lib/ExternalTaskWorkerProcess.cjs"),l=Ze(c,{env:{...process.env,PROCESSCUBE_ENGINE_URL:st}});x[e]=l,l.once("disconnect",()=>{delete x[e]}),l.on("error",d=>{E.error(`External Task Worker process error for ${o}`,{error:d,topic:o,workerDirectory:e})}),l.on("exit",(d,f)=>{if(E.info(`External Task Worker process exited for ${o}`,{code:d,signal:f,topic:o,workerDirectory:e}),delete x[e],d===3||d===4)if(us(e)){let u=ot[e]?.count??1,m=Math.min(1e3*Math.pow(2,u-1),os);E.info(`Scheduling restart for ${o} in ${m}ms (attempt ${u}/${Ot})`,{delay:m,restartCount:u,exitCode:d,topic:o,workerDirectory:e}),setTimeout(async()=>{try{if(F&&!at){E.info("Token refresh cycle is not active, restarting it before worker restart");let g=await Bt();C=lt(g),await Ht(g)}await dt(s,t)}catch(g){E.error(`Failed to restart External Task Worker process for ${o}`,{error:g,topic:o,workerDirectory:e})}},m)}else E.error(`External Task Worker process for ${o} reached maximum restart attempts`,{exitCode:d,topic:o,workerDirectory:e})}),l.send({action:"create",payload:{topic:o,identity:C,moduleString:i,workerPath:s}})}async function ds(s,t){let e=ct(s),n=x[e];if(!n)return dt(s,t);let r=await jt(s),i=Lt(t,e),a=Yt(i);n.send({action:"restart",payload:{topic:a,identity:C,moduleString:r,workerPath:s}})}function Wt(s){let t=ct(s),e=x[t];e&&e.kill()}async function Mt(){if(!F)return null;if(!process.env.PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_ID||!process.env.PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_SECRET){let n=new Error("Required environment variables PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_ID and PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_SECRET are missing. For help, please refer to our documentation on environment variables at: https://processcube.io/docs/app-sdk/samples/nextjs/external-task-adapter-with-nextjs#authority");throw E.error("Required environment variables PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_ID and PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_SECRET are missing",{err:n}),n}let s=await ts.discover(process.env.PROCESSCUBE_AUTHORITY_URL);return await new s.Client({client_id:process.env.PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_ID,client_secret:process.env.PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_SECRET}).grant({grant_type:"client_credentials",scope:"engine_etw"})}async function Bt(){if(!F)return null;for(let s=1;s<=rt;s++)try{return await Mt()}catch(t){let e=Math.min(1e3*Math.pow(2,s-1),as);if(E.error(`Failed to fetch initial token set (attempt ${s}/${rt}), retrying in ${e}ms`,{error:t,attempt:s,delay:e}),s===rt)throw t;await new Promise(n=>setTimeout(n,e))}return null}function lt(s){if(!F||s===null)return ns;let t=s.access_token,e=Qe(t);return{token:s.access_token,userId:e.sub}}async function Ht(s){if(!F||s===null||at)return;at=!0;let t=0,n=await ls(s)*rs*1e3,r=async()=>{try{let i=await Mt();C=lt(i);for(let[a,o]of Object.entries(x))try{o.send({action:"updateIdentity",payload:{identity:C}})}catch(c){E.warn(`Failed to send identity update to worker process ${a}`,{sendError:c})}t=0,setTimeout(r,n)}catch(i){t++;let a=Math.min(1e3*Math.pow(2,t-1),cs);t<=At?E.error(`Could not refresh identity (attempt ${t}/${At}), retrying in ${a}ms`,{error:i,attempt:t,delay:a}):E.error(`Could not refresh identity (attempt ${t}), continuing to retry every ${a}ms`,{error:i,attempt:t,delay:a}),setTimeout(r,a)}};setTimeout(r,n)}async function jt(s){let t=await Ve({entryPoints:[s],write:!1,bundle:!0,platform:"node",target:"node18",format:"cjs",external:["@opentelemetry/api"]});if(t.errors.length>0)throw E.error(`Could not transpile file at '${s}'`,{errors:t.errors}),new Error(`Could not transpile file at '${s}'`);return t.warnings.length>0&&E.warn(`Transpiled file at '${s}' with warnings`,{warnings:t.warnings}),t.outputFiles[0].text}async function ls(s){let t=s.expires_in;if(!t&&s.expires_at&&(t=Math.floor(s.expires_at-Date.now()/1e3)),t===void 0)throw new Error("Could not determine the time until the access token for external task workers expires");return t}function Yt(s){return s.replace(/^\.\/+|\([^)]+\)|^\/*|\/*$/g,"").replace(/[\/]{2,}/g,"/")}function fs(s){let t,e=[s,it(process.cwd(),"app"),it(process.cwd(),"src","app")];for(let n of e)if(n&&vt(n)){t=n;break}if(!t)throw new Error("Could not find external tasks directory");return t}function us(s){let t=Date.now(),e=ot[s];return!e||t-e.timestamp>is?(ot[s]={count:1,timestamp:t},!0):e.count>=Ot?!1:(e.count++,!0)}function Js(){return h}import{getToken as zt}from"next-auth/jwt";import{ResponseCookies as hs}from"next/dist/compiled/@edge-runtime/cookies/index.js";import{cookies as Y,headers as Kt}from"next/headers";async function w(){let s=await zt({req:{cookies:await Y(),headers:await Kt()}});if(s?.expiresAt&&Date.now()>=s.expiresAt*1e3){let e=await fetch(`${process.env.NEXTAUTH_URL}/api/auth/session`,{method:"GET",headers:{"Content-Type":"application/json",cookie:(await Y()).toString()}}),n=new hs(e.headers);if(n.getAll().length){let r=!1;try{for(let i of n.getAll())(await Y()).set(i.name,i.value,{...i})}catch{r=!0}if(s=await zt({req:{cookies:r?n:await Y(),headers:await Kt()}}),s?.error)throw s.error}}if(!s?.accessToken||!s?.sub)throw new Error("AccessToken or Sub could not be determined!");return{token:s?.accessToken,userId:s?.sub}}import{DataModels as A}from"@5minds/processcube_engine_client";async function v(){try{return w()}catch{return}}async function $t(s){let t=await v();return(await h.processInstances.query({processInstanceId:s},{identity:t,includeXml:!0})).processInstances[0]}async function qt(s,t={sortSettings:{sortBy:A.FlowNodeInstances.FlowNodeInstanceSortableColumns.createdAt,sortDir:"ASC"}}){return(await h.flowNodeInstances.query({processInstanceId:s},{...t,identity:t.identity??await v()})).flowNodeInstances}async function Gt(s){let t=await v();return(await h.flowNodeInstances.query({triggeredByFlowNodeInstance:s},{identity:t})).flowNodeInstances}async function Xt(s,t,e){let n=await v();await h.processInstances.retryProcessInstance(s,{flowNodeInstanceId:t,newStartToken:e,identity:n})}async function Vt(s){let t=await v();await h.processInstances.terminateProcessInstance(s,t)}async function dn(s={options:{identity:!0}}){switch(s.options.identity){case!0:s.options.identity=await w();break;case!1:s.options.identity=void 0;break;case void 0:s.options.identity=await w();break}return await h.processInstances.query({...s?.query,state:A.ProcessInstances.ProcessInstanceState.running},s?.options)}async function ln(s={},t=!0){let{processInstanceId:e}=s,n=typeof t=="boolean"?t==!0?await w():void 0:t;return new Promise(async(r,i)=>{let a=[],o=async c=>{if(e!==void 0&&c.processInstanceId!==e)return;let d=await h.processInstances.query({processInstanceId:c.processInstanceId},{identity:n});for(let f of a)h.notification.removeSubscription(f,n);return d.totalCount===0?i(new Error(`Process with instance ID "${c.processInstanceId}" does not exist.`)):r(d.processInstances[0])};if(a.push(await h.notification.onProcessEnded(o,{identity:n})),a.push(await h.notification.onProcessError(o,{identity:n})),a.push(await h.notification.onProcessTerminated(o,{identity:n})),e){let c=await h.processInstances.query({processInstanceId:e,state:[A.ProcessInstances.ProcessInstanceState.finished,A.ProcessInstances.ProcessInstanceState.terminated,A.ProcessInstances.ProcessInstanceState.error]},{identity:n});if(c.totalCount>0){for(let l of a)h.notification.removeSubscription(l,n);r(c.processInstances[0])}}})}import{DataModels as P}from"@5minds/processcube_engine_client";import{mapUserTask as Qt,mapUserTaskList as b}from"../common/index.mjs";async function _n(s={},t=!0){let{correlationId:e,processInstanceId:n,flowNodeId:r}=s,i=typeof t=="boolean"?t==!0?await w():void 0:t;return new Promise(async(a,o)=>{let c=await h.userTasks.onUserTaskWaiting(async d=>{let f=e!==void 0&&d.correlationId!==e,u=d.flowNodeInstanceId===void 0,m=n!==void 0&&d.processInstanceId!==n,g=r!==void 0&&d.flowNodeId!==r;if(f||u||m||g)return;let k=await ms(d.flowNodeInstanceId,{identity:i});return h.notification.removeSubscription(c,i),k===null?o(new Error(`UserTask with instance ID "${d.flowNodeInstanceId}" does not exist.`)):a(k)},{identity:i}),l=await ps({correlationId:e,processInstanceId:n,flowNodeId:r,state:P.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:i});l.userTasks.length>0&&(h.notification.removeSubscription(c,i),a(l.userTasks[0]))})}async function gn(s,t={},e={},n=!0){let r=typeof n=="boolean"?n==!0?await w():void 0:n;await h.userTasks.finishUserTask(s,e,r);let i={state:P.FlowNodeInstances.FlowNodeInstanceState.suspended,...t},a=await h.userTasks.query(i,{identity:r});return Qt(a.userTasks[0])}async function ps(s,t={identity:!0}){switch(t?.identity){case!0:t.identity=await w();break;case!1:t.identity=void 0;break;case void 0:t.identity=await w();break}let e=await h.userTasks.query(s,t);return b(e)}async function En(s={identity:!0}){switch(s?.identity){case!0:s.identity=await w();break;case!1:s.identity=void 0;break;case void 0:s.identity=await w();break}let t=await h.userTasks.query({state:P.FlowNodeInstances.FlowNodeInstanceState.suspended},s);return b(t)}async function In(s,t={identity:!0}){switch(t?.identity){case!0:t.identity=await w();break;case!1:t.identity=void 0;break;case void 0:t.identity=await w();break}let e=await h.userTasks.query({processInstanceId:s,state:P.FlowNodeInstances.FlowNodeInstanceState.suspended},t);return b(e)}async function Tn(s,t={identity:!0}){switch(t?.identity){case!0:t.identity=await w();break;case!1:t.identity=void 0;break;case void 0:t.identity=await w();break}let e=await h.userTasks.query({flowNodeId:s,state:P.FlowNodeInstances.FlowNodeInstanceState.suspended},t);return b(e)}async function ms(s,t={identity:!0}){switch(t?.identity){case!0:t.identity=await w();break;case!1:t.identity=void 0;break;case void 0:t.identity=await w();break}let e=await h.userTasks.query({flowNodeInstanceId:s,state:P.FlowNodeInstances.FlowNodeInstanceState.suspended},{...t,limit:1});return e.userTasks.length===0?null:Qt(e.userTasks[0])}async function Pn(s,t={identity:!0}){switch(t?.identity){case!0:t.identity=await w();break;case!1:t.identity=void 0;break;case void 0:t.identity=await w();break}let e=await h.userTasks.query({correlationId:s,state:P.FlowNodeInstances.FlowNodeInstanceState.suspended},t);return b(e)}async function kn(s,t){let e=s||await w(),n=await h.userTasks.query({state:P.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:e,...t}),r=n.userTasks.filter(i=>i.actualOwnerId===e.userId);return n.userTasks=r,b(n)}async function Rn(s,t,e){await h.userTasks.reserveUserTaskInstance(s,t,e||s.userId)}async function xn(s,t){await h.userTasks.cancelUserTaskInstanceReservation(s,t)}async function bn(s,t){let e=s||await w(),n=await h.userTasks.query({state:P.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:e,...t}),r=n.userTasks.filter(i=>i.assignedUserIds?.includes(e.userId));return n.userTasks=r,b(n)}import{PHASE_DEVELOPMENT_SERVER as ys,PHASE_PRODUCTION_BUILD as ws,PHASE_PRODUCTION_SERVER as _s}from"next/dist/shared/lib/constants";var Zt=!1,ft=!1;function Dn(s={}){let{applicationSdk:t,...e}=s;return async(n,r)=>{ft=ft||n===ws;let i=n===ys||n===_s;return t?.useExternalTasks&&i&&!Zt&&!ft&&(Zt=!0,await Ut(t?.customExternalTasksDirPath)),{...e,experimental:{...e.experimental,serverComponentsExternalPackages:[...e.experimental?.serverComponentsExternalPackages||[],"esbuild"]}}}}import{redirect as gs}from"next/navigation";function Ln(s){gs(s)}async function Wn(...s){return await h.processModels.startProcessInstance(...s)}async function Jt(...s){await h.manualTasks.finishManualTask(...s)}async function te(...s){await h.userTasks.finishUserTask(...s)}async function ee(...s){await h.untypedTasks.finishTask(...s)}import{DataModels as Es}from"@5minds/processcube_engine_client";async function Is(){try{return w()}catch{return}}var Vn=async(s,t)=>{let e=await Is();t==="bpmn:UserTask"?await te(s,{},e):t==="bpmn:ManualTask"?await Jt(s,e):t==="bpmn:Task"?await ee(s,e):console.error(`[@5minds/processcube_app_sdk:handlePlay] Unsupported flow node type: ${t}`)},Qn=async s=>{await Vt(s)},Zn=async(s,t,e)=>{await Xt(s,t,e)},Jn=async s=>$t(s),tr=async s=>qt(s,{sortSettings:{sortBy:Es.FlowNodeInstances.FlowNodeInstanceSortableColumns.createdAt,sortDir:"DESC"}}),er=async s=>Gt(s);export{xn as cancelReservedUserTask,Jt as finishManualTask,Vn as finishTask,ee as finishUntypedTask,te as finishUserTask,gn as finishUserTaskAndGetNext,dn as getActiveProcessInstances,bn as getAssignedUserTasksByIdentity,Js as getEngineClient,tr as getFlowNodeInstances,qt as getFlowNodeInstancesByProcessInstanceId,Gt as getFlowNodeInstancesTriggeredByFlowNodeInstanceIds,w as getIdentity,Jn as getProcessInstance,$t as getProcessInstanceById,kn as getReservedUserTasksByIdentity,er as getTriggeredFlowNodeInstances,ps as getUserTasks,ms as getWaitingUserTaskByFlowNodeInstanceId,En as getWaitingUserTasks,Pn as getWaitingUserTasksByCorrelationId,Tn as getWaitingUserTasksByFlowNodeId,In as getWaitingUserTasksByProcessInstanceId,Ln as navigateToUrl,Rn as reserveUserTask,Zn as retryProcess,Xt as retryProcessInstance,Wn as startProcess,Qn as terminateProcess,Vt as terminateProcessInstance,ln as waitForProcessEnd,_n as waitForUserTask,Dn as withApplicationSdk};
1
+ import"only-server";import"../common/index.mjs";import{stat as Fe}from"fs";import{stat as Ae,readdir as ve}from"fs/promises";import{EventEmitter as Le}from"events";import*as p from"path";import{stat as ne,lstat as ut,readdir as re,realpath as ie}from"node:fs/promises";import{Readable as oe}from"node:stream";import{resolve as ht,relative as ae,join as ce,sep as de}from"node:path";var I={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},z={root:".",fileFilter:s=>!0,directoryFilter:s=>!0,type:I.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(z);var wt="READDIRP_RECURSIVE_ERROR",le=new Set(["ENOENT","EPERM","EACCES","ELOOP",wt]),pt=[I.DIR_TYPE,I.EVERYTHING_TYPE,I.FILE_DIR_TYPE,I.FILE_TYPE],fe=new Set([I.DIR_TYPE,I.EVERYTHING_TYPE,I.FILE_DIR_TYPE]),ue=new Set([I.EVERYTHING_TYPE,I.FILE_DIR_TYPE,I.FILE_TYPE]),he=s=>le.has(s.code),pe=process.platform==="win32",mt=s=>!0,yt=s=>{if(s===void 0)return mt;if(typeof s=="function")return s;if(typeof s=="string"){let t=s.trim();return e=>e.basename===t}if(Array.isArray(s)){let t=s.map(e=>e.trim());return e=>t.some(n=>e.basename===n)}return mt},K=class extends oe{constructor(t={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:t.highWaterMark});let e={...z,...t},{root:n,type:r}=e;this._fileFilter=yt(e.fileFilter),this._directoryFilter=yt(e.directoryFilter);let i=e.lstat?ut:ne;pe?this._stat=a=>i(a,{bigint:!0}):this._stat=i,this._maxDepth=e.depth??z.depth,this._wantsDir=r?fe.has(r):!1,this._wantsFile=r?ue.has(r):!1,this._wantsEverything=r===I.EVERYTHING_TYPE,this._root=ht(n),this._isDirent=!e.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent},this.parents=[this._exploreDir(n,1)],this.reading=!1,this.parent=void 0}async _read(t){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&t>0;){let e=this.parent,n=e&&e.files;if(n&&n.length>0){let{path:r,depth:i}=e,a=n.splice(0,t).map(c=>this._formatEntry(c,r)),o=await Promise.all(a);for(let c of o){if(!c)continue;if(this.destroyed)return;let l=await this._getEntryType(c);l==="directory"&&this._directoryFilter(c)?(i<=this._maxDepth&&this.parents.push(this._exploreDir(c.fullPath,i+1)),this._wantsDir&&(this.push(c),t--)):(l==="file"||this._includeAsFile(c))&&this._fileFilter(c)&&this._wantsFile&&(this.push(c),t--)}}else{let r=this.parents.pop();if(!r){this.push(null);break}if(this.parent=await r,this.destroyed)return}}}catch(e){this.destroy(e)}finally{this.reading=!1}}}async _exploreDir(t,e){let n;try{n=await re(t,this._rdOptions)}catch(r){this._onError(r)}return{files:n,depth:e,path:t}}async _formatEntry(t,e){let n,r=this._isDirent?t.name:t;try{let i=ht(ce(e,r));n={path:ae(this._root,i),fullPath:i,basename:r},n[this._statsProp]=this._isDirent?t:await this._stat(i)}catch(i){this._onError(i);return}return n}_onError(t){he(t)&&!this.destroyed?this.emit("warn",t):this.destroy(t)}async _getEntryType(t){if(!t&&this._statsProp in t)return"";let e=t[this._statsProp];if(e.isFile())return"file";if(e.isDirectory())return"directory";if(e&&e.isSymbolicLink()){let n=t.fullPath;try{let r=await ie(n),i=await ut(r);if(i.isFile())return"file";if(i.isDirectory()){let a=r.length;if(n.startsWith(r)&&n.substr(a,1)===de){let o=new Error(`Circular symlink detected: "${n}" points to "${r}"`);return o.code=wt,this._onError(o)}return"directory"}}catch(r){return this._onError(r),""}}}_includeAsFile(t){let e=t&&t[this._statsProp];return e&&this._wantsEverything&&!e.isDirectory()}};function _t(s,t={}){let e=t.entryType||t.type;if(e==="both"&&(e=I.FILE_DIR_TYPE),e&&(t.type=e),s){if(typeof s!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(e&&!pt.includes(e))throw new Error(`readdirp: Invalid type passed. Use one of ${pt.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return t.root=s,new K(t)}import{watchFile as me,unwatchFile as gt,watch as ye}from"fs";import{open as we,stat as It,lstat as _e,realpath as $}from"fs/promises";import*as y from"path";import{type as ge}from"os";var Ee="data",X="end",Tt="close",M=()=>{};var B=process.platform,V=B==="win32",Ie=B==="darwin",Te=B==="linux",Pe=B==="freebsd",Pt=ge()==="OS400",_={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},T=_,ke="watch",Re={lstat:_e,stat:It},R="listeners",L="errHandlers",S="rawEmitters",xe=[R,L,S],be=new Set(["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]),Se=s=>be.has(y.extname(s).slice(1).toLowerCase()),G=(s,t)=>{s instanceof Set?s.forEach(t):t(s)},N=(s,t,e)=>{let n=s[t];n instanceof Set||(s[t]=n=new Set([n])),n.add(e)},Ce=s=>t=>{let e=s[t];e instanceof Set?e.clear():delete s[t]},D=(s,t,e)=>{let n=s[t];n instanceof Set?n.delete(e):n===e&&delete s[t]},kt=s=>s instanceof Set?s.size===0:!s,O=new Map;function Et(s,t,e,n,r){let i=(a,o)=>{e(s),r(a,o,{watchedPath:s}),o&&s!==o&&U(y.resolve(s,o),R,y.join(s,o))};try{return ye(s,{persistent:t.persistent},i)}catch(a){n(a);return}}var U=(s,t,e,n,r)=>{let i=O.get(s);i&&G(i[t],a=>{a(e,n,r)})},Ne=(s,t,e,n)=>{let{listener:r,errHandler:i,rawEmitter:a}=n,o=O.get(t),c;if(!e.persistent)return c=Et(s,e,r,i,a),c?c.close.bind(c):void 0;if(o)N(o,R,r),N(o,L,i),N(o,S,a);else{if(c=Et(s,e,U.bind(null,t,R),i,U.bind(null,t,S)),!c)return;c.on(T.ERROR,async l=>{let d=U.bind(null,t,L);if(o&&(o.watcherUnusable=!0),V&&l.code==="EPERM")try{await(await we(s,"r")).close(),d(l)}catch{}else d(l)}),o={listeners:r,errHandlers:i,rawEmitters:a,watcher:c},O.set(t,o)}return()=>{D(o,R,r),D(o,L,i),D(o,S,a),kt(o.listeners)&&(o.watcher.close(),O.delete(t),xe.forEach(Ce(o)),o.watcher=void 0,Object.freeze(o))}},q=new Map,De=(s,t,e,n)=>{let{listener:r,rawEmitter:i}=n,a=q.get(t),o=a&&a.options;return o&&(o.persistent<e.persistent||o.interval>e.interval)&&(gt(t),a=void 0),a?(N(a,R,r),N(a,S,i)):(a={listeners:r,rawEmitters:i,options:e,watcher:me(t,e,(c,l)=>{G(a.rawEmitters,f=>{f(T.CHANGE,t,{curr:c,prev:l})});let d=c.mtimeMs;(c.size!==l.size||d>l.mtimeMs||d===0)&&G(a.listeners,f=>f(s,c))})},q.set(t,a)),()=>{D(a,R,r),D(a,S,i),kt(a.listeners)&&(q.delete(t),gt(t),a.options=a.watcher=void 0,Object.freeze(a))}},W=class{constructor(t){this.fsw=t,this._boundHandleError=e=>t._handleError(e)}_watchWithNodeFs(t,e){let n=this.fsw.options,r=y.dirname(t),i=y.basename(t);this.fsw._getWatchedDir(r).add(i);let o=y.resolve(t),c={persistent:n.persistent};e||(e=M);let l;if(n.usePolling){let d=n.interval!==n.binaryInterval;c.interval=d&&Se(i)?n.binaryInterval:n.interval,l=De(t,o,c,{listener:e,rawEmitter:this.fsw._emitRaw})}else l=Ne(t,o,c,{listener:e,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return l}_handleFile(t,e,n){if(this.fsw.closed)return;let r=y.dirname(t),i=y.basename(t),a=this.fsw._getWatchedDir(r),o=e;if(a.has(i))return;let c=async(d,f)=>{if(this.fsw._throttle(ke,t,5)){if(!f||f.mtimeMs===0)try{let u=await It(t);if(this.fsw.closed)return;let m=u.atimeMs,g=u.mtimeMs;if((!m||m<=g||g!==o.mtimeMs)&&this.fsw._emit(T.CHANGE,t,u),(Ie||Te||Pe)&&o.ino!==u.ino){this.fsw._closeFile(d),o=u;let k=this._watchWithNodeFs(t,c);k&&this.fsw._addPathCloser(d,k)}else o=u}catch{this.fsw._remove(r,i)}else if(a.has(i)){let u=f.atimeMs,m=f.mtimeMs;(!u||u<=m||m!==o.mtimeMs)&&this.fsw._emit(T.CHANGE,t,f),o=f}}},l=this._watchWithNodeFs(t,c);if(!(n&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(t)){if(!this.fsw._throttle(T.ADD,t,0))return;this.fsw._emit(T.ADD,t,e)}return l}async _handleSymlink(t,e,n,r){if(this.fsw.closed)return;let i=t.fullPath,a=this.fsw._getWatchedDir(e);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let o;try{o=await $(n)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(a.has(r)?this.fsw._symlinkPaths.get(i)!==o&&(this.fsw._symlinkPaths.set(i,o),this.fsw._emit(T.CHANGE,n,t.stats)):(a.add(r),this.fsw._symlinkPaths.set(i,o),this.fsw._emit(T.ADD,n,t.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(i))return!0;this.fsw._symlinkPaths.set(i,!0)}_handleRead(t,e,n,r,i,a,o){if(t=y.join(t,""),o=this.fsw._throttle("readdir",t,1e3),!o)return;let c=this.fsw._getWatchedDir(n.path),l=new Set,d=this.fsw._readdirp(t,{fileFilter:f=>n.filterPath(f),directoryFilter:f=>n.filterDir(f)});if(d)return d.on(Ee,async f=>{if(this.fsw.closed){d=void 0;return}let u=f.path,m=y.join(t,u);if(l.add(u),!(f.stats.isSymbolicLink()&&await this._handleSymlink(f,t,m,u))){if(this.fsw.closed){d=void 0;return}(u===r||!r&&!c.has(u))&&(this.fsw._incrReadyCount(),m=y.join(i,y.relative(i,m)),this._addToNodeFs(m,e,n,a+1))}}).on(T.ERROR,this._boundHandleError),new Promise((f,u)=>{if(!d)return u();d.once(X,()=>{if(this.fsw.closed){d=void 0;return}let m=o?o.clear():!1;f(void 0),c.getChildren().filter(g=>g!==t&&!l.has(g)).forEach(g=>{this.fsw._remove(t,g)}),d=void 0,m&&this._handleRead(t,!1,n,r,i,a,o)})})}async _handleDir(t,e,n,r,i,a,o){let c=this.fsw._getWatchedDir(y.dirname(t)),l=c.has(y.basename(t));!(n&&this.fsw.options.ignoreInitial)&&!i&&!l&&this.fsw._emit(T.ADD_DIR,t,e),c.add(y.basename(t)),this.fsw._getWatchedDir(t);let d,f,u=this.fsw.options.depth;if((u==null||r<=u)&&!this.fsw._symlinkPaths.has(o)){if(!i&&(await this._handleRead(t,n,a,i,t,r,d),this.fsw.closed))return;f=this._watchWithNodeFs(t,(m,g)=>{g&&g.mtimeMs===0||this._handleRead(m,!1,a,i,t,r,d)})}return f}async _addToNodeFs(t,e,n,r,i){let a=this.fsw._emitReady;if(this.fsw._isIgnored(t)||this.fsw.closed)return a(),!1;let o=this.fsw._getWatchHelpers(t);n&&(o.filterPath=c=>n.filterPath(c),o.filterDir=c=>n.filterDir(c));try{let c=await Re[o.statMethod](o.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(o.watchPath,c))return a(),!1;let l=this.fsw.options.followSymlinks,d;if(c.isDirectory()){let f=y.resolve(t),u=l?await $(t):t;if(this.fsw.closed||(d=await this._handleDir(o.watchPath,c,e,r,i,o,u),this.fsw.closed))return;f!==u&&u!==void 0&&this.fsw._symlinkPaths.set(f,u)}else if(c.isSymbolicLink()){let f=l?await $(t):t;if(this.fsw.closed)return;let u=y.dirname(o.watchPath);if(this.fsw._getWatchedDir(u).add(o.watchPath),this.fsw._emit(T.ADD,o.watchPath,c),d=await this._handleDir(u,c,e,r,t,o,f),this.fsw.closed)return;f!==void 0&&this.fsw._symlinkPaths.set(y.resolve(t),f)}else d=this._handleFile(o.watchPath,c,e);return a(),d&&this.fsw._addPathCloser(t,d),!1}catch(c){if(this.fsw._handleError(c))return a(),t}}};var Q="/",Oe="//",Nt=".",Ue="..",We="string",Me=/\\/g,Rt=/\/\//,Be=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,He=/^\.[/\\]/;function H(s){return Array.isArray(s)?s:[s]}var Z=s=>typeof s=="object"&&s!==null&&!(s instanceof RegExp);function je(s){return typeof s=="function"?s:typeof s=="string"?t=>s===t:s instanceof RegExp?t=>s.test(t):typeof s=="object"&&s!==null?t=>{if(s.path===t)return!0;if(s.recursive){let e=p.relative(s.path,t);return e?!e.startsWith("..")&&!p.isAbsolute(e):!1}return!1}:()=>!1}function Ye(s){if(typeof s!="string")throw new Error("string expected");s=p.normalize(s),s=s.replace(/\\/g,"/");let t=!1;s.startsWith("//")&&(t=!0);let e=/\/\//;for(;s.match(e);)s=s.replace(e,"/");return t&&(s="/"+s),s}function xt(s,t,e){let n=Ye(t);for(let r=0;r<s.length;r++){let i=s[r];if(i(n,e))return!0}return!1}function ze(s,t){if(s==null)throw new TypeError("anymatch: specify first argument");let n=H(s).map(r=>je(r));return t==null?(r,i)=>xt(n,r,i):xt(n,t)}var bt=s=>{let t=H(s).flat();if(!t.every(e=>typeof e===We))throw new TypeError(`Non-string provided as watch path: ${t}`);return t.map(Dt)},St=s=>{let t=s.replace(Me,Q),e=!1;for(t.startsWith(Oe)&&(e=!0);t.match(Rt);)t=t.replace(Rt,Q);return e&&(t=Q+t),t},Dt=s=>St(p.normalize(St(s))),Ct=(s="")=>t=>typeof t=="string"?Dt(p.isAbsolute(t)?t:p.join(s,t)):t,Ke=(s,t)=>p.isAbsolute(s)?s:p.join(t,s),$e=Object.freeze(new Set),J=class{constructor(t,e){this.path=t,this._removeWatcher=e,this.items=new Set}add(t){let{items:e}=this;e&&t!==Nt&&t!==Ue&&e.add(t)}async remove(t){let{items:e}=this;if(!e||(e.delete(t),e.size>0))return;let n=this.path;try{await ve(n)}catch{this._removeWatcher&&this._removeWatcher(p.dirname(n),p.basename(n))}}has(t){let{items:e}=this;if(e)return e.has(t)}getChildren(){let{items:t}=this;return t?[...t.values()]:[]}dispose(){this.items.clear(),this.path="",this._removeWatcher=M,this.items=$e,Object.freeze(this)}},qe="stat",Ge="lstat",tt=class{constructor(t,e,n){this.fsw=n;let r=t;this.path=t=t.replace(He,""),this.watchPath=r,this.fullWatchPath=p.resolve(r),this.dirParts=[],this.dirParts.forEach(i=>{i.length>1&&i.pop()}),this.followSymlinks=e,this.statMethod=e?qe:Ge}entryPath(t){return p.join(this.watchPath,p.relative(this.watchPath,t.fullPath))}filterPath(t){let{stats:e}=t;if(e&&e.isSymbolicLink())return this.filterDir(t);let n=this.entryPath(t);return this.fsw._isntIgnored(n,e)&&this.fsw._hasReadPermissions(e)}filterDir(t){return this.fsw._isntIgnored(this.entryPath(t),t.stats)}},et=class extends Le{constructor(t={}){super(),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let e=t.awaitWriteFinish,n={stabilityThreshold:2e3,pollInterval:100},r={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...t,ignored:t.ignored?H(t.ignored):H([]),awaitWriteFinish:e===!0?n:typeof e=="object"?{...n,...e}:!1};Pt&&(r.usePolling=!0),r.atomic===void 0&&(r.atomic=!r.usePolling);let i=process.env.CHOKIDAR_USEPOLLING;if(i!==void 0){let c=i.toLowerCase();c==="false"||c==="0"?r.usePolling=!1:c==="true"||c==="1"?r.usePolling=!0:r.usePolling=!!c}let a=process.env.CHOKIDAR_INTERVAL;a&&(r.interval=Number.parseInt(a,10));let o=0;this._emitReady=()=>{o++,o>=this._readyCount&&(this._emitReady=M,this._readyEmitted=!0,process.nextTick(()=>this.emit(_.READY)))},this._emitRaw=(...c)=>this.emit(_.RAW,...c),this._boundRemove=this._remove.bind(this),this.options=r,this._nodeFsHandler=new W(this),Object.freeze(r)}_addIgnoredPath(t){if(Z(t)){for(let e of this._ignoredPaths)if(Z(e)&&e.path===t.path&&e.recursive===t.recursive)return}this._ignoredPaths.add(t)}_removeIgnoredPath(t){if(this._ignoredPaths.delete(t),typeof t=="string")for(let e of this._ignoredPaths)Z(e)&&e.path===t&&this._ignoredPaths.delete(e)}add(t,e,n){let{cwd:r}=this.options;this.closed=!1,this._closePromise=void 0;let i=bt(t);return r&&(i=i.map(a=>Ke(a,r))),i.forEach(a=>{this._removeIgnoredPath(a)}),this._userIgnored=void 0,this._readyCount||(this._readyCount=0),this._readyCount+=i.length,Promise.all(i.map(async a=>{let o=await this._nodeFsHandler._addToNodeFs(a,!n,void 0,0,e);return o&&this._emitReady(),o})).then(a=>{this.closed||a.forEach(o=>{o&&this.add(p.dirname(o),p.basename(e||o))})}),this}unwatch(t){if(this.closed)return this;let e=bt(t),{cwd:n}=this.options;return e.forEach(r=>{!p.isAbsolute(r)&&!this._closers.has(r)&&(n&&(r=p.join(n,r)),r=p.resolve(r)),this._closePath(r),this._addIgnoredPath(r),this._watched.has(r)&&this._addIgnoredPath({path:r,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let t=[];return this._closers.forEach(e=>e.forEach(n=>{let r=n();r instanceof Promise&&t.push(r)})),this._streams.forEach(e=>e.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(e=>e.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=t.length?Promise.all(t).then(()=>{}):Promise.resolve(),this._closePromise}getWatched(){let t={};return this._watched.forEach((e,n)=>{let i=(this.options.cwd?p.relative(this.options.cwd,n):n)||Nt;t[i]=e.getChildren().sort()}),t}emitWithAll(t,e){this.emit(t,...e),t!==_.ERROR&&this.emit(_.ALL,t,...e)}async _emit(t,e,n){if(this.closed)return;let r=this.options;V&&(e=p.normalize(e)),r.cwd&&(e=p.relative(r.cwd,e));let i=[e];n!=null&&i.push(n);let a=r.awaitWriteFinish,o;if(a&&(o=this._pendingWrites.get(e)))return o.lastChange=new Date,this;if(r.atomic){if(t===_.UNLINK)return this._pendingUnlinks.set(e,[t,...i]),setTimeout(()=>{this._pendingUnlinks.forEach((c,l)=>{this.emit(...c),this.emit(_.ALL,...c),this._pendingUnlinks.delete(l)})},typeof r.atomic=="number"?r.atomic:100),this;t===_.ADD&&this._pendingUnlinks.has(e)&&(t=_.CHANGE,this._pendingUnlinks.delete(e))}if(a&&(t===_.ADD||t===_.CHANGE)&&this._readyEmitted){let c=(l,d)=>{l?(t=_.ERROR,i[0]=l,this.emitWithAll(t,i)):d&&(i.length>1?i[1]=d:i.push(d),this.emitWithAll(t,i))};return this._awaitWriteFinish(e,a.stabilityThreshold,t,c),this}if(t===_.CHANGE&&!this._throttle(_.CHANGE,e,50))return this;if(r.alwaysStat&&n===void 0&&(t===_.ADD||t===_.ADD_DIR||t===_.CHANGE)){let c=r.cwd?p.join(r.cwd,e):e,l;try{l=await Ae(c)}catch{}if(!l||this.closed)return;i.push(l)}return this.emitWithAll(t,i),this}_handleError(t){let e=t&&t.code;return t&&e!=="ENOENT"&&e!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||e!=="EPERM"&&e!=="EACCES")&&this.emit(_.ERROR,t),t||this.closed}_throttle(t,e,n){this._throttled.has(t)||this._throttled.set(t,new Map);let r=this._throttled.get(t);if(!r)throw new Error("invalid throttle");let i=r.get(e);if(i)return i.count++,!1;let a,o=()=>{let l=r.get(e),d=l?l.count:0;return r.delete(e),clearTimeout(a),l&&clearTimeout(l.timeoutObject),d};a=setTimeout(o,n);let c={timeoutObject:a,clear:o,count:0};return r.set(e,c),c}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(t,e,n,r){let i=this.options.awaitWriteFinish;if(typeof i!="object")return;let a=i.pollInterval,o,c=t;this.options.cwd&&!p.isAbsolute(t)&&(c=p.join(this.options.cwd,t));let l=new Date,d=this._pendingWrites;function f(u){Fe(c,(m,g)=>{if(m||!d.has(t)){m&&m.code!=="ENOENT"&&r(m);return}let k=Number(new Date);u&&g.size!==u.size&&(d.get(t).lastChange=k);let se=d.get(t);k-se.lastChange>=e?(d.delete(t),r(void 0,g)):o=setTimeout(f,a,g)})}d.has(t)||(d.set(t,{lastChange:l,cancelWait:()=>(d.delete(t),clearTimeout(o),n)}),o=setTimeout(f,a))}_isIgnored(t,e){if(this.options.atomic&&Be.test(t))return!0;if(!this._userIgnored){let{cwd:n}=this.options,i=(this.options.ignored||[]).map(Ct(n)),o=[...[...this._ignoredPaths].map(Ct(n)),...i];this._userIgnored=ze(o,void 0)}return this._userIgnored(t,e)}_isntIgnored(t,e){return!this._isIgnored(t,e)}_getWatchHelpers(t){return new tt(t,this.options.followSymlinks,this)}_getWatchedDir(t){let e=p.resolve(t);return this._watched.has(e)||this._watched.set(e,new J(e,this._boundRemove)),this._watched.get(e)}_hasReadPermissions(t){return this.options.ignorePermissionErrors?!0:!!(Number(t.mode)&256)}_remove(t,e,n){let r=p.join(t,e),i=p.resolve(r);if(n=n??(this._watched.has(r)||this._watched.has(i)),!this._throttle("remove",r,100))return;!n&&this._watched.size===1&&this.add(t,e,!0),this._getWatchedDir(r).getChildren().forEach(u=>this._remove(r,u));let c=this._getWatchedDir(t),l=c.has(e);c.remove(e),this._symlinkPaths.has(i)&&this._symlinkPaths.delete(i);let d=r;if(this.options.cwd&&(d=p.relative(this.options.cwd,r)),this.options.awaitWriteFinish&&this._pendingWrites.has(d)&&this._pendingWrites.get(d).cancelWait()===_.ADD)return;this._watched.delete(r),this._watched.delete(i);let f=n?_.UNLINK_DIR:_.UNLINK;l&&!this._isIgnored(r)&&this._emit(f,r),this._closePath(r)}_closePath(t){this._closeFile(t);let e=p.dirname(t);this._getWatchedDir(e).remove(p.basename(t))}_closeFile(t){let e=this._closers.get(t);e&&(e.forEach(n=>n()),this._closers.delete(t))}_addPathCloser(t,e){if(!e)return;let n=this._closers.get(t);n||(n=[],this._closers.set(t,n)),n.push(e)}_readdirp(t,e){if(this.closed)return;let n={type:_.ALL,alwaysStat:!0,lstat:!0,...e,depth:0},r=_t(t,n);return this._streams.add(r),r.once(Tt,()=>{r=void 0}),r.once(X,()=>{r&&(this._streams.delete(r),r=void 0)}),r}};function Ft(s,t={}){let e=new et(t);return e.add(s),e}import{build as Ve}from"esbuild";import{jwtDecode as Qe}from"jwt-decode";import{fork as Ze}from"node:child_process";import{existsSync as vt,promises as Je}from"node:fs";import{basename as nt,dirname as ct,join as it,relative as Lt}from"node:path";import{Issuer as ts,custom as es}from"openid-client";import{Logger as ss}from"@5minds/processcube_engine_sdk";import{EngineClient as Xe}from"@5minds/processcube_engine_client";var st=process.env.PROCESSCUBE_ENGINE_URL??"http://localhost:10560",h=new Xe(st);var ns={token:"ZHVtbXlfdG9rZW4=",userId:"dummy_token"},rs=.85,j=["external_task.ts","external_task.js"],F=process.env.PROCESSCUBE_AUTHORITY_URL!==void 0,E=new ss("processcube_app_sdk:external_task_adapter"),x={},ot={},C,at=!1,Ot=6,is=3e5,os=3e4,rt=10,as=3e4,At=10,cs=6e4;async function Ut(s){if(s&&!vt(s))throw new Error(`Invalid customExternalTasksDirPath. The given path '${s}' does not exist`);es.setHttpOptionsDefaults({timeout:1e5});let t=await Bt();C=lt(t),await Ht(t);let e=fs(s);Ft(e).on("add",async n=>{if(j.includes(nt(n)))return dt(n,e)}).on("change",async n=>{if(j.includes(nt(n)))return ds(n,e)}).on("unlink",async n=>{j.includes(nt(n))&&Wt(n)}).on("error",n=>E.error(`Watcher error: ${n}`))}async function dt(s,t){let e=ct(s);if((await Je.readdir(e)).filter(d=>j.includes(d)).length>1){E.error(`Multiple external task files found in directory ${e}. Stopping all external task workers for this directory.`),x[e]&&Wt(s);return}let i=await jt(s),a=Lt(t,e),o=Yt(a),c=it(__dirname,"lib/ExternalTaskWorkerProcess.cjs"),l=Ze(c,{stdio:["pipe","inherit","inherit","ipc"],env:{...process.env,PROCESSCUBE_ENGINE_URL:st}});x[e]=l,l.once("disconnect",()=>{delete x[e]}),l.on("error",d=>{E.error(`External Task Worker process error for ${o}`,{error:d,topic:o,workerDirectory:e})}),l.on("exit",(d,f)=>{if(E.info(`External Task Worker process exited for ${o}`,{code:d,signal:f,topic:o,workerDirectory:e}),delete x[e],d===3||d===4)if(us(e)){let u=ot[e]?.count??1,m=Math.min(1e3*Math.pow(2,u-1),os);E.info(`Scheduling restart for ${o} in ${m}ms (attempt ${u}/${Ot})`,{delay:m,restartCount:u,exitCode:d,topic:o,workerDirectory:e}),setTimeout(async()=>{try{if(F&&!at){E.info("Token refresh cycle is not active, restarting it before worker restart");let g=await Bt();C=lt(g),await Ht(g)}await dt(s,t)}catch(g){E.error(`Failed to restart External Task Worker process for ${o}`,{error:g,topic:o,workerDirectory:e})}},m)}else E.error(`External Task Worker process for ${o} reached maximum restart attempts`,{exitCode:d,topic:o,workerDirectory:e})}),l.send({action:"create",payload:{topic:o,identity:C,moduleString:i,workerPath:s}})}async function ds(s,t){let e=ct(s),n=x[e];if(!n)return dt(s,t);let r=await jt(s),i=Lt(t,e),a=Yt(i);n.send({action:"restart",payload:{topic:a,identity:C,moduleString:r,workerPath:s}})}function Wt(s){let t=ct(s),e=x[t];e&&e.kill()}async function Mt(){if(!F)return null;if(!process.env.PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_ID||!process.env.PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_SECRET){let n=new Error("Required environment variables PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_ID and PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_SECRET are missing. For help, please refer to our documentation on environment variables at: https://processcube.io/docs/app-sdk/samples/nextjs/external-task-adapter-with-nextjs#authority");throw E.error("Required environment variables PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_ID and PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_SECRET are missing",{err:n}),n}let s=await ts.discover(process.env.PROCESSCUBE_AUTHORITY_URL);return await new s.Client({client_id:process.env.PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_ID,client_secret:process.env.PROCESSCUBE_EXTERNAL_TASK_WORKER_CLIENT_SECRET}).grant({grant_type:"client_credentials",scope:"engine_etw"})}async function Bt(){if(!F)return null;for(let s=1;s<=rt;s++)try{return await Mt()}catch(t){let e=Math.min(1e3*Math.pow(2,s-1),as);if(E.error(`Failed to fetch initial token set (attempt ${s}/${rt}), retrying in ${e}ms`,{error:t,attempt:s,delay:e}),s===rt)throw t;await new Promise(n=>setTimeout(n,e))}return null}function lt(s){if(!F||s===null)return ns;let t=s.access_token,e=Qe(t);return{token:s.access_token,userId:e.sub}}async function Ht(s){if(!F||s===null||at)return;at=!0;let t=0,n=await ls(s)*rs*1e3,r=async()=>{try{let i=await Mt();C=lt(i);for(let[a,o]of Object.entries(x))try{o.send({action:"updateIdentity",payload:{identity:C}})}catch(c){E.warn(`Failed to send identity update to worker process ${a}`,{sendError:c})}t=0,setTimeout(r,n)}catch(i){t++;let a=Math.min(1e3*Math.pow(2,t-1),cs);t<=At?E.error(`Could not refresh identity (attempt ${t}/${At}), retrying in ${a}ms`,{error:i,attempt:t,delay:a}):E.error(`Could not refresh identity (attempt ${t}), continuing to retry every ${a}ms`,{error:i,attempt:t,delay:a}),setTimeout(r,a)}};setTimeout(r,n)}async function jt(s){let t=await Ve({entryPoints:[s],write:!1,bundle:!0,platform:"node",target:"node18",format:"cjs",external:["@opentelemetry/api"]});if(t.errors.length>0)throw E.error(`Could not transpile file at '${s}'`,{errors:t.errors}),new Error(`Could not transpile file at '${s}'`);return t.warnings.length>0&&E.warn(`Transpiled file at '${s}' with warnings`,{warnings:t.warnings}),t.outputFiles[0].text}async function ls(s){let t=s.expires_in;if(!t&&s.expires_at&&(t=Math.floor(s.expires_at-Date.now()/1e3)),t===void 0)throw new Error("Could not determine the time until the access token for external task workers expires");return t}function Yt(s){return s.replace(/^\.\/+|\([^)]+\)|^\/*|\/*$/g,"").replace(/[\/]{2,}/g,"/")}function fs(s){let t,e=[s,it(process.cwd(),"app"),it(process.cwd(),"src","app")];for(let n of e)if(n&&vt(n)){t=n;break}if(!t)throw new Error("Could not find external tasks directory");return t}function us(s){let t=Date.now(),e=ot[s];return!e||t-e.timestamp>is?(ot[s]={count:1,timestamp:t},!0):e.count>=Ot?!1:(e.count++,!0)}function Js(){return h}import{getToken as zt}from"next-auth/jwt";import{ResponseCookies as hs}from"next/dist/compiled/@edge-runtime/cookies/index.js";import{cookies as Y,headers as Kt}from"next/headers";async function w(){let s=await zt({req:{cookies:await Y(),headers:await Kt()}});if(s?.expiresAt&&Date.now()>=s.expiresAt*1e3){let e=await fetch(`${process.env.NEXTAUTH_URL}/api/auth/session`,{method:"GET",headers:{"Content-Type":"application/json",cookie:(await Y()).toString()}}),n=new hs(e.headers);if(n.getAll().length){let r=!1;try{for(let i of n.getAll())(await Y()).set(i.name,i.value,{...i})}catch{r=!0}if(s=await zt({req:{cookies:r?n:await Y(),headers:await Kt()}}),s?.error)throw s.error}}if(!s?.accessToken||!s?.sub)throw new Error("AccessToken or Sub could not be determined!");return{token:s?.accessToken,userId:s?.sub}}import{DataModels as A}from"@5minds/processcube_engine_client";async function v(){try{return w()}catch{return}}async function $t(s){let t=await v();return(await h.processInstances.query({processInstanceId:s},{identity:t,includeXml:!0})).processInstances[0]}async function qt(s,t={sortSettings:{sortBy:A.FlowNodeInstances.FlowNodeInstanceSortableColumns.createdAt,sortDir:"ASC"}}){return(await h.flowNodeInstances.query({processInstanceId:s},{...t,identity:t.identity??await v()})).flowNodeInstances}async function Gt(s){let t=await v();return(await h.flowNodeInstances.query({triggeredByFlowNodeInstance:s},{identity:t})).flowNodeInstances}async function Xt(s,t,e){let n=await v();await h.processInstances.retryProcessInstance(s,{flowNodeInstanceId:t,newStartToken:e,identity:n})}async function Vt(s){let t=await v();await h.processInstances.terminateProcessInstance(s,t)}async function dn(s={options:{identity:!0}}){switch(s.options.identity){case!0:s.options.identity=await w();break;case!1:s.options.identity=void 0;break;case void 0:s.options.identity=await w();break}return await h.processInstances.query({...s?.query,state:A.ProcessInstances.ProcessInstanceState.running},s?.options)}async function ln(s={},t=!0){let{processInstanceId:e}=s,n=typeof t=="boolean"?t==!0?await w():void 0:t;return new Promise(async(r,i)=>{let a=[],o=async c=>{if(e!==void 0&&c.processInstanceId!==e)return;let d=await h.processInstances.query({processInstanceId:c.processInstanceId},{identity:n});for(let f of a)h.notification.removeSubscription(f,n);return d.totalCount===0?i(new Error(`Process with instance ID "${c.processInstanceId}" does not exist.`)):r(d.processInstances[0])};if(a.push(await h.notification.onProcessEnded(o,{identity:n})),a.push(await h.notification.onProcessError(o,{identity:n})),a.push(await h.notification.onProcessTerminated(o,{identity:n})),e){let c=await h.processInstances.query({processInstanceId:e,state:[A.ProcessInstances.ProcessInstanceState.finished,A.ProcessInstances.ProcessInstanceState.terminated,A.ProcessInstances.ProcessInstanceState.error]},{identity:n});if(c.totalCount>0){for(let l of a)h.notification.removeSubscription(l,n);r(c.processInstances[0])}}})}import{DataModels as P}from"@5minds/processcube_engine_client";import{mapUserTask as Qt,mapUserTaskList as b}from"../common/index.mjs";async function _n(s={},t=!0){let{correlationId:e,processInstanceId:n,flowNodeId:r}=s,i=typeof t=="boolean"?t==!0?await w():void 0:t;return new Promise(async(a,o)=>{let c=await h.userTasks.onUserTaskWaiting(async d=>{let f=e!==void 0&&d.correlationId!==e,u=d.flowNodeInstanceId===void 0,m=n!==void 0&&d.processInstanceId!==n,g=r!==void 0&&d.flowNodeId!==r;if(f||u||m||g)return;let k=await ms(d.flowNodeInstanceId,{identity:i});return h.notification.removeSubscription(c,i),k===null?o(new Error(`UserTask with instance ID "${d.flowNodeInstanceId}" does not exist.`)):a(k)},{identity:i}),l=await ps({correlationId:e,processInstanceId:n,flowNodeId:r,state:P.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:i});l.userTasks.length>0&&(h.notification.removeSubscription(c,i),a(l.userTasks[0]))})}async function gn(s,t={},e={},n=!0){let r=typeof n=="boolean"?n==!0?await w():void 0:n;await h.userTasks.finishUserTask(s,e,r);let i={state:P.FlowNodeInstances.FlowNodeInstanceState.suspended,...t},a=await h.userTasks.query(i,{identity:r});return Qt(a.userTasks[0])}async function ps(s,t={identity:!0}){switch(t?.identity){case!0:t.identity=await w();break;case!1:t.identity=void 0;break;case void 0:t.identity=await w();break}let e=await h.userTasks.query(s,t);return b(e)}async function En(s={identity:!0}){switch(s?.identity){case!0:s.identity=await w();break;case!1:s.identity=void 0;break;case void 0:s.identity=await w();break}let t=await h.userTasks.query({state:P.FlowNodeInstances.FlowNodeInstanceState.suspended},s);return b(t)}async function In(s,t={identity:!0}){switch(t?.identity){case!0:t.identity=await w();break;case!1:t.identity=void 0;break;case void 0:t.identity=await w();break}let e=await h.userTasks.query({processInstanceId:s,state:P.FlowNodeInstances.FlowNodeInstanceState.suspended},t);return b(e)}async function Tn(s,t={identity:!0}){switch(t?.identity){case!0:t.identity=await w();break;case!1:t.identity=void 0;break;case void 0:t.identity=await w();break}let e=await h.userTasks.query({flowNodeId:s,state:P.FlowNodeInstances.FlowNodeInstanceState.suspended},t);return b(e)}async function ms(s,t={identity:!0}){switch(t?.identity){case!0:t.identity=await w();break;case!1:t.identity=void 0;break;case void 0:t.identity=await w();break}let e=await h.userTasks.query({flowNodeInstanceId:s,state:P.FlowNodeInstances.FlowNodeInstanceState.suspended},{...t,limit:1});return e.userTasks.length===0?null:Qt(e.userTasks[0])}async function Pn(s,t={identity:!0}){switch(t?.identity){case!0:t.identity=await w();break;case!1:t.identity=void 0;break;case void 0:t.identity=await w();break}let e=await h.userTasks.query({correlationId:s,state:P.FlowNodeInstances.FlowNodeInstanceState.suspended},t);return b(e)}async function kn(s,t){let e=s||await w(),n=await h.userTasks.query({state:P.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:e,...t}),r=n.userTasks.filter(i=>i.actualOwnerId===e.userId);return n.userTasks=r,b(n)}async function Rn(s,t,e){await h.userTasks.reserveUserTaskInstance(s,t,e||s.userId)}async function xn(s,t){await h.userTasks.cancelUserTaskInstanceReservation(s,t)}async function bn(s,t){let e=s||await w(),n=await h.userTasks.query({state:P.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:e,...t}),r=n.userTasks.filter(i=>i.assignedUserIds?.includes(e.userId));return n.userTasks=r,b(n)}import{PHASE_DEVELOPMENT_SERVER as ys,PHASE_PRODUCTION_BUILD as ws,PHASE_PRODUCTION_SERVER as _s}from"next/dist/shared/lib/constants";var Zt=!1,ft=!1;function Dn(s={}){let{applicationSdk:t,...e}=s;return async(n,r)=>{ft=ft||n===ws;let i=n===ys||n===_s;return t?.useExternalTasks&&i&&!Zt&&!ft&&(Zt=!0,await Ut(t?.customExternalTasksDirPath)),{...e,experimental:{...e.experimental,serverComponentsExternalPackages:[...e.experimental?.serverComponentsExternalPackages||[],"esbuild"]}}}}import{redirect as gs}from"next/navigation";function Ln(s){gs(s)}async function Wn(...s){return await h.processModels.startProcessInstance(...s)}async function Jt(...s){await h.manualTasks.finishManualTask(...s)}async function te(...s){await h.userTasks.finishUserTask(...s)}async function ee(...s){await h.untypedTasks.finishTask(...s)}import{DataModels as Es}from"@5minds/processcube_engine_client";async function Is(){try{return w()}catch{return}}var Vn=async(s,t)=>{let e=await Is();t==="bpmn:UserTask"?await te(s,{},e):t==="bpmn:ManualTask"?await Jt(s,e):t==="bpmn:Task"?await ee(s,e):console.error(`[@5minds/processcube_app_sdk:handlePlay] Unsupported flow node type: ${t}`)},Qn=async s=>{await Vt(s)},Zn=async(s,t,e)=>{await Xt(s,t,e)},Jn=async s=>$t(s),tr=async s=>qt(s,{sortSettings:{sortBy:Es.FlowNodeInstances.FlowNodeInstanceSortableColumns.createdAt,sortDir:"DESC"}}),er=async s=>Gt(s);export{xn as cancelReservedUserTask,Jt as finishManualTask,Vn as finishTask,ee as finishUntypedTask,te as finishUserTask,gn as finishUserTaskAndGetNext,dn as getActiveProcessInstances,bn as getAssignedUserTasksByIdentity,Js as getEngineClient,tr as getFlowNodeInstances,qt as getFlowNodeInstancesByProcessInstanceId,Gt as getFlowNodeInstancesTriggeredByFlowNodeInstanceIds,w as getIdentity,Jn as getProcessInstance,$t as getProcessInstanceById,kn as getReservedUserTasksByIdentity,er as getTriggeredFlowNodeInstances,ps as getUserTasks,ms as getWaitingUserTaskByFlowNodeInstanceId,En as getWaitingUserTasks,Pn as getWaitingUserTasksByCorrelationId,Tn as getWaitingUserTasksByFlowNodeId,In as getWaitingUserTasksByProcessInstanceId,Ln as navigateToUrl,Rn as reserveUserTask,Zn as retryProcess,Xt as retryProcessInstance,Wn as startProcess,Qn as terminateProcess,Vt as terminateProcessInstance,ln as waitForProcessEnd,_n as waitForUserTask,Dn as withApplicationSdk};
2
2
  /*! Bundled license information:
3
3
 
4
4
  chokidar/esm/index.js:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@5minds/processcube_app_sdk",
3
- "version": "8.2.2",
3
+ "version": "8.2.3-alpha.1",
4
4
  "description": "The SDK for ProcessCube Apps",
5
5
  "type": "module",
6
6
  "main": "build/common/index.cjs",