@5minds/processcube_app_sdk 8.5.0 → 8.6.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 v=Object.defineProperty;var Ce=Object.getOwnPropertyDescriptor;var Pe=Object.getOwnPropertyNames;var Re=Object.prototype.hasOwnProperty;var xe=(e,t)=>{for(var s in t)v(e,s,{get:t[s],enumerable:!0})},Ne=(e,t,s,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Pe(t))!Re.call(e,o)&&o!==s&&v(e,o,{get:()=>t[o],enumerable:!(n=Ce(t,o))||n.enumerable});return e};var Ue=e=>Ne(v({},"__esModule",{value:!0}),e);var mt={};xe(mt,{AuthorityClient:()=>M,cancelReservedUserTask:()=>rt,finishManualTask:()=>J,finishTask:()=>ut,finishUntypedTask:()=>Z,finishUserTask:()=>Q,finishUserTaskAndGetNext:()=>Qe,getActiveProcessInstances:()=>Ye,getAssignedUserTasksByIdentity:()=>ot,getEngineClient:()=>je,getFlowNodeInstances:()=>yt,getFlowNodeInstancesByProcessInstanceId:()=>H,getFlowNodeInstancesTriggeredByFlowNodeInstanceIds:()=>G,getIdentity:()=>d,getProcessInstance:()=>ft,getProcessInstanceById:()=>X,getReservedUserTasksByIdentity:()=>st,getServerAccessToken:()=>U,getServerIdentity:()=>Fe,getTriggeredFlowNodeInstances:()=>It,getUserTasks:()=>we,getWaitingUserTaskByFlowNodeInstanceId:()=>Ee,getWaitingUserTasks:()=>Ze,getWaitingUserTasksByCorrelationId:()=>tt,getWaitingUserTasksByFlowNodeId:()=>et,getWaitingUserTasksByProcessInstanceId:()=>ze,navigateToUrl:()=>at,reserveUserTask:()=>nt,retryProcess:()=>pt,retryProcessInstance:()=>j,startProcess:()=>ct,terminateProcess:()=>lt,terminateProcessInstance:()=>Y,waitForProcessEnd:()=>Ve,waitForUserTask:()=>Je,withApplicationSdk:()=>it});module.exports=Ue(mt);var ts=require("only-server"),ss=require("../common/index.cjs");var se=require("@5minds/processcube_engine_sdk");var z=require("jwt-decode"),ee=require("@5minds/processcube_engine_sdk"),F=new ee.Logger("processcube_app_sdk:server_identity"),be=.85,Ae="upe_admin engine_read engine_write",P=null;function Oe(e){let t=e?.authorityUrl??process.env.PROCESSCUBE_AUTHORITY_URL,s=e?.clientId??process.env.PROCESSCUBE_SERVER_CLIENT_ID,n=e?.clientSecret??process.env.PROCESSCUBE_SERVER_CLIENT_SECRET,o=e?.scopes??process.env.PROCESSCUBE_SERVER_SCOPES??Ae;if(!t)throw new Error("PROCESSCUBE_AUTHORITY_URL is not configured. Set the environment variable or pass authorityUrl.");if(!s)throw new Error("PROCESSCUBE_SERVER_CLIENT_ID is not configured. Set the environment variable or pass clientId.");if(!n)throw new Error("PROCESSCUBE_SERVER_CLIENT_SECRET is not configured. Set the environment variable or pass clientSecret.");return{authorityUrl:t,clientId:s,clientSecret:n,scopes:o}}function ve(){return P?Date.now()<P.expiresAt:!1}async function U(e){if(!e?.skipCache&&ve())return P.accessToken;let{authorityUrl:t,clientId:s,clientSecret:n,scopes:o}=Oe(e);F.info("Fetching new server access token");let i=await fetch(`${t}/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},redirect:"follow",body:new URLSearchParams({grant_type:"client_credentials",client_id:s,client_secret:n,scope:o}).toString(),cache:"no-store"});if(!i.ok){let u=await i.text().catch(()=>""),m=`Failed to fetch server access token: ${i.status} ${i.statusText}${u?` \u2014 ${u}`:""}`;throw F.error(m),new Error(m)}let a=await i.json();if(!a.access_token)throw new Error("Authority response did not contain an access_token");let c=a.expires_in;return c&&c>0?P={accessToken:a.access_token,expiresAt:Date.now()+c*be*1e3}:P=null,F.info("Server access token fetched successfully"),a.access_token}async function Fe(e){let t=await U(e),s=(0,z.jwtDecode)(t);if(!s.sub)throw new Error('Server access token does not contain a "sub" claim');return{token:t,userId:s.sub}}var te=new se.Logger("processcube_app_sdk:authority_client"),M=class{authorityUrl;tokenOptions;constructor(t){let s=t?.authorityUrl??process.env.PROCESSCUBE_AUTHORITY_URL;if(!s)throw new Error("PROCESSCUBE_AUTHORITY_URL is not configured. Set the environment variable or pass authorityUrl.");this.authorityUrl=s.replace(/\/+$/,""),this.tokenOptions=t??{}}async request(t,s,n){let o=await U(this.tokenOptions),i=`${this.authorityUrl}${s}`;te.info(`Authority request: ${t} ${s}`);let a={Cookie:`access_token=${o}`,"Content-Type":"application/json"},c=await fetch(i,{method:t,headers:a,redirect:"follow",body:n!==void 0?JSON.stringify(n):void 0}),u;try{u=await c.json()}catch{u=void 0}return c.ok||te.error(`Authority request failed: ${t} ${s} \u2192 ${c.status} ${c.statusText}`),{ok:c.ok,status:c.status,data:u}}userAdminPath(t,s){return`/acr/username_password/admin/user/${encodeURIComponent(t)}/${s}`}async updateClaim(t,s,n){return this.request("PATCH",this.userAdminPath(t,"update/claim"),{claimName:s,claimValue:n})}async addScope(t,s){return this.request("PATCH",this.userAdminPath(t,"add/scope"),{scopeName:s})}async addGroup(t,s){return this.request("PATCH",this.userAdminPath(t,"add/group"),{groupName:s})}async deleteUser(t,s){return this.request("DELETE",this.userAdminPath(t,"delete"),{fullDelete:s?.fullDelete??!1})}};var oe=require("chokidar"),ie=require("esbuild"),ae=require("jwt-decode"),ce=require("node:child_process"),R=require("node:fs"),l=require("node:path"),de=require("node:url"),A=require("openid-client"),ue=require("@5minds/processcube_engine_sdk");var ne=require("@5minds/processcube_engine_client"),B=process.env.PROCESSCUBE_ENGINE_URL??"http://localhost:10560",r=new ne.EngineClient(B);var Ge={},Me={token:"ZHVtbXlfdG9rZW4=",userId:"dummy_token"},Be=.85,b=["external_task.ts","external_task.js"],x=process.env.PROCESSCUBE_AUTHORITY_URL!==void 0,f=new ue.Logger("processcube_app_sdk:external_task_adapter"),w={},L={},E,W=!1,le=6,De=3e5,Le=3e4,D=10,We=3e4,re=10,$e=6e4;async function pe(e){if(e&&!(0,R.existsSync)(e))throw new Error(`Invalid customExternalTasksDirPath. The given path '${e}' does not exist`);A.custom.setHttpOptionsDefaults({timeout:1e5});let t=await Ie();E=q(t),await me(t);let s=Xe(e);(0,oe.watch)(s).on("add",async n=>{if(b.includes((0,l.basename)(n)))return $(n,s)}).on("change",async n=>{if(b.includes((0,l.basename)(n)))return qe(n,s)}).on("unlink",async n=>{b.includes((0,l.basename)(n))&&fe(n)}).on("error",n=>f.error(`Watcher error: ${n}`))}async function $(e,t){let s=(0,l.dirname)(e);if((await R.promises.readdir(s)).filter(y=>b.includes(y)).length>1){f.error(`Multiple external task files found in directory ${s}. Stopping all external task workers for this directory.`),w[s]&&fe(e);return}let i=await Te(e),a=(0,l.relative)(t,s),c=ke(a),u=typeof __dirname<"u"?__dirname:(0,l.dirname)((0,de.fileURLToPath)(Ge.url)),m=(0,l.join)(u,"lib/ExternalTaskWorkerProcess.cjs"),p=(0,ce.fork)(m,{stdio:["pipe","inherit","inherit","ipc"],env:{...process.env,PROCESSCUBE_ENGINE_URL:B}});w[s]=p,p.once("disconnect",()=>{delete w[s]}),p.on("error",y=>{f.error(`External Task Worker process error for ${c}`,{error:y,topic:c,workerDirectory:s})}),p.on("exit",(y,O)=>{if(f.info(`External Task Worker process exited for ${c}`,{code:y,signal:O,topic:c,workerDirectory:s}),delete w[s],y===3||y===4)if(He(s)){let _=L[s]?.count??1,C=Math.min(1e3*Math.pow(2,_-1),Le);f.info(`Scheduling restart for ${c} in ${C}ms (attempt ${_}/${le})`,{delay:C,restartCount:_,exitCode:y,topic:c,workerDirectory:s}),setTimeout(async()=>{try{if(x&&!W){f.info("Token refresh cycle is not active, restarting it before worker restart");let g=await Ie();E=q(g),await me(g)}await $(e,t)}catch(g){f.error(`Failed to restart External Task Worker process for ${c}`,{error:g,topic:c,workerDirectory:s})}},C)}else f.error(`External Task Worker process for ${c} reached maximum restart attempts`,{exitCode:y,topic:c,workerDirectory:s})}),p.send({action:"create",payload:{topic:c,identity:E,moduleString:i,workerPath:e}})}async function qe(e,t){let s=(0,l.dirname)(e),n=w[s];if(!n)return $(e,t);let o=await Te(e),i=(0,l.relative)(t,s),a=ke(i);n.send({action:"restart",payload:{topic:a,identity:E,moduleString:o,workerPath:e}})}function fe(e){let t=(0,l.dirname)(e),s=w[t];s&&s.kill()}async function ye(){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 f.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 A.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<=D;e++)try{return await ye()}catch(t){let s=Math.min(1e3*Math.pow(2,e-1),We);if(f.error(`Failed to fetch initial token set (attempt ${e}/${D}), retrying in ${s}ms`,{error:t,attempt:e,delay:s}),e===D)throw t;await new Promise(n=>setTimeout(n,s))}return null}function q(e){if(!x||e===null)return Me;let t=e.access_token,s=(0,ae.jwtDecode)(t);return{token:e.access_token,userId:s.sub}}async function me(e){if(!x||e===null||W)return;W=!0;let t=0,n=await Ke(e)*Be*1e3,o=async()=>{try{let i=await ye();E=q(i);for(let[a,c]of Object.entries(w))try{c.send({action:"updateIdentity",payload:{identity:E}})}catch(u){f.warn(`Failed to send identity update to worker process ${a}`,{sendError:u})}t=0,setTimeout(o,n)}catch(i){t++;let a=Math.min(1e3*Math.pow(2,t-1),$e);t<=re?f.error(`Could not refresh identity (attempt ${t}/${re}), retrying in ${a}ms`,{error:i,attempt:t,delay:a}):f.error(`Could not refresh identity (attempt ${t}), continuing to retry every ${a}ms`,{error:i,attempt:t,delay:a}),setTimeout(o,a)}};setTimeout(o,n)}async function Te(e){let t=await(0,ie.build)({entryPoints:[e],write:!1,bundle:!0,platform:"node",target:"node18",format:"cjs",external:["@opentelemetry/api"]});if(t.errors.length>0)throw f.error(`Could not transpile file at '${e}'`,{errors:t.errors}),new Error(`Could not transpile file at '${e}'`);return t.warnings.length>0&&f.warn(`Transpiled file at '${e}' with warnings`,{warnings:t.warnings}),t.outputFiles[0].text}async function Ke(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 ke(e){return e.replace(/^\.\/+|\([^)]+\)|^\/*|\/*$/g,"").replace(/[\/]{2,}/g,"/")}function Xe(e){let t,s=[e,(0,l.join)(process.cwd(),"app"),(0,l.join)(process.cwd(),"src","app")];for(let n of s)if(n&&(0,R.existsSync)(n)){t=n;break}if(!t)throw new Error("Could not find external tasks directory");return t}function He(e){let t=Date.now(),s=L[e];return!s||t-s.timestamp>De?(L[e]={count:1,timestamp:t},!0):s.count>=le?!1:(s.count++,!0)}function je(){return r}var K=require("next-auth/jwt"),ge=require("next/dist/compiled/@edge-runtime/cookies/index.js"),k=require("next/headers");async function d(){let e=await(0,K.getToken)({req:{cookies:await(0,k.cookies)(),headers:await(0,k.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,k.cookies)()).toString()}}),n=new ge.ResponseCookies(s.headers);if(n.getAll().length){let o=!1;try{for(let i of n.getAll())(await(0,k.cookies)()).set(i.name,i.value,{...i})}catch{o=!0}if(e=await(0,K.getToken)({req:{cookies:o?n:await(0,k.cookies)(),headers:await(0,k.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 h=require("@5minds/processcube_engine_client");async function N(){try{return d()}catch{return}}async function X(e){let t=await N();return(await r.processInstances.query({processInstanceId:e},{identity:t,includeXml:!0})).processInstances[0]}async function H(e,t={sortSettings:{sortBy:h.DataModels.FlowNodeInstances.FlowNodeInstanceSortableColumns.createdAt,sortDir:"ASC"}}){return(await r.flowNodeInstances.query({processInstanceId:e},{...t,identity:t.identity??await N()})).flowNodeInstances}async function G(e){let t=await N();return(await r.flowNodeInstances.query({triggeredByFlowNodeInstance:e},{identity:t})).flowNodeInstances}async function j(e,t,s){let n=await N();await r.processInstances.retryProcessInstance(e,{flowNodeInstanceId:t,newStartToken:s,identity:n})}async function Y(e){let t=await N();await r.processInstances.terminateProcessInstance(e,t)}async function Ye(e={options:{identity:!0}}){switch(e.options.identity){case!0:e.options.identity=await d();break;case!1:e.options.identity=void 0;break;case void 0:e.options.identity=await d();break}return await r.processInstances.query({...e?.query,state:h.DataModels.ProcessInstances.ProcessInstanceState.running},e?.options)}async function Ve(e={},t=!0){let{processInstanceId:s}=e,n=typeof t=="boolean"?t==!0?await d():void 0:t;return new Promise(async(o,i)=>{let a=[],c=async u=>{if(s!==void 0&&u.processInstanceId!==s)return;let p=await r.processInstances.query({processInstanceId:u.processInstanceId},{identity:n});for(let y of a)r.notification.removeSubscription(y,n);return p.totalCount===0?i(new Error(`Process with instance ID "${u.processInstanceId}" does not exist.`)):o(p.processInstances[0])};if(a.push(await r.notification.onProcessEnded(c,{identity:n})),a.push(await r.notification.onProcessError(c,{identity:n})),a.push(await r.notification.onProcessTerminated(c,{identity:n})),s){let u=await r.processInstances.query({processInstanceId:s,state:[h.DataModels.ProcessInstances.ProcessInstanceState.finished,h.DataModels.ProcessInstances.ProcessInstanceState.terminated,h.DataModels.ProcessInstances.ProcessInstanceState.error]},{identity:n});if(u.totalCount>0){for(let m of a)r.notification.removeSubscription(m,n);o(u.processInstances[0])}}})}var T=require("@5minds/processcube_engine_client"),I=require("../common/index.cjs");async function Je(e={},t=!0){let{correlationId:s,processInstanceId:n,flowNodeId:o}=e,i=typeof t=="boolean"?t==!0?await d():void 0:t;return new Promise(async(a,c)=>{let u=await r.userTasks.onUserTaskWaiting(async p=>{let y=s!==void 0&&p.correlationId!==s,O=p.flowNodeInstanceId===void 0,_=n!==void 0&&p.processInstanceId!==n,C=o!==void 0&&p.flowNodeId!==o;if(y||O||_||C)return;let g=await Ee(p.flowNodeInstanceId,{identity:i});return r.notification.removeSubscription(u,i),g===null?c(new Error(`UserTask with instance ID "${p.flowNodeInstanceId}" does not exist.`)):a(g)},{identity:i}),m=await we({correlationId:s,processInstanceId:n,flowNodeId:o,state:T.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:i});m.userTasks.length>0&&(r.notification.removeSubscription(u,i),a(m.userTasks[0]))})}async function Qe(e,t={},s={},n=!0){let o=typeof n=="boolean"?n==!0?await d():void 0:n;await r.userTasks.finishUserTask(e,s,o);let i={state:T.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended,...t},a=await r.userTasks.query(i,{identity:o});return(0,I.mapUserTask)(a.userTasks[0])}async function we(e,t={identity:!0}){switch(t?.identity){case!0:t.identity=await d();break;case!1:t.identity=void 0;break;case void 0:t.identity=await d();break}let s=await r.userTasks.query(e,t);return(0,I.mapUserTaskList)(s)}async function Ze(e={identity:!0}){switch(e?.identity){case!0:e.identity=await d();break;case!1:e.identity=void 0;break;case void 0:e.identity=await d();break}let t=await r.userTasks.query({state:T.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},e);return(0,I.mapUserTaskList)(t)}async function ze(e,t={identity:!0}){switch(t?.identity){case!0:t.identity=await d();break;case!1:t.identity=void 0;break;case void 0:t.identity=await d();break}let s=await r.userTasks.query({processInstanceId:e,state:T.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},t);return(0,I.mapUserTaskList)(s)}async function et(e,t={identity:!0}){switch(t?.identity){case!0:t.identity=await d();break;case!1:t.identity=void 0;break;case void 0:t.identity=await d();break}let s=await r.userTasks.query({flowNodeId:e,state:T.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},t);return(0,I.mapUserTaskList)(s)}async function Ee(e,t={identity:!0}){switch(t?.identity){case!0:t.identity=await d();break;case!1:t.identity=void 0;break;case void 0:t.identity=await d();break}let s=await r.userTasks.query({flowNodeInstanceId:e,state:T.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},{...t,limit:1});return s.userTasks.length===0?null:(0,I.mapUserTask)(s.userTasks[0])}async function tt(e,t={identity:!0}){switch(t?.identity){case!0:t.identity=await d();break;case!1:t.identity=void 0;break;case void 0:t.identity=await d();break}let s=await r.userTasks.query({correlationId:e,state:T.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},t);return(0,I.mapUserTaskList)(s)}async function st(e,t){let s=e||await d(),n=await r.userTasks.query({state:T.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 nt(e,t,s){await r.userTasks.reserveUserTaskInstance(e,t,s||e.userId)}async function rt(e,t){await r.userTasks.cancelUserTaskInstanceReservation(e,t)}async function ot(e,t){let s=e||await d(),n=await r.userTasks.query({state:T.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 S=require("next/dist/shared/lib/constants");var he=!1,V=!1;function it(e={}){let{applicationSdk:t,...s}=e;return async(n,o)=>{V=V||n===S.PHASE_PRODUCTION_BUILD;let i=n===S.PHASE_DEVELOPMENT_SERVER||n===S.PHASE_PRODUCTION_SERVER;return t?.useExternalTasks&&i&&!he&&!V&&(he=!0,await pe(t?.customExternalTasksDirPath)),{...s,experimental:{...s.experimental,serverComponentsExternalPackages:[...s.experimental?.serverComponentsExternalPackages||[],"esbuild"]}}}}var Se=require("next/navigation");function at(e){(0,Se.redirect)(e)}async function ct(...e){return await r.processModels.startProcessInstance(...e)}async function J(...e){await r.manualTasks.finishManualTask(...e)}async function Q(...e){await r.userTasks.finishUserTask(...e)}async function Z(...e){await r.untypedTasks.finishTask(...e)}var _e=require("@5minds/processcube_engine_client");async function dt(){try{return d()}catch{return}}var ut=async(e,t)=>{let s=await dt();t==="bpmn:UserTask"?await Q(e,{},s):t==="bpmn:ManualTask"?await J(e,s):t==="bpmn:Task"?await Z(e,s):console.error(`[@5minds/processcube_app_sdk:handlePlay] Unsupported flow node type: ${t}`)},lt=async e=>{await Y(e)},pt=async(e,t,s)=>{await j(e,t,s)},ft=async e=>X(e),yt=async e=>H(e,{sortSettings:{sortBy:_e.DataModels.FlowNodeInstances.FlowNodeInstanceSortableColumns.createdAt,sortDir:"DESC"}}),It=async e=>G(e);0&&(module.exports={AuthorityClient,cancelReservedUserTask,finishManualTask,finishTask,finishUntypedTask,finishUserTask,finishUserTaskAndGetNext,getActiveProcessInstances,getAssignedUserTasksByIdentity,getEngineClient,getFlowNodeInstances,getFlowNodeInstancesByProcessInstanceId,getFlowNodeInstancesTriggeredByFlowNodeInstanceIds,getIdentity,getProcessInstance,getProcessInstanceById,getReservedUserTasksByIdentity,getServerAccessToken,getServerIdentity,getTriggeredFlowNodeInstances,getUserTasks,getWaitingUserTaskByFlowNodeInstanceId,getWaitingUserTasks,getWaitingUserTasksByCorrelationId,getWaitingUserTasksByFlowNodeId,getWaitingUserTasksByProcessInstanceId,navigateToUrl,reserveUserTask,retryProcess,retryProcessInstance,startProcess,terminateProcess,terminateProcessInstance,waitForProcessEnd,waitForUserTask,withApplicationSdk});
1
+ var v=Object.defineProperty;var Ce=Object.getOwnPropertyDescriptor;var Pe=Object.getOwnPropertyNames;var Re=Object.prototype.hasOwnProperty;var xe=(e,t)=>{for(var s in t)v(e,s,{get:t[s],enumerable:!0})},Ne=(e,t,s,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Pe(t))!Re.call(e,o)&&o!==s&&v(e,o,{get:()=>t[o],enumerable:!(n=Ce(t,o))||n.enumerable});return e};var Ue=e=>Ne(v({},"__esModule",{value:!0}),e);var mt={};xe(mt,{AuthorityClient:()=>M,cancelReservedUserTask:()=>rt,finishManualTask:()=>J,finishTask:()=>lt,finishUntypedTask:()=>Z,finishUserTask:()=>Q,finishUserTaskAndGetNext:()=>Qe,getActiveProcessInstances:()=>Ye,getAssignedUserTasksByIdentity:()=>ot,getEngineClient:()=>je,getFlowNodeInstances:()=>yt,getFlowNodeInstancesByProcessInstanceId:()=>H,getFlowNodeInstancesTriggeredByFlowNodeInstanceIds:()=>G,getIdentity:()=>d,getProcessInstance:()=>ft,getProcessInstanceById:()=>X,getReservedUserTasksByIdentity:()=>st,getServerAccessToken:()=>U,getServerIdentity:()=>Fe,getTriggeredFlowNodeInstances:()=>It,getUserTasks:()=>we,getWaitingUserTaskByFlowNodeInstanceId:()=>Ee,getWaitingUserTasks:()=>Ze,getWaitingUserTasksByCorrelationId:()=>tt,getWaitingUserTasksByFlowNodeId:()=>et,getWaitingUserTasksByProcessInstanceId:()=>ze,navigateToUrl:()=>at,reserveUserTask:()=>nt,retryProcess:()=>pt,retryProcessInstance:()=>j,startProcess:()=>ct,terminateProcess:()=>ut,terminateProcessInstance:()=>Y,waitForProcessEnd:()=>Ve,waitForUserTask:()=>Je,withApplicationSdk:()=>it});module.exports=Ue(mt);var ts=require("only-server"),ss=require("../common/index.cjs");var se=require("@5minds/processcube_engine_sdk");var z=require("jwt-decode"),ee=require("@5minds/processcube_engine_sdk"),F=new ee.Logger("processcube_app_sdk:server_identity"),be=.85,Ae="upe_admin engine_read engine_write",P=null;function Oe(e){let t=e?.authorityUrl??process.env.PROCESSCUBE_AUTHORITY_URL,s=e?.clientId??process.env.PROCESSCUBE_SERVER_CLIENT_ID,n=e?.clientSecret??process.env.PROCESSCUBE_SERVER_CLIENT_SECRET,o=e?.scopes??process.env.PROCESSCUBE_SERVER_SCOPES??Ae;if(!t)throw new Error("PROCESSCUBE_AUTHORITY_URL is not configured. Set the environment variable or pass authorityUrl.");if(!s)throw new Error("PROCESSCUBE_SERVER_CLIENT_ID is not configured. Set the environment variable or pass clientId.");if(!n)throw new Error("PROCESSCUBE_SERVER_CLIENT_SECRET is not configured. Set the environment variable or pass clientSecret.");return{authorityUrl:t,clientId:s,clientSecret:n,scopes:o}}function ve(){return P?Date.now()<P.expiresAt:!1}async function U(e){if(!e?.skipCache&&ve())return P.accessToken;let{authorityUrl:t,clientId:s,clientSecret:n,scopes:o}=Oe(e);F.info("Fetching new server access token");let i=await fetch(`${t}/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},redirect:"follow",body:new URLSearchParams({grant_type:"client_credentials",client_id:s,client_secret:n,scope:o}).toString(),cache:"no-store"});if(!i.ok){let l=await i.text().catch(()=>""),m=`Failed to fetch server access token: ${i.status} ${i.statusText}${l?` \u2014 ${l}`:""}`;throw F.error(m),new Error(m)}let a=await i.json();if(!a.access_token)throw new Error("Authority response did not contain an access_token");let c=a.expires_in;return c&&c>0?P={accessToken:a.access_token,expiresAt:Date.now()+c*be*1e3}:P=null,F.info("Server access token fetched successfully"),a.access_token}async function Fe(e){let t=await U(e),s=(0,z.jwtDecode)(t);if(!s.sub)throw new Error('Server access token does not contain a "sub" claim');return{token:t,userId:s.sub}}var te=new se.Logger("processcube_app_sdk:authority_client"),M=class{authorityUrl;tokenOptions;constructor(t){let s=t?.authorityUrl??process.env.PROCESSCUBE_AUTHORITY_URL;if(!s)throw new Error("PROCESSCUBE_AUTHORITY_URL is not configured. Set the environment variable or pass authorityUrl.");this.authorityUrl=s.replace(/\/+$/,""),this.tokenOptions=t??{}}async request(t,s,n){let o=await U(this.tokenOptions),i=`${this.authorityUrl}${s}`;te.info(`Authority request: ${t} ${s}`);let a={Cookie:`access_token=${o}`,"Content-Type":"application/json"},c=await fetch(i,{method:t,headers:a,redirect:"follow",body:n!==void 0?JSON.stringify(n):void 0}),l;try{l=await c.json()}catch{l=void 0}return c.ok||te.error(`Authority request failed: ${t} ${s} \u2192 ${c.status} ${c.statusText}`),{ok:c.ok,status:c.status,data:l}}userAdminPath(t,s){return`/acr/username_password/admin/user/${encodeURIComponent(t)}/${s}`}async updateClaim(t,s,n){return this.request("PATCH",this.userAdminPath(t,"update/claim"),{claimName:s,claimValue:n})}async addScope(t,s){return this.request("PATCH",this.userAdminPath(t,"add/scope"),{scopeName:s})}async addGroup(t,s){return this.request("PATCH",this.userAdminPath(t,"add/group"),{groupName:s})}async deleteUser(t,s){return this.request("DELETE",this.userAdminPath(t,"delete"),{fullDelete:s?.fullDelete??!1})}};var oe=require("chokidar"),ie=require("esbuild"),ae=require("jwt-decode"),ce=require("node:child_process"),R=require("node:fs"),u=require("node:path"),de=require("node:url"),A=require("openid-client"),le=require("@5minds/processcube_engine_sdk");var ne=require("@5minds/processcube_engine_client"),B=process.env.PROCESSCUBE_ENGINE_URL??"http://localhost:10560",r=new ne.EngineClient(B);var Ge={},Me={token:"ZHVtbXlfdG9rZW4=",userId:"dummy_token"},Be=.85,b=["external_task.ts","external_task.js"],x=process.env.PROCESSCUBE_AUTHORITY_URL!==void 0,f=new le.Logger("processcube_app_sdk:external_task_adapter"),w={},L={},E,W=!1,ue=6,De=3e5,Le=3e4,D=10,We=3e4,re=10,$e=6e4;async function pe(e){if(e&&!(0,R.existsSync)(e))throw new Error(`Invalid customExternalTasksDirPath. The given path '${e}' does not exist`);A.custom.setHttpOptionsDefaults({timeout:1e5});let t=await Ie();E=q(t),await me(t);let s=Xe(e);(0,oe.watch)(s).on("add",async n=>{if(b.includes((0,u.basename)(n)))return $(n,s)}).on("change",async n=>{if(b.includes((0,u.basename)(n)))return qe(n,s)}).on("unlink",async n=>{b.includes((0,u.basename)(n))&&fe(n)}).on("error",n=>f.error(`Watcher error: ${n}`))}async function $(e,t){let s=(0,u.dirname)(e);if((await R.promises.readdir(s)).filter(y=>b.includes(y)).length>1){f.error(`Multiple external task files found in directory ${s}. Stopping all external task workers for this directory.`),w[s]&&fe(e);return}let i=await Te(e),a=(0,u.relative)(t,s),c=ke(a),l=typeof __dirname<"u"?__dirname:(0,u.dirname)((0,de.fileURLToPath)(Ge.url)),m=(0,u.join)(l,"lib/ExternalTaskWorkerProcess.cjs"),p=(0,ce.fork)(m,{stdio:["pipe","inherit","inherit","ipc"],env:{...process.env,PROCESSCUBE_ENGINE_URL:B}});w[s]=p,p.once("disconnect",()=>{delete w[s]}),p.on("error",y=>{f.error(`External Task Worker process error for ${c}`,{error:y,topic:c,workerDirectory:s})}),p.on("exit",(y,O)=>{if(f.info(`External Task Worker process exited for ${c}`,{code:y,signal:O,topic:c,workerDirectory:s}),delete w[s],y===3||y===4)if(He(s)){let _=L[s]?.count??1,C=Math.min(1e3*Math.pow(2,_-1),Le);f.info(`Scheduling restart for ${c} in ${C}ms (attempt ${_}/${ue})`,{delay:C,restartCount:_,exitCode:y,topic:c,workerDirectory:s}),setTimeout(async()=>{try{if(x&&!W){f.info("Token refresh cycle is not active, restarting it before worker restart");let g=await Ie();E=q(g),await me(g)}await $(e,t)}catch(g){f.error(`Failed to restart External Task Worker process for ${c}`,{error:g,topic:c,workerDirectory:s})}},C)}else f.error(`External Task Worker process for ${c} reached maximum restart attempts`,{exitCode:y,topic:c,workerDirectory:s})}),p.send({action:"create",payload:{topic:c,identity:E,moduleString:i,workerPath:e}})}async function qe(e,t){let s=(0,u.dirname)(e),n=w[s];if(!n)return $(e,t);let o=await Te(e),i=(0,u.relative)(t,s),a=ke(i);n.send({action:"restart",payload:{topic:a,identity:E,moduleString:o,workerPath:e}})}function fe(e){let t=(0,u.dirname)(e),s=w[t];s&&s.kill()}async function ye(){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 f.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 A.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<=D;e++)try{return await ye()}catch(t){let s=Math.min(1e3*Math.pow(2,e-1),We);if(f.error(`Failed to fetch initial token set (attempt ${e}/${D}), retrying in ${s}ms`,{error:t,attempt:e,delay:s}),e===D)throw t;await new Promise(n=>setTimeout(n,s))}return null}function q(e){if(!x||e===null)return Me;let t=e.access_token,s=(0,ae.jwtDecode)(t);return{token:e.access_token,userId:s.sub}}async function me(e){if(!x||e===null||W)return;W=!0;let t=0,n=await Ke(e)*Be*1e3,o=async()=>{try{let i=await ye();E=q(i);for(let[a,c]of Object.entries(w))try{c.send({action:"updateIdentity",payload:{identity:E}})}catch(l){f.warn(`Failed to send identity update to worker process ${a}`,{sendError:l})}t=0,setTimeout(o,n)}catch(i){t++;let a=Math.min(1e3*Math.pow(2,t-1),$e);t<=re?f.error(`Could not refresh identity (attempt ${t}/${re}), retrying in ${a}ms`,{error:i,attempt:t,delay:a}):f.error(`Could not refresh identity (attempt ${t}), continuing to retry every ${a}ms`,{error:i,attempt:t,delay:a}),setTimeout(o,a)}};setTimeout(o,n)}async function Te(e){let t=await(0,ie.build)({entryPoints:[e],write:!1,bundle:!0,platform:"node",target:"node18",format:"cjs",external:["@opentelemetry/api"]});if(t.errors.length>0)throw f.error(`Could not transpile file at '${e}'`,{errors:t.errors}),new Error(`Could not transpile file at '${e}'`);return t.warnings.length>0&&f.warn(`Transpiled file at '${e}' with warnings`,{warnings:t.warnings}),t.outputFiles[0].text}async function Ke(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 ke(e){return e.replace(/^\.\/+|\([^)]+\)|^\/*|\/*$/g,"").replace(/[\/]{2,}/g,"/")}function Xe(e){let t,s=[e,(0,u.join)(process.cwd(),"app"),(0,u.join)(process.cwd(),"src","app")];for(let n of s)if(n&&(0,R.existsSync)(n)){t=n;break}if(!t)throw new Error("Could not find external tasks directory");return t}function He(e){let t=Date.now(),s=L[e];return!s||t-s.timestamp>De?(L[e]={count:1,timestamp:t},!0):s.count>=ue?!1:(s.count++,!0)}function je(){return r}var K=require("next-auth/jwt"),ge=require("next/dist/compiled/@edge-runtime/cookies/index.js"),k=require("next/headers");async function d(){let e=await(0,K.getToken)({req:{cookies:await(0,k.cookies)(),headers:await(0,k.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,k.cookies)()).toString()}}),n=new ge.ResponseCookies(s.headers);if(n.getAll().length){let o=!1;try{for(let i of n.getAll())(await(0,k.cookies)()).set(i.name,i.value,{...i})}catch{o=!0}if(e=await(0,K.getToken)({req:{cookies:o?n:await(0,k.cookies)(),headers:await(0,k.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 h=require("@5minds/processcube_engine_client");async function N(){try{return d()}catch{return}}async function X(e){let t=await N();return(await r.processInstances.query({processInstanceId:e},{identity:t,includeXml:!0})).processInstances[0]}async function H(e,t={sortSettings:{sortBy:h.DataModels.FlowNodeInstances.FlowNodeInstanceSortableColumns.createdAt,sortDir:"ASC"}}){return(await r.flowNodeInstances.query({processInstanceId:e},{...t,identity:t.identity??await N()})).flowNodeInstances}async function G(e){let t=await N();return(await r.flowNodeInstances.query({triggeredByFlowNodeInstance:e},{identity:t})).flowNodeInstances}async function j(e,t,s){let n=await N();await r.processInstances.retryProcessInstance(e,{flowNodeInstanceId:t,newStartToken:s,identity:n})}async function Y(e){let t=await N();await r.processInstances.terminateProcessInstance(e,t)}async function Ye(e={options:{identity:!0}}){switch(e.options.identity){case!0:e.options.identity=await d();break;case!1:delete e.options.identity;break;case void 0:e.options.identity=await d();break}return await r.processInstances.query({...e?.query,state:h.DataModels.ProcessInstances.ProcessInstanceState.running},e?.options)}async function Ve(e={},t=!0){let{processInstanceId:s}=e,n=typeof t=="boolean"?t==!0?await d():void 0:t;return new Promise(async(o,i)=>{let a=[],c=async l=>{if(s!==void 0&&l.processInstanceId!==s)return;let p=await r.processInstances.query({processInstanceId:l.processInstanceId},{identity:n});for(let y of a)r.notification.removeSubscription(y,n);return p.totalCount===0?i(new Error(`Process with instance ID "${l.processInstanceId}" does not exist.`)):o(p.processInstances[0])};if(a.push(await r.notification.onProcessEnded(c,{identity:n})),a.push(await r.notification.onProcessError(c,{identity:n})),a.push(await r.notification.onProcessTerminated(c,{identity:n})),s){let l=await r.processInstances.query({processInstanceId:s,state:[h.DataModels.ProcessInstances.ProcessInstanceState.finished,h.DataModels.ProcessInstances.ProcessInstanceState.terminated,h.DataModels.ProcessInstances.ProcessInstanceState.error]},{identity:n});if(l.totalCount>0){for(let m of a)r.notification.removeSubscription(m,n);o(l.processInstances[0])}}})}var T=require("@5minds/processcube_engine_client"),I=require("../common/index.cjs");async function Je(e={},t=!0){let{correlationId:s,processInstanceId:n,flowNodeId:o}=e,i=typeof t=="boolean"?t==!0?await d():void 0:t;return new Promise(async(a,c)=>{let l=await r.userTasks.onUserTaskWaiting(async p=>{let y=s!==void 0&&p.correlationId!==s,O=p.flowNodeInstanceId===void 0,_=n!==void 0&&p.processInstanceId!==n,C=o!==void 0&&p.flowNodeId!==o;if(y||O||_||C)return;let g=await Ee(p.flowNodeInstanceId,{identity:i});return r.notification.removeSubscription(l,i),g===null?c(new Error(`UserTask with instance ID "${p.flowNodeInstanceId}" does not exist.`)):a(g)},{identity:i}),m=await we({correlationId:s,processInstanceId:n,flowNodeId:o,state:T.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:i});m.userTasks.length>0&&(r.notification.removeSubscription(l,i),a(m.userTasks[0]))})}async function Qe(e,t={},s={},n=!0){let o=typeof n=="boolean"?n==!0?await d():void 0:n;await r.userTasks.finishUserTask(e,s,o);let i={state:T.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended,...t},a=await r.userTasks.query(i,{identity:o});return(0,I.mapUserTask)(a.userTasks[0])}async function we(e,t={identity:!0}){switch(t?.identity){case!0:t.identity=await d();break;case!1:delete t.identity;break;case void 0:t.identity=await d();break}let s=await r.userTasks.query(e,t);return(0,I.mapUserTaskList)(s)}async function Ze(e={identity:!0}){switch(e?.identity){case!0:e.identity=await d();break;case!1:delete e.identity;break;case void 0:e.identity=await d();break}let t=await r.userTasks.query({state:T.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},e);return(0,I.mapUserTaskList)(t)}async function ze(e,t={identity:!0}){switch(t?.identity){case!0:t.identity=await d();break;case!1:delete t.identity;break;case void 0:t.identity=await d();break}let s=await r.userTasks.query({processInstanceId:e,state:T.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},t);return(0,I.mapUserTaskList)(s)}async function et(e,t={identity:!0}){switch(t?.identity){case!0:t.identity=await d();break;case!1:delete t.identity;break;case void 0:t.identity=await d();break}let s=await r.userTasks.query({flowNodeId:e,state:T.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},t);return(0,I.mapUserTaskList)(s)}async function Ee(e,t={identity:!0}){switch(t?.identity){case!0:t.identity=await d();break;case!1:delete t.identity;break;case void 0:t.identity=await d();break}let s=await r.userTasks.query({flowNodeInstanceId:e,state:T.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},{...t,limit:1});return s.userTasks.length===0?null:(0,I.mapUserTask)(s.userTasks[0])}async function tt(e,t={identity:!0}){switch(t?.identity){case!0:t.identity=await d();break;case!1:delete t.identity;break;case void 0:t.identity=await d();break}let s=await r.userTasks.query({correlationId:e,state:T.DataModels.FlowNodeInstances.FlowNodeInstanceState.suspended},t);return(0,I.mapUserTaskList)(s)}async function st(e,t){let s=e||await d(),n=await r.userTasks.query({state:T.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 nt(e,t,s){await r.userTasks.reserveUserTaskInstance(e,t,s||e.userId)}async function rt(e,t){await r.userTasks.cancelUserTaskInstanceReservation(e,t)}async function ot(e,t){let s=e||await d(),n=await r.userTasks.query({state:T.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 S=require("next/dist/shared/lib/constants");var he=!1,V=!1;function it(e={}){let{applicationSdk:t,...s}=e;return async(n,o)=>{V=V||n===S.PHASE_PRODUCTION_BUILD;let i=n===S.PHASE_DEVELOPMENT_SERVER||n===S.PHASE_PRODUCTION_SERVER;return t?.useExternalTasks&&i&&!he&&!V&&(he=!0,await pe(t?.customExternalTasksDirPath)),{...s,serverExternalPackages:[...s.serverExternalPackages||[],"esbuild"]}}}var Se=require("next/navigation");function at(e){(0,Se.redirect)(e)}async function ct(...e){return await r.processModels.startProcessInstance(...e)}async function J(...e){await r.manualTasks.finishManualTask(...e)}async function Q(...e){await r.userTasks.finishUserTask(...e)}async function Z(...e){await r.untypedTasks.finishTask(...e)}var _e=require("@5minds/processcube_engine_client");async function dt(){try{return d()}catch{return}}var lt=async(e,t)=>{let s=await dt();t==="bpmn:UserTask"?await Q(e,{},s):t==="bpmn:ManualTask"?await J(e,s):t==="bpmn:Task"?await Z(e,s):console.error(`[@5minds/processcube_app_sdk:handlePlay] Unsupported flow node type: ${t}`)},ut=async e=>{await Y(e)},pt=async(e,t,s)=>{await j(e,t,s)},ft=async e=>X(e),yt=async e=>H(e,{sortSettings:{sortBy:_e.DataModels.FlowNodeInstances.FlowNodeInstanceSortableColumns.createdAt,sortDir:"DESC"}}),It=async e=>G(e);0&&(module.exports={AuthorityClient,cancelReservedUserTask,finishManualTask,finishTask,finishUntypedTask,finishUserTask,finishUserTaskAndGetNext,getActiveProcessInstances,getAssignedUserTasksByIdentity,getEngineClient,getFlowNodeInstances,getFlowNodeInstancesByProcessInstanceId,getFlowNodeInstancesTriggeredByFlowNodeInstanceIds,getIdentity,getProcessInstance,getProcessInstanceById,getReservedUserTasksByIdentity,getServerAccessToken,getServerIdentity,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{Logger as pt}from"@5minds/processcube_engine_sdk";import{jwtDecode as ct}from"jwt-decode";import{Logger as dt}from"@5minds/processcube_engine_sdk";var K=new dt("processcube_app_sdk:server_identity"),lt=.85,ft="upe_admin engine_read engine_write",N=null;function ut(s){let e=s?.authorityUrl??process.env.PROCESSCUBE_AUTHORITY_URL,t=s?.clientId??process.env.PROCESSCUBE_SERVER_CLIENT_ID,n=s?.clientSecret??process.env.PROCESSCUBE_SERVER_CLIENT_SECRET,r=s?.scopes??process.env.PROCESSCUBE_SERVER_SCOPES??ft;if(!e)throw new Error("PROCESSCUBE_AUTHORITY_URL is not configured. Set the environment variable or pass authorityUrl.");if(!t)throw new Error("PROCESSCUBE_SERVER_CLIENT_ID is not configured. Set the environment variable or pass clientId.");if(!n)throw new Error("PROCESSCUBE_SERVER_CLIENT_SECRET is not configured. Set the environment variable or pass clientSecret.");return{authorityUrl:e,clientId:t,clientSecret:n,scopes:r}}function ht(){return N?Date.now()<N.expiresAt:!1}async function q(s){if(!s?.skipCache&&ht())return N.accessToken;let{authorityUrl:e,clientId:t,clientSecret:n,scopes:r}=ut(s);K.info("Fetching new server access token");let i=await fetch(`${e}/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},redirect:"follow",body:new URLSearchParams({grant_type:"client_credentials",client_id:t,client_secret:n,scope:r}).toString(),cache:"no-store"});if(!i.ok){let c=await i.text().catch(()=>""),l=`Failed to fetch server access token: ${i.status} ${i.statusText}${c?` \u2014 ${c}`:""}`;throw K.error(l),new Error(l)}let a=await i.json();if(!a.access_token)throw new Error("Authority response did not contain an access_token");let o=a.expires_in;return o&&o>0?N={accessToken:a.access_token,expiresAt:Date.now()+o*lt*1e3}:N=null,K.info("Server access token fetched successfully"),a.access_token}async function Ms(s){let e=await q(s),t=ct(e);if(!t.sub)throw new Error('Server access token does not contain a "sub" claim');return{token:e,userId:t.sub}}var me=new pt("processcube_app_sdk:authority_client"),ye=class{authorityUrl;tokenOptions;constructor(e){let t=e?.authorityUrl??process.env.PROCESSCUBE_AUTHORITY_URL;if(!t)throw new Error("PROCESSCUBE_AUTHORITY_URL is not configured. Set the environment variable or pass authorityUrl.");this.authorityUrl=t.replace(/\/+$/,""),this.tokenOptions=e??{}}async request(e,t,n){let r=await q(this.tokenOptions),i=`${this.authorityUrl}${t}`;me.info(`Authority request: ${e} ${t}`);let a={Cookie:`access_token=${r}`,"Content-Type":"application/json"},o=await fetch(i,{method:e,headers:a,redirect:"follow",body:n!==void 0?JSON.stringify(n):void 0}),c;try{c=await o.json()}catch{c=void 0}return o.ok||me.error(`Authority request failed: ${e} ${t} \u2192 ${o.status} ${o.statusText}`),{ok:o.ok,status:o.status,data:c}}userAdminPath(e,t){return`/acr/username_password/admin/user/${encodeURIComponent(e)}/${t}`}async updateClaim(e,t,n){return this.request("PATCH",this.userAdminPath(e,"update/claim"),{claimName:t,claimValue:n})}async addScope(e,t){return this.request("PATCH",this.userAdminPath(e,"add/scope"),{scopeName:t})}async addGroup(e,t){return this.request("PATCH",this.userAdminPath(e,"add/group"),{groupName:t})}async deleteUser(e,t){return this.request("DELETE",this.userAdminPath(e,"delete"),{fullDelete:t?.fullDelete??!1})}};import{stat as Yt}from"node:fs";import{stat as zt,readdir as Kt}from"node:fs/promises";import{EventEmitter as qt}from"node:events";import*as p from"node:path";import{stat as mt,lstat as we,readdir as yt,realpath as wt}from"node:fs/promises";import{Readable as _t}from"node:stream";import{resolve as _e,relative as gt,join as Et,sep as It}from"node:path";var T={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},G={root:".",fileFilter:s=>!0,directoryFilter:s=>!0,type:T.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(G);var Te="READDIRP_RECURSIVE_ERROR",Tt=new Set(["ENOENT","EPERM","EACCES","ELOOP",Te]),ge=[T.DIR_TYPE,T.EVERYTHING_TYPE,T.FILE_DIR_TYPE,T.FILE_TYPE],Pt=new Set([T.DIR_TYPE,T.EVERYTHING_TYPE,T.FILE_DIR_TYPE]),kt=new Set([T.EVERYTHING_TYPE,T.FILE_DIR_TYPE,T.FILE_TYPE]),Rt=s=>Tt.has(s.code),St=process.platform==="win32",Ee=s=>!0,Ie=s=>{if(s===void 0)return Ee;if(typeof s=="function")return s;if(typeof s=="string"){let e=s.trim();return t=>t.basename===e}if(Array.isArray(s)){let e=s.map(t=>t.trim());return t=>e.some(n=>t.basename===n)}return Ee},V=class extends _t{constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark});let t={...G,...e},{root:n,type:r}=t;this._fileFilter=Ie(t.fileFilter),this._directoryFilter=Ie(t.directoryFilter);let i=t.lstat?we:mt;St?this._stat=a=>i(a,{bigint:!0}):this._stat=i,this._maxDepth=t.depth??G.depth,this._wantsDir=r?Pt.has(r):!1,this._wantsFile=r?kt.has(r):!1,this._wantsEverything=r===T.EVERYTHING_TYPE,this._root=_e(n),this._isDirent=!t.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(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let t=this.parent,n=t&&t.files;if(n&&n.length>0){let{path:r,depth:i}=t,a=n.splice(0,e).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),e--)):(l==="file"||this._includeAsFile(c))&&this._fileFilter(c)&&this._wantsFile&&(this.push(c),e--)}}else{let r=this.parents.pop();if(!r){this.push(null);break}if(this.parent=await r,this.destroyed)return}}}catch(t){this.destroy(t)}finally{this.reading=!1}}}async _exploreDir(e,t){let n;try{n=await yt(e,this._rdOptions)}catch(r){this._onError(r)}return{files:n,depth:t,path:e}}async _formatEntry(e,t){let n,r=this._isDirent?e.name:e;try{let i=_e(Et(t,r));n={path:gt(this._root,i),fullPath:i,basename:r},n[this._statsProp]=this._isDirent?e:await this._stat(i)}catch(i){this._onError(i);return}return n}_onError(e){Rt(e)&&!this.destroyed?this.emit("warn",e):this.destroy(e)}async _getEntryType(e){if(!e&&this._statsProp in e)return"";let t=e[this._statsProp];if(t.isFile())return"file";if(t.isDirectory())return"directory";if(t&&t.isSymbolicLink()){let n=e.fullPath;try{let r=await wt(n),i=await we(r);if(i.isFile())return"file";if(i.isDirectory()){let a=r.length;if(n.startsWith(r)&&n.substr(a,1)===It){let o=new Error(`Circular symlink detected: "${n}" points to "${r}"`);return o.code=Te,this._onError(o)}return"directory"}}catch(r){return this._onError(r),""}}}_includeAsFile(e){let t=e&&e[this._statsProp];return t&&this._wantsEverything&&!t.isDirectory()}};function Pe(s,e={}){let t=e.entryType||e.type;if(t==="both"&&(t=T.FILE_DIR_TYPE),t&&(e.type=t),s){if(typeof s!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(t&&!ge.includes(t))throw new Error(`readdirp: Invalid type passed. Use one of ${ge.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return e.root=s,new V(e)}import{watchFile as Ct,unwatchFile as ke,watch as xt}from"node:fs";import{open as bt,stat as Se,lstat as Nt,realpath as X}from"node:fs/promises";import*as y from"node:path";import{type as At}from"node:os";var vt="data",Z="end",Ce="close",B=()=>{};var H=process.platform,ee=H==="win32",Dt=H==="darwin",Ft=H==="linux",Ut=H==="freebsd",xe=At()==="OS400",_={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},P=_,Ot="watch",Lt={lstat:Nt,stat:Se},R="listeners",O="errHandlers",x="rawEmitters",Mt=[R,O,x],Wt=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"]),Bt=s=>Wt.has(y.extname(s).slice(1).toLowerCase()),Q=(s,e)=>{s instanceof Set?s.forEach(e):e(s)},A=(s,e,t)=>{let n=s[e];n instanceof Set||(s[e]=n=new Set([n])),n.add(t)},Ht=s=>e=>{let t=s[e];t instanceof Set?t.clear():delete s[e]},v=(s,e,t)=>{let n=s[e];n instanceof Set?n.delete(t):n===t&&delete s[e]},be=s=>s instanceof Set?s.size===0:!s,L=new Map;function Re(s,e,t,n,r){let i=(a,o)=>{t(s),r(a,o,{watchedPath:s}),o&&s!==o&&M(y.resolve(s,o),R,y.join(s,o))};try{return xt(s,{persistent:e.persistent},i)}catch(a){n(a);return}}var M=(s,e,t,n,r)=>{let i=L.get(s);i&&Q(i[e],a=>{a(t,n,r)})},$t=(s,e,t,n)=>{let{listener:r,errHandler:i,rawEmitter:a}=n,o=L.get(e),c;if(!t.persistent)return c=Re(s,t,r,i,a),c?c.close.bind(c):void 0;if(o)A(o,R,r),A(o,O,i),A(o,x,a);else{if(c=Re(s,t,M.bind(null,e,R),i,M.bind(null,e,x)),!c)return;c.on(P.ERROR,async l=>{let d=M.bind(null,e,O);if(o&&(o.watcherUnusable=!0),ee&&l.code==="EPERM")try{await(await bt(s,"r")).close(),d(l)}catch{}else d(l)}),o={listeners:r,errHandlers:i,rawEmitters:a,watcher:c},L.set(e,o)}return()=>{v(o,R,r),v(o,O,i),v(o,x,a),be(o.listeners)&&(o.watcher.close(),L.delete(e),Mt.forEach(Ht(o)),o.watcher=void 0,Object.freeze(o))}},J=new Map,jt=(s,e,t,n)=>{let{listener:r,rawEmitter:i}=n,a=J.get(e),o=a&&a.options;return o&&(o.persistent<t.persistent||o.interval>t.interval)&&(ke(e),a=void 0),a?(A(a,R,r),A(a,x,i)):(a={listeners:r,rawEmitters:i,options:t,watcher:Ct(e,t,(c,l)=>{Q(a.rawEmitters,f=>{f(P.CHANGE,e,{curr:c,prev:l})});let d=c.mtimeMs;(c.size!==l.size||d>l.mtimeMs||d===0)&&Q(a.listeners,f=>f(s,c))})},J.set(e,a)),()=>{v(a,R,r),v(a,x,i),be(a.listeners)&&(J.delete(e),ke(e),a.options=a.watcher=void 0,Object.freeze(a))}},W=class{constructor(e){this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){let n=this.fsw.options,r=y.dirname(e),i=y.basename(e);this.fsw._getWatchedDir(r).add(i);let o=y.resolve(e),c={persistent:n.persistent};t||(t=B);let l;if(n.usePolling){let d=n.interval!==n.binaryInterval;c.interval=d&&Bt(i)?n.binaryInterval:n.interval,l=jt(e,o,c,{listener:t,rawEmitter:this.fsw._emitRaw})}else l=$t(e,o,c,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return l}_handleFile(e,t,n){if(this.fsw.closed)return;let r=y.dirname(e),i=y.basename(e),a=this.fsw._getWatchedDir(r),o=t;if(a.has(i))return;let c=async(d,f)=>{if(this.fsw._throttle(Ot,e,5)){if(!f||f.mtimeMs===0)try{let h=await Se(e);if(this.fsw.closed)return;let m=h.atimeMs,g=h.mtimeMs;if((!m||m<=g||g!==o.mtimeMs)&&this.fsw._emit(P.CHANGE,e,h),(Dt||Ft||Ut)&&o.ino!==h.ino){this.fsw._closeFile(d),o=h;let I=this._watchWithNodeFs(e,c);I&&this.fsw._addPathCloser(d,I)}else o=h}catch{this.fsw._remove(r,i)}else if(a.has(i)){let h=f.atimeMs,m=f.mtimeMs;(!h||h<=m||m!==o.mtimeMs)&&this.fsw._emit(P.CHANGE,e,f),o=f}}},l=this._watchWithNodeFs(e,c);if(!(n&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(P.ADD,e,0))return;this.fsw._emit(P.ADD,e,t)}return l}async _handleSymlink(e,t,n,r){if(this.fsw.closed)return;let i=e.fullPath,a=this.fsw._getWatchedDir(t);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let o;try{o=await X(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(P.CHANGE,n,e.stats)):(a.add(r),this.fsw._symlinkPaths.set(i,o),this.fsw._emit(P.ADD,n,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(i))return!0;this.fsw._symlinkPaths.set(i,!0)}_handleRead(e,t,n,r,i,a,o){if(e=y.join(e,""),o=this.fsw._throttle("readdir",e,1e3),!o)return;let c=this.fsw._getWatchedDir(n.path),l=new Set,d=this.fsw._readdirp(e,{fileFilter:f=>n.filterPath(f),directoryFilter:f=>n.filterDir(f)});if(d)return d.on(vt,async f=>{if(this.fsw.closed){d=void 0;return}let h=f.path,m=y.join(e,h);if(l.add(h),!(f.stats.isSymbolicLink()&&await this._handleSymlink(f,e,m,h))){if(this.fsw.closed){d=void 0;return}(h===r||!r&&!c.has(h))&&(this.fsw._incrReadyCount(),m=y.join(i,y.relative(i,m)),this._addToNodeFs(m,t,n,a+1))}}).on(P.ERROR,this._boundHandleError),new Promise((f,h)=>{if(!d)return h();d.once(Z,()=>{if(this.fsw.closed){d=void 0;return}let m=o?o.clear():!1;f(void 0),c.getChildren().filter(g=>g!==e&&!l.has(g)).forEach(g=>{this.fsw._remove(e,g)}),d=void 0,m&&this._handleRead(e,!1,n,r,i,a,o)})})}async _handleDir(e,t,n,r,i,a,o){let c=this.fsw._getWatchedDir(y.dirname(e)),l=c.has(y.basename(e));!(n&&this.fsw.options.ignoreInitial)&&!i&&!l&&this.fsw._emit(P.ADD_DIR,e,t),c.add(y.basename(e)),this.fsw._getWatchedDir(e);let d,f,h=this.fsw.options.depth;if((h==null||r<=h)&&!this.fsw._symlinkPaths.has(o)){if(!i&&(await this._handleRead(e,n,a,i,e,r,d),this.fsw.closed))return;f=this._watchWithNodeFs(e,(m,g)=>{g&&g.mtimeMs===0||this._handleRead(m,!1,a,i,e,r,d)})}return f}async _addToNodeFs(e,t,n,r,i){let a=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return a(),!1;let o=this.fsw._getWatchHelpers(e);n&&(o.filterPath=c=>n.filterPath(c),o.filterDir=c=>n.filterDir(c));try{let c=await Lt[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(e),h=l?await X(e):e;if(this.fsw.closed||(d=await this._handleDir(o.watchPath,c,t,r,i,o,h),this.fsw.closed))return;f!==h&&h!==void 0&&this.fsw._symlinkPaths.set(f,h)}else if(c.isSymbolicLink()){let f=l?await X(e):e;if(this.fsw.closed)return;let h=y.dirname(o.watchPath);if(this.fsw._getWatchedDir(h).add(o.watchPath),this.fsw._emit(P.ADD,o.watchPath,c),d=await this._handleDir(h,c,t,r,e,o,f),this.fsw.closed)return;f!==void 0&&this.fsw._symlinkPaths.set(y.resolve(e),f)}else d=this._handleFile(o.watchPath,c,t);return a(),d&&this.fsw._addPathCloser(e,d),!1}catch(c){if(this.fsw._handleError(c))return a(),e}}};var te="/",Gt="//",Ue=".",Vt="..",Xt="string",Jt=/\\/g,Ne=/\/\//,Qt=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,Zt=/^\.[/\\]/;function $(s){return Array.isArray(s)?s:[s]}var se=s=>typeof s=="object"&&s!==null&&!(s instanceof RegExp);function es(s){return typeof s=="function"?s:typeof s=="string"?e=>s===e:s instanceof RegExp?e=>s.test(e):typeof s=="object"&&s!==null?e=>{if(s.path===e)return!0;if(s.recursive){let t=p.relative(s.path,e);return t?!t.startsWith("..")&&!p.isAbsolute(t):!1}return!1}:()=>!1}function ts(s){if(typeof s!="string")throw new Error("string expected");s=p.normalize(s),s=s.replace(/\\/g,"/");let e=!1;s.startsWith("//")&&(e=!0);let t=/\/\//;for(;s.match(t);)s=s.replace(t,"/");return e&&(s="/"+s),s}function Ae(s,e,t){let n=ts(e);for(let r=0;r<s.length;r++){let i=s[r];if(i(n,t))return!0}return!1}function ss(s,e){if(s==null)throw new TypeError("anymatch: specify first argument");let n=$(s).map(r=>es(r));return e==null?(r,i)=>Ae(n,r,i):Ae(n,e)}var ve=s=>{let e=$(s).flat();if(!e.every(t=>typeof t===Xt))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(Oe)},De=s=>{let e=s.replace(Jt,te),t=!1;for(e.startsWith(Gt)&&(t=!0);e.match(Ne);)e=e.replace(Ne,te);return t&&(e=te+e),e},Oe=s=>De(p.normalize(De(s))),Fe=(s="")=>e=>typeof e=="string"?Oe(p.isAbsolute(e)?e:p.join(s,e)):e,ns=(s,e)=>p.isAbsolute(s)?s:p.join(e,s),rs=Object.freeze(new Set),ne=class{constructor(e,t){this.path=e,this._removeWatcher=t,this.items=new Set}add(e){let{items:t}=this;t&&e!==Ue&&e!==Vt&&t.add(e)}async remove(e){let{items:t}=this;if(!t||(t.delete(e),t.size>0))return;let n=this.path;try{await Kt(n)}catch{this._removeWatcher&&this._removeWatcher(p.dirname(n),p.basename(n))}}has(e){let{items:t}=this;if(t)return t.has(e)}getChildren(){let{items:e}=this;return e?[...e.values()]:[]}dispose(){this.items.clear(),this.path="",this._removeWatcher=B,this.items=rs,Object.freeze(this)}},is="stat",os="lstat",re=class{constructor(e,t,n){this.fsw=n;let r=e;this.path=e=e.replace(Zt,""),this.watchPath=r,this.fullWatchPath=p.resolve(r),this.dirParts=[],this.dirParts.forEach(i=>{i.length>1&&i.pop()}),this.followSymlinks=t,this.statMethod=t?is:os}entryPath(e){return p.join(this.watchPath,p.relative(this.watchPath,e.fullPath))}filterPath(e){let{stats:t}=e;if(t&&t.isSymbolicLink())return this.filterDir(e);let n=this.entryPath(e);return this.fsw._isntIgnored(n,t)&&this.fsw._hasReadPermissions(t)}filterDir(e){return this.fsw._isntIgnored(this.entryPath(e),e.stats)}},ie=class extends qt{constructor(e={}){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 t=e.awaitWriteFinish,n={stabilityThreshold:2e3,pollInterval:100},r={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...e,ignored:e.ignored?$(e.ignored):$([]),awaitWriteFinish:t===!0?n:typeof t=="object"?{...n,...t}:!1};xe&&(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=B,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(e){if(se(e)){for(let t of this._ignoredPaths)if(se(t)&&t.path===e.path&&t.recursive===e.recursive)return}this._ignoredPaths.add(e)}_removeIgnoredPath(e){if(this._ignoredPaths.delete(e),typeof e=="string")for(let t of this._ignoredPaths)se(t)&&t.path===e&&this._ignoredPaths.delete(t)}add(e,t,n){let{cwd:r}=this.options;this.closed=!1,this._closePromise=void 0;let i=ve(e);return r&&(i=i.map(a=>ns(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,t);return o&&this._emitReady(),o})).then(a=>{this.closed||a.forEach(o=>{o&&this.add(p.dirname(o),p.basename(t||o))})}),this}unwatch(e){if(this.closed)return this;let t=ve(e),{cwd:n}=this.options;return t.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 e=[];return this._closers.forEach(t=>t.forEach(n=>{let r=n();r instanceof Promise&&e.push(r)})),this._streams.forEach(t=>t.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(t=>t.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=e.length?Promise.all(e).then(()=>{}):Promise.resolve(),this._closePromise}getWatched(){let e={};return this._watched.forEach((t,n)=>{let i=(this.options.cwd?p.relative(this.options.cwd,n):n)||Ue;e[i]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(e,...t),e!==_.ERROR&&this.emit(_.ALL,e,...t)}async _emit(e,t,n){if(this.closed)return;let r=this.options;ee&&(t=p.normalize(t)),r.cwd&&(t=p.relative(r.cwd,t));let i=[t];n!=null&&i.push(n);let a=r.awaitWriteFinish,o;if(a&&(o=this._pendingWrites.get(t)))return o.lastChange=new Date,this;if(r.atomic){if(e===_.UNLINK)return this._pendingUnlinks.set(t,[e,...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;e===_.ADD&&this._pendingUnlinks.has(t)&&(e=_.CHANGE,this._pendingUnlinks.delete(t))}if(a&&(e===_.ADD||e===_.CHANGE)&&this._readyEmitted){let c=(l,d)=>{l?(e=_.ERROR,i[0]=l,this.emitWithAll(e,i)):d&&(i.length>1?i[1]=d:i.push(d),this.emitWithAll(e,i))};return this._awaitWriteFinish(t,a.stabilityThreshold,e,c),this}if(e===_.CHANGE&&!this._throttle(_.CHANGE,t,50))return this;if(r.alwaysStat&&n===void 0&&(e===_.ADD||e===_.ADD_DIR||e===_.CHANGE)){let c=r.cwd?p.join(r.cwd,t):t,l;try{l=await zt(c)}catch{}if(!l||this.closed)return;i.push(l)}return this.emitWithAll(e,i),this}_handleError(e){let t=e&&e.code;return e&&t!=="ENOENT"&&t!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||t!=="EPERM"&&t!=="EACCES")&&this.emit(_.ERROR,e),e||this.closed}_throttle(e,t,n){this._throttled.has(e)||this._throttled.set(e,new Map);let r=this._throttled.get(e);if(!r)throw new Error("invalid throttle");let i=r.get(t);if(i)return i.count++,!1;let a,o=()=>{let l=r.get(t),d=l?l.count:0;return r.delete(t),clearTimeout(a),l&&clearTimeout(l.timeoutObject),d};a=setTimeout(o,n);let c={timeoutObject:a,clear:o,count:0};return r.set(t,c),c}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,t,n,r){let i=this.options.awaitWriteFinish;if(typeof i!="object")return;let a=i.pollInterval,o,c=e;this.options.cwd&&!p.isAbsolute(e)&&(c=p.join(this.options.cwd,e));let l=new Date,d=this._pendingWrites;function f(h){Yt(c,(m,g)=>{if(m||!d.has(e)){m&&m.code!=="ENOENT"&&r(m);return}let I=Number(new Date);h&&g.size!==h.size&&(d.get(e).lastChange=I);let at=d.get(e);I-at.lastChange>=t?(d.delete(e),r(void 0,g)):o=setTimeout(f,a,g)})}d.has(e)||(d.set(e,{lastChange:l,cancelWait:()=>(d.delete(e),clearTimeout(o),n)}),o=setTimeout(f,a))}_isIgnored(e,t){if(this.options.atomic&&Qt.test(e))return!0;if(!this._userIgnored){let{cwd:n}=this.options,i=(this.options.ignored||[]).map(Fe(n)),o=[...[...this._ignoredPaths].map(Fe(n)),...i];this._userIgnored=ss(o,void 0)}return this._userIgnored(e,t)}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e){return new re(e,this.options.followSymlinks,this)}_getWatchedDir(e){let t=p.resolve(e);return this._watched.has(t)||this._watched.set(t,new ne(t,this._boundRemove)),this._watched.get(t)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,t,n){let r=p.join(e,t),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(e,t,!0),this._getWatchedDir(r).getChildren().forEach(h=>this._remove(r,h));let c=this._getWatchedDir(e),l=c.has(t);c.remove(t),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(e){this._closeFile(e);let t=p.dirname(e);this._getWatchedDir(t).remove(p.basename(e))}_closeFile(e){let t=this._closers.get(e);t&&(t.forEach(n=>n()),this._closers.delete(e))}_addPathCloser(e,t){if(!t)return;let n=this._closers.get(e);n||(n=[],this._closers.set(e,n)),n.push(t)}_readdirp(e,t){if(this.closed)return;let n={type:_.ALL,alwaysStat:!0,lstat:!0,...t,depth:0},r=Pe(e,n);return this._streams.add(r),r.once(Ce,()=>{r=void 0}),r.once(Z,()=>{r&&(this._streams.delete(r),r=void 0)}),r}};function Le(s,e={}){let t=new ie(e);return t.add(s),t}import{build as cs}from"esbuild";import{jwtDecode as ds}from"jwt-decode";import{fork as ls}from"node:child_process";import{existsSync as We,promises as fs}from"node:fs";import{basename as ae,dirname as Y,join as de,relative as Be}from"node:path";import{fileURLToPath as us}from"node:url";import{Issuer as hs,custom as ps}from"openid-client";import{Logger as ms}from"@5minds/processcube_engine_sdk";import{EngineClient as as}from"@5minds/processcube_engine_client";var oe=process.env.PROCESSCUBE_ENGINE_URL??"http://localhost:10560",u=new as(oe);var ys={token:"ZHVtbXlfdG9rZW4=",userId:"dummy_token"},ws=.85,j=["external_task.ts","external_task.js"],D=process.env.PROCESSCUBE_AUTHORITY_URL!==void 0,E=new ms("processcube_app_sdk:external_task_adapter"),S={},le={},b,fe=!1,He=6,_s=3e5,gs=3e4,ce=10,Es=3e4,Me=10,Is=6e4;async function $e(s){if(s&&!We(s))throw new Error(`Invalid customExternalTasksDirPath. The given path '${s}' does not exist`);ps.setHttpOptionsDefaults({timeout:1e5});let e=await ze();b=he(e),await Ke(e);let t=ks(s);Le(t).on("add",async n=>{if(j.includes(ae(n)))return ue(n,t)}).on("change",async n=>{if(j.includes(ae(n)))return Ts(n,t)}).on("unlink",async n=>{j.includes(ae(n))&&je(n)}).on("error",n=>E.error(`Watcher error: ${n}`))}async function ue(s,e){let t=Y(s);if((await fs.readdir(t)).filter(f=>j.includes(f)).length>1){E.error(`Multiple external task files found in directory ${t}. Stopping all external task workers for this directory.`),S[t]&&je(s);return}let i=await qe(s),a=Be(e,t),o=Ge(a),c=typeof __dirname<"u"?__dirname:Y(us(import.meta.url)),l=de(c,"lib/ExternalTaskWorkerProcess.cjs"),d=ls(l,{stdio:["pipe","inherit","inherit","ipc"],env:{...process.env,PROCESSCUBE_ENGINE_URL:oe}});S[t]=d,d.once("disconnect",()=>{delete S[t]}),d.on("error",f=>{E.error(`External Task Worker process error for ${o}`,{error:f,topic:o,workerDirectory:t})}),d.on("exit",(f,h)=>{if(E.info(`External Task Worker process exited for ${o}`,{code:f,signal:h,topic:o,workerDirectory:t}),delete S[t],f===3||f===4)if(Rs(t)){let m=le[t]?.count??1,g=Math.min(1e3*Math.pow(2,m-1),gs);E.info(`Scheduling restart for ${o} in ${g}ms (attempt ${m}/${He})`,{delay:g,restartCount:m,exitCode:f,topic:o,workerDirectory:t}),setTimeout(async()=>{try{if(D&&!fe){E.info("Token refresh cycle is not active, restarting it before worker restart");let I=await ze();b=he(I),await Ke(I)}await ue(s,e)}catch(I){E.error(`Failed to restart External Task Worker process for ${o}`,{error:I,topic:o,workerDirectory:t})}},g)}else E.error(`External Task Worker process for ${o} reached maximum restart attempts`,{exitCode:f,topic:o,workerDirectory:t})}),d.send({action:"create",payload:{topic:o,identity:b,moduleString:i,workerPath:s}})}async function Ts(s,e){let t=Y(s),n=S[t];if(!n)return ue(s,e);let r=await qe(s),i=Be(e,t),a=Ge(i);n.send({action:"restart",payload:{topic:a,identity:b,moduleString:r,workerPath:s}})}function je(s){let e=Y(s),t=S[e];t&&t.kill()}async function Ye(){if(!D)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 hs.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 ze(){if(!D)return null;for(let s=1;s<=ce;s++)try{return await Ye()}catch(e){let t=Math.min(1e3*Math.pow(2,s-1),Es);if(E.error(`Failed to fetch initial token set (attempt ${s}/${ce}), retrying in ${t}ms`,{error:e,attempt:s,delay:t}),s===ce)throw e;await new Promise(n=>setTimeout(n,t))}return null}function he(s){if(!D||s===null)return ys;let e=s.access_token,t=ds(e);return{token:s.access_token,userId:t.sub}}async function Ke(s){if(!D||s===null||fe)return;fe=!0;let e=0,n=await Ps(s)*ws*1e3,r=async()=>{try{let i=await Ye();b=he(i);for(let[a,o]of Object.entries(S))try{o.send({action:"updateIdentity",payload:{identity:b}})}catch(c){E.warn(`Failed to send identity update to worker process ${a}`,{sendError:c})}e=0,setTimeout(r,n)}catch(i){e++;let a=Math.min(1e3*Math.pow(2,e-1),Is);e<=Me?E.error(`Could not refresh identity (attempt ${e}/${Me}), retrying in ${a}ms`,{error:i,attempt:e,delay:a}):E.error(`Could not refresh identity (attempt ${e}), continuing to retry every ${a}ms`,{error:i,attempt:e,delay:a}),setTimeout(r,a)}};setTimeout(r,n)}async function qe(s){let e=await cs({entryPoints:[s],write:!1,bundle:!0,platform:"node",target:"node18",format:"cjs",external:["@opentelemetry/api"]});if(e.errors.length>0)throw E.error(`Could not transpile file at '${s}'`,{errors:e.errors}),new Error(`Could not transpile file at '${s}'`);return e.warnings.length>0&&E.warn(`Transpiled file at '${s}' with warnings`,{warnings:e.warnings}),e.outputFiles[0].text}async function Ps(s){let e=s.expires_in;if(!e&&s.expires_at&&(e=Math.floor(s.expires_at-Date.now()/1e3)),e===void 0)throw new Error("Could not determine the time until the access token for external task workers expires");return e}function Ge(s){return s.replace(/^\.\/+|\([^)]+\)|^\/*|\/*$/g,"").replace(/[\/]{2,}/g,"/")}function ks(s){let e,t=[s,de(process.cwd(),"app"),de(process.cwd(),"src","app")];for(let n of t)if(n&&We(n)){e=n;break}if(!e)throw new Error("Could not find external tasks directory");return e}function Rs(s){let e=Date.now(),t=le[s];return!t||e-t.timestamp>_s?(le[s]={count:1,timestamp:e},!0):t.count>=He?!1:(t.count++,!0)}function Tn(){return u}import{getToken as Ve}from"next-auth/jwt";import{ResponseCookies as Ss}from"next/dist/compiled/@edge-runtime/cookies/index.js";import{cookies as z,headers as Xe}from"next/headers.js";async function w(){let s=await Ve({req:{cookies:await z(),headers:await Xe()}});if(s?.expiresAt&&Date.now()>=s.expiresAt*1e3){let t=await fetch(`${process.env.NEXTAUTH_URL}/api/auth/session`,{method:"GET",headers:{"Content-Type":"application/json",cookie:(await z()).toString()}}),n=new Ss(t.headers);if(n.getAll().length){let r=!1;try{for(let i of n.getAll())(await z()).set(i.name,i.value,{...i})}catch{r=!0}if(s=await Ve({req:{cookies:r?n:await z(),headers:await Xe()}}),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 F}from"@5minds/processcube_engine_client";async function U(){try{return w()}catch{return}}async function Je(s){let e=await U();return(await u.processInstances.query({processInstanceId:s},{identity:e,includeXml:!0})).processInstances[0]}async function Qe(s,e={sortSettings:{sortBy:F.FlowNodeInstances.FlowNodeInstanceSortableColumns.createdAt,sortDir:"ASC"}}){return(await u.flowNodeInstances.query({processInstanceId:s},{...e,identity:e.identity??await U()})).flowNodeInstances}async function Ze(s){let e=await U();return(await u.flowNodeInstances.query({triggeredByFlowNodeInstance:s},{identity:e})).flowNodeInstances}async function et(s,e,t){let n=await U();await u.processInstances.retryProcessInstance(s,{flowNodeInstanceId:e,newStartToken:t,identity:n})}async function tt(s){let e=await U();await u.processInstances.terminateProcessInstance(s,e)}async function An(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 u.processInstances.query({...s?.query,state:F.ProcessInstances.ProcessInstanceState.running},s?.options)}async function vn(s={},e=!0){let{processInstanceId:t}=s,n=typeof e=="boolean"?e==!0?await w():void 0:e;return new Promise(async(r,i)=>{let a=[],o=async c=>{if(t!==void 0&&c.processInstanceId!==t)return;let d=await u.processInstances.query({processInstanceId:c.processInstanceId},{identity:n});for(let f of a)u.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 u.notification.onProcessEnded(o,{identity:n})),a.push(await u.notification.onProcessError(o,{identity:n})),a.push(await u.notification.onProcessTerminated(o,{identity:n})),t){let c=await u.processInstances.query({processInstanceId:t,state:[F.ProcessInstances.ProcessInstanceState.finished,F.ProcessInstances.ProcessInstanceState.terminated,F.ProcessInstances.ProcessInstanceState.error]},{identity:n});if(c.totalCount>0){for(let l of a)u.notification.removeSubscription(l,n);r(c.processInstances[0])}}})}import{DataModels as k}from"@5minds/processcube_engine_client";import{mapUserTask as st,mapUserTaskList as C}from"../common/index.mjs";async function Bn(s={},e=!0){let{correlationId:t,processInstanceId:n,flowNodeId:r}=s,i=typeof e=="boolean"?e==!0?await w():void 0:e;return new Promise(async(a,o)=>{let c=await u.userTasks.onUserTaskWaiting(async d=>{let f=t!==void 0&&d.correlationId!==t,h=d.flowNodeInstanceId===void 0,m=n!==void 0&&d.processInstanceId!==n,g=r!==void 0&&d.flowNodeId!==r;if(f||h||m||g)return;let I=await xs(d.flowNodeInstanceId,{identity:i});return u.notification.removeSubscription(c,i),I===null?o(new Error(`UserTask with instance ID "${d.flowNodeInstanceId}" does not exist.`)):a(I)},{identity:i}),l=await Cs({correlationId:t,processInstanceId:n,flowNodeId:r,state:k.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:i});l.userTasks.length>0&&(u.notification.removeSubscription(c,i),a(l.userTasks[0]))})}async function Hn(s,e={},t={},n=!0){let r=typeof n=="boolean"?n==!0?await w():void 0:n;await u.userTasks.finishUserTask(s,t,r);let i={state:k.FlowNodeInstances.FlowNodeInstanceState.suspended,...e},a=await u.userTasks.query(i,{identity:r});return st(a.userTasks[0])}async function Cs(s,e={identity:!0}){switch(e?.identity){case!0:e.identity=await w();break;case!1:e.identity=void 0;break;case void 0:e.identity=await w();break}let t=await u.userTasks.query(s,e);return C(t)}async function $n(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 e=await u.userTasks.query({state:k.FlowNodeInstances.FlowNodeInstanceState.suspended},s);return C(e)}async function jn(s,e={identity:!0}){switch(e?.identity){case!0:e.identity=await w();break;case!1:e.identity=void 0;break;case void 0:e.identity=await w();break}let t=await u.userTasks.query({processInstanceId:s,state:k.FlowNodeInstances.FlowNodeInstanceState.suspended},e);return C(t)}async function Yn(s,e={identity:!0}){switch(e?.identity){case!0:e.identity=await w();break;case!1:e.identity=void 0;break;case void 0:e.identity=await w();break}let t=await u.userTasks.query({flowNodeId:s,state:k.FlowNodeInstances.FlowNodeInstanceState.suspended},e);return C(t)}async function xs(s,e={identity:!0}){switch(e?.identity){case!0:e.identity=await w();break;case!1:e.identity=void 0;break;case void 0:e.identity=await w();break}let t=await u.userTasks.query({flowNodeInstanceId:s,state:k.FlowNodeInstances.FlowNodeInstanceState.suspended},{...e,limit:1});return t.userTasks.length===0?null:st(t.userTasks[0])}async function zn(s,e={identity:!0}){switch(e?.identity){case!0:e.identity=await w();break;case!1:e.identity=void 0;break;case void 0:e.identity=await w();break}let t=await u.userTasks.query({correlationId:s,state:k.FlowNodeInstances.FlowNodeInstanceState.suspended},e);return C(t)}async function Kn(s,e){let t=s||await w(),n=await u.userTasks.query({state:k.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:t,...e}),r=n.userTasks.filter(i=>i.actualOwnerId===t.userId);return n.userTasks=r,C(n)}async function qn(s,e,t){await u.userTasks.reserveUserTaskInstance(s,e,t||s.userId)}async function Gn(s,e){await u.userTasks.cancelUserTaskInstanceReservation(s,e)}async function Vn(s,e){let t=s||await w(),n=await u.userTasks.query({state:k.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:t,...e}),r=n.userTasks.filter(i=>i.assignedUserIds?.includes(t.userId));return n.userTasks=r,C(n)}import{PHASE_DEVELOPMENT_SERVER as bs,PHASE_PRODUCTION_BUILD as Ns,PHASE_PRODUCTION_SERVER as As}from"next/dist/shared/lib/constants.js";var nt=!1,pe=!1;function Zn(s={}){let{applicationSdk:e,...t}=s;return async(n,r)=>{pe=pe||n===Ns;let i=n===bs||n===As;return e?.useExternalTasks&&i&&!nt&&!pe&&(nt=!0,await $e(e?.customExternalTasksDirPath)),{...t,experimental:{...t.experimental,serverComponentsExternalPackages:[...t.experimental?.serverComponentsExternalPackages||[],"esbuild"]}}}}import{redirect as vs}from"next/navigation.js";function nr(s){vs(s)}async function or(...s){return await u.processModels.startProcessInstance(...s)}async function rt(...s){await u.manualTasks.finishManualTask(...s)}async function it(...s){await u.userTasks.finishUserTask(...s)}async function ot(...s){await u.untypedTasks.finishTask(...s)}import{DataModels as Ds}from"@5minds/processcube_engine_client";async function Fs(){try{return w()}catch{return}}var _r=async(s,e)=>{let t=await Fs();e==="bpmn:UserTask"?await it(s,{},t):e==="bpmn:ManualTask"?await rt(s,t):e==="bpmn:Task"?await ot(s,t):console.error(`[@5minds/processcube_app_sdk:handlePlay] Unsupported flow node type: ${e}`)},gr=async s=>{await tt(s)},Er=async(s,e,t)=>{await et(s,e,t)},Ir=async s=>Je(s),Tr=async s=>Qe(s,{sortSettings:{sortBy:Ds.FlowNodeInstances.FlowNodeInstanceSortableColumns.createdAt,sortDir:"DESC"}}),Pr=async s=>Ze(s);export{ye as AuthorityClient,Gn as cancelReservedUserTask,rt as finishManualTask,_r as finishTask,ot as finishUntypedTask,it as finishUserTask,Hn as finishUserTaskAndGetNext,An as getActiveProcessInstances,Vn as getAssignedUserTasksByIdentity,Tn as getEngineClient,Tr as getFlowNodeInstances,Qe as getFlowNodeInstancesByProcessInstanceId,Ze as getFlowNodeInstancesTriggeredByFlowNodeInstanceIds,w as getIdentity,Ir as getProcessInstance,Je as getProcessInstanceById,Kn as getReservedUserTasksByIdentity,q as getServerAccessToken,Ms as getServerIdentity,Pr as getTriggeredFlowNodeInstances,Cs as getUserTasks,xs as getWaitingUserTaskByFlowNodeInstanceId,$n as getWaitingUserTasks,zn as getWaitingUserTasksByCorrelationId,Yn as getWaitingUserTasksByFlowNodeId,jn as getWaitingUserTasksByProcessInstanceId,nr as navigateToUrl,qn as reserveUserTask,Er as retryProcess,et as retryProcessInstance,or as startProcess,gr as terminateProcess,tt as terminateProcessInstance,vn as waitForProcessEnd,Bn as waitForUserTask,Zn as withApplicationSdk};
1
+ import"only-server";import"../common/index.mjs";import{Logger as pt}from"@5minds/processcube_engine_sdk";import{jwtDecode as ct}from"jwt-decode";import{Logger as lt}from"@5minds/processcube_engine_sdk";var K=new lt("processcube_app_sdk:server_identity"),dt=.85,ft="upe_admin engine_read engine_write",N=null;function ut(s){let e=s?.authorityUrl??process.env.PROCESSCUBE_AUTHORITY_URL,t=s?.clientId??process.env.PROCESSCUBE_SERVER_CLIENT_ID,n=s?.clientSecret??process.env.PROCESSCUBE_SERVER_CLIENT_SECRET,r=s?.scopes??process.env.PROCESSCUBE_SERVER_SCOPES??ft;if(!e)throw new Error("PROCESSCUBE_AUTHORITY_URL is not configured. Set the environment variable or pass authorityUrl.");if(!t)throw new Error("PROCESSCUBE_SERVER_CLIENT_ID is not configured. Set the environment variable or pass clientId.");if(!n)throw new Error("PROCESSCUBE_SERVER_CLIENT_SECRET is not configured. Set the environment variable or pass clientSecret.");return{authorityUrl:e,clientId:t,clientSecret:n,scopes:r}}function ht(){return N?Date.now()<N.expiresAt:!1}async function q(s){if(!s?.skipCache&&ht())return N.accessToken;let{authorityUrl:e,clientId:t,clientSecret:n,scopes:r}=ut(s);K.info("Fetching new server access token");let i=await fetch(`${e}/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},redirect:"follow",body:new URLSearchParams({grant_type:"client_credentials",client_id:t,client_secret:n,scope:r}).toString(),cache:"no-store"});if(!i.ok){let c=await i.text().catch(()=>""),d=`Failed to fetch server access token: ${i.status} ${i.statusText}${c?` \u2014 ${c}`:""}`;throw K.error(d),new Error(d)}let a=await i.json();if(!a.access_token)throw new Error("Authority response did not contain an access_token");let o=a.expires_in;return o&&o>0?N={accessToken:a.access_token,expiresAt:Date.now()+o*dt*1e3}:N=null,K.info("Server access token fetched successfully"),a.access_token}async function Ms(s){let e=await q(s),t=ct(e);if(!t.sub)throw new Error('Server access token does not contain a "sub" claim');return{token:e,userId:t.sub}}var me=new pt("processcube_app_sdk:authority_client"),ye=class{authorityUrl;tokenOptions;constructor(e){let t=e?.authorityUrl??process.env.PROCESSCUBE_AUTHORITY_URL;if(!t)throw new Error("PROCESSCUBE_AUTHORITY_URL is not configured. Set the environment variable or pass authorityUrl.");this.authorityUrl=t.replace(/\/+$/,""),this.tokenOptions=e??{}}async request(e,t,n){let r=await q(this.tokenOptions),i=`${this.authorityUrl}${t}`;me.info(`Authority request: ${e} ${t}`);let a={Cookie:`access_token=${r}`,"Content-Type":"application/json"},o=await fetch(i,{method:e,headers:a,redirect:"follow",body:n!==void 0?JSON.stringify(n):void 0}),c;try{c=await o.json()}catch{c=void 0}return o.ok||me.error(`Authority request failed: ${e} ${t} \u2192 ${o.status} ${o.statusText}`),{ok:o.ok,status:o.status,data:c}}userAdminPath(e,t){return`/acr/username_password/admin/user/${encodeURIComponent(e)}/${t}`}async updateClaim(e,t,n){return this.request("PATCH",this.userAdminPath(e,"update/claim"),{claimName:t,claimValue:n})}async addScope(e,t){return this.request("PATCH",this.userAdminPath(e,"add/scope"),{scopeName:t})}async addGroup(e,t){return this.request("PATCH",this.userAdminPath(e,"add/group"),{groupName:t})}async deleteUser(e,t){return this.request("DELETE",this.userAdminPath(e,"delete"),{fullDelete:t?.fullDelete??!1})}};import{stat as Yt}from"node:fs";import{stat as zt,readdir as Kt}from"node:fs/promises";import{EventEmitter as qt}from"node:events";import*as p from"node:path";import{stat as mt,lstat as we,readdir as yt,realpath as wt}from"node:fs/promises";import{Readable as _t}from"node:stream";import{resolve as _e,relative as gt,join as Et,sep as It}from"node:path";var T={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},G={root:".",fileFilter:s=>!0,directoryFilter:s=>!0,type:T.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(G);var Te="READDIRP_RECURSIVE_ERROR",Tt=new Set(["ENOENT","EPERM","EACCES","ELOOP",Te]),ge=[T.DIR_TYPE,T.EVERYTHING_TYPE,T.FILE_DIR_TYPE,T.FILE_TYPE],Pt=new Set([T.DIR_TYPE,T.EVERYTHING_TYPE,T.FILE_DIR_TYPE]),kt=new Set([T.EVERYTHING_TYPE,T.FILE_DIR_TYPE,T.FILE_TYPE]),Rt=s=>Tt.has(s.code),St=process.platform==="win32",Ee=s=>!0,Ie=s=>{if(s===void 0)return Ee;if(typeof s=="function")return s;if(typeof s=="string"){let e=s.trim();return t=>t.basename===e}if(Array.isArray(s)){let e=s.map(t=>t.trim());return t=>e.some(n=>t.basename===n)}return Ee},V=class extends _t{constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark});let t={...G,...e},{root:n,type:r}=t;this._fileFilter=Ie(t.fileFilter),this._directoryFilter=Ie(t.directoryFilter);let i=t.lstat?we:mt;St?this._stat=a=>i(a,{bigint:!0}):this._stat=i,this._maxDepth=t.depth??G.depth,this._wantsDir=r?Pt.has(r):!1,this._wantsFile=r?kt.has(r):!1,this._wantsEverything=r===T.EVERYTHING_TYPE,this._root=_e(n),this._isDirent=!t.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(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let t=this.parent,n=t&&t.files;if(n&&n.length>0){let{path:r,depth:i}=t,a=n.splice(0,e).map(c=>this._formatEntry(c,r)),o=await Promise.all(a);for(let c of o){if(!c)continue;if(this.destroyed)return;let d=await this._getEntryType(c);d==="directory"&&this._directoryFilter(c)?(i<=this._maxDepth&&this.parents.push(this._exploreDir(c.fullPath,i+1)),this._wantsDir&&(this.push(c),e--)):(d==="file"||this._includeAsFile(c))&&this._fileFilter(c)&&this._wantsFile&&(this.push(c),e--)}}else{let r=this.parents.pop();if(!r){this.push(null);break}if(this.parent=await r,this.destroyed)return}}}catch(t){this.destroy(t)}finally{this.reading=!1}}}async _exploreDir(e,t){let n;try{n=await yt(e,this._rdOptions)}catch(r){this._onError(r)}return{files:n,depth:t,path:e}}async _formatEntry(e,t){let n,r=this._isDirent?e.name:e;try{let i=_e(Et(t,r));n={path:gt(this._root,i),fullPath:i,basename:r},n[this._statsProp]=this._isDirent?e:await this._stat(i)}catch(i){this._onError(i);return}return n}_onError(e){Rt(e)&&!this.destroyed?this.emit("warn",e):this.destroy(e)}async _getEntryType(e){if(!e&&this._statsProp in e)return"";let t=e[this._statsProp];if(t.isFile())return"file";if(t.isDirectory())return"directory";if(t&&t.isSymbolicLink()){let n=e.fullPath;try{let r=await wt(n),i=await we(r);if(i.isFile())return"file";if(i.isDirectory()){let a=r.length;if(n.startsWith(r)&&n.substr(a,1)===It){let o=new Error(`Circular symlink detected: "${n}" points to "${r}"`);return o.code=Te,this._onError(o)}return"directory"}}catch(r){return this._onError(r),""}}}_includeAsFile(e){let t=e&&e[this._statsProp];return t&&this._wantsEverything&&!t.isDirectory()}};function Pe(s,e={}){let t=e.entryType||e.type;if(t==="both"&&(t=T.FILE_DIR_TYPE),t&&(e.type=t),s){if(typeof s!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(t&&!ge.includes(t))throw new Error(`readdirp: Invalid type passed. Use one of ${ge.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return e.root=s,new V(e)}import{watchFile as Ct,unwatchFile as ke,watch as bt}from"node:fs";import{open as xt,stat as Se,lstat as Nt,realpath as X}from"node:fs/promises";import*as y from"node:path";import{type as At}from"node:os";var vt="data",Z="end",Ce="close",B=()=>{};var H=process.platform,ee=H==="win32",Dt=H==="darwin",Ft=H==="linux",Ut=H==="freebsd",be=At()==="OS400",_={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},P=_,Ot="watch",Lt={lstat:Nt,stat:Se},R="listeners",O="errHandlers",b="rawEmitters",Mt=[R,O,b],Wt=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"]),Bt=s=>Wt.has(y.extname(s).slice(1).toLowerCase()),Q=(s,e)=>{s instanceof Set?s.forEach(e):e(s)},A=(s,e,t)=>{let n=s[e];n instanceof Set||(s[e]=n=new Set([n])),n.add(t)},Ht=s=>e=>{let t=s[e];t instanceof Set?t.clear():delete s[e]},v=(s,e,t)=>{let n=s[e];n instanceof Set?n.delete(t):n===t&&delete s[e]},xe=s=>s instanceof Set?s.size===0:!s,L=new Map;function Re(s,e,t,n,r){let i=(a,o)=>{t(s),r(a,o,{watchedPath:s}),o&&s!==o&&M(y.resolve(s,o),R,y.join(s,o))};try{return bt(s,{persistent:e.persistent},i)}catch(a){n(a);return}}var M=(s,e,t,n,r)=>{let i=L.get(s);i&&Q(i[e],a=>{a(t,n,r)})},$t=(s,e,t,n)=>{let{listener:r,errHandler:i,rawEmitter:a}=n,o=L.get(e),c;if(!t.persistent)return c=Re(s,t,r,i,a),c?c.close.bind(c):void 0;if(o)A(o,R,r),A(o,O,i),A(o,b,a);else{if(c=Re(s,t,M.bind(null,e,R),i,M.bind(null,e,b)),!c)return;c.on(P.ERROR,async d=>{let l=M.bind(null,e,O);if(o&&(o.watcherUnusable=!0),ee&&d.code==="EPERM")try{await(await xt(s,"r")).close(),l(d)}catch{}else l(d)}),o={listeners:r,errHandlers:i,rawEmitters:a,watcher:c},L.set(e,o)}return()=>{v(o,R,r),v(o,O,i),v(o,b,a),xe(o.listeners)&&(o.watcher.close(),L.delete(e),Mt.forEach(Ht(o)),o.watcher=void 0,Object.freeze(o))}},J=new Map,jt=(s,e,t,n)=>{let{listener:r,rawEmitter:i}=n,a=J.get(e),o=a&&a.options;return o&&(o.persistent<t.persistent||o.interval>t.interval)&&(ke(e),a=void 0),a?(A(a,R,r),A(a,b,i)):(a={listeners:r,rawEmitters:i,options:t,watcher:Ct(e,t,(c,d)=>{Q(a.rawEmitters,f=>{f(P.CHANGE,e,{curr:c,prev:d})});let l=c.mtimeMs;(c.size!==d.size||l>d.mtimeMs||l===0)&&Q(a.listeners,f=>f(s,c))})},J.set(e,a)),()=>{v(a,R,r),v(a,b,i),xe(a.listeners)&&(J.delete(e),ke(e),a.options=a.watcher=void 0,Object.freeze(a))}},W=class{constructor(e){this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){let n=this.fsw.options,r=y.dirname(e),i=y.basename(e);this.fsw._getWatchedDir(r).add(i);let o=y.resolve(e),c={persistent:n.persistent};t||(t=B);let d;if(n.usePolling){let l=n.interval!==n.binaryInterval;c.interval=l&&Bt(i)?n.binaryInterval:n.interval,d=jt(e,o,c,{listener:t,rawEmitter:this.fsw._emitRaw})}else d=$t(e,o,c,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return d}_handleFile(e,t,n){if(this.fsw.closed)return;let r=y.dirname(e),i=y.basename(e),a=this.fsw._getWatchedDir(r),o=t;if(a.has(i))return;let c=async(l,f)=>{if(this.fsw._throttle(Ot,e,5)){if(!f||f.mtimeMs===0)try{let h=await Se(e);if(this.fsw.closed)return;let m=h.atimeMs,g=h.mtimeMs;if((!m||m<=g||g!==o.mtimeMs)&&this.fsw._emit(P.CHANGE,e,h),(Dt||Ft||Ut)&&o.ino!==h.ino){this.fsw._closeFile(l),o=h;let I=this._watchWithNodeFs(e,c);I&&this.fsw._addPathCloser(l,I)}else o=h}catch{this.fsw._remove(r,i)}else if(a.has(i)){let h=f.atimeMs,m=f.mtimeMs;(!h||h<=m||m!==o.mtimeMs)&&this.fsw._emit(P.CHANGE,e,f),o=f}}},d=this._watchWithNodeFs(e,c);if(!(n&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(P.ADD,e,0))return;this.fsw._emit(P.ADD,e,t)}return d}async _handleSymlink(e,t,n,r){if(this.fsw.closed)return;let i=e.fullPath,a=this.fsw._getWatchedDir(t);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let o;try{o=await X(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(P.CHANGE,n,e.stats)):(a.add(r),this.fsw._symlinkPaths.set(i,o),this.fsw._emit(P.ADD,n,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(i))return!0;this.fsw._symlinkPaths.set(i,!0)}_handleRead(e,t,n,r,i,a,o){if(e=y.join(e,""),o=this.fsw._throttle("readdir",e,1e3),!o)return;let c=this.fsw._getWatchedDir(n.path),d=new Set,l=this.fsw._readdirp(e,{fileFilter:f=>n.filterPath(f),directoryFilter:f=>n.filterDir(f)});if(l)return l.on(vt,async f=>{if(this.fsw.closed){l=void 0;return}let h=f.path,m=y.join(e,h);if(d.add(h),!(f.stats.isSymbolicLink()&&await this._handleSymlink(f,e,m,h))){if(this.fsw.closed){l=void 0;return}(h===r||!r&&!c.has(h))&&(this.fsw._incrReadyCount(),m=y.join(i,y.relative(i,m)),this._addToNodeFs(m,t,n,a+1))}}).on(P.ERROR,this._boundHandleError),new Promise((f,h)=>{if(!l)return h();l.once(Z,()=>{if(this.fsw.closed){l=void 0;return}let m=o?o.clear():!1;f(void 0),c.getChildren().filter(g=>g!==e&&!d.has(g)).forEach(g=>{this.fsw._remove(e,g)}),l=void 0,m&&this._handleRead(e,!1,n,r,i,a,o)})})}async _handleDir(e,t,n,r,i,a,o){let c=this.fsw._getWatchedDir(y.dirname(e)),d=c.has(y.basename(e));!(n&&this.fsw.options.ignoreInitial)&&!i&&!d&&this.fsw._emit(P.ADD_DIR,e,t),c.add(y.basename(e)),this.fsw._getWatchedDir(e);let l,f,h=this.fsw.options.depth;if((h==null||r<=h)&&!this.fsw._symlinkPaths.has(o)){if(!i&&(await this._handleRead(e,n,a,i,e,r,l),this.fsw.closed))return;f=this._watchWithNodeFs(e,(m,g)=>{g&&g.mtimeMs===0||this._handleRead(m,!1,a,i,e,r,l)})}return f}async _addToNodeFs(e,t,n,r,i){let a=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return a(),!1;let o=this.fsw._getWatchHelpers(e);n&&(o.filterPath=c=>n.filterPath(c),o.filterDir=c=>n.filterDir(c));try{let c=await Lt[o.statMethod](o.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(o.watchPath,c))return a(),!1;let d=this.fsw.options.followSymlinks,l;if(c.isDirectory()){let f=y.resolve(e),h=d?await X(e):e;if(this.fsw.closed||(l=await this._handleDir(o.watchPath,c,t,r,i,o,h),this.fsw.closed))return;f!==h&&h!==void 0&&this.fsw._symlinkPaths.set(f,h)}else if(c.isSymbolicLink()){let f=d?await X(e):e;if(this.fsw.closed)return;let h=y.dirname(o.watchPath);if(this.fsw._getWatchedDir(h).add(o.watchPath),this.fsw._emit(P.ADD,o.watchPath,c),l=await this._handleDir(h,c,t,r,e,o,f),this.fsw.closed)return;f!==void 0&&this.fsw._symlinkPaths.set(y.resolve(e),f)}else l=this._handleFile(o.watchPath,c,t);return a(),l&&this.fsw._addPathCloser(e,l),!1}catch(c){if(this.fsw._handleError(c))return a(),e}}};var te="/",Gt="//",Ue=".",Vt="..",Xt="string",Jt=/\\/g,Ne=/\/\//,Qt=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,Zt=/^\.[/\\]/;function $(s){return Array.isArray(s)?s:[s]}var se=s=>typeof s=="object"&&s!==null&&!(s instanceof RegExp);function es(s){return typeof s=="function"?s:typeof s=="string"?e=>s===e:s instanceof RegExp?e=>s.test(e):typeof s=="object"&&s!==null?e=>{if(s.path===e)return!0;if(s.recursive){let t=p.relative(s.path,e);return t?!t.startsWith("..")&&!p.isAbsolute(t):!1}return!1}:()=>!1}function ts(s){if(typeof s!="string")throw new Error("string expected");s=p.normalize(s),s=s.replace(/\\/g,"/");let e=!1;s.startsWith("//")&&(e=!0);let t=/\/\//;for(;s.match(t);)s=s.replace(t,"/");return e&&(s="/"+s),s}function Ae(s,e,t){let n=ts(e);for(let r=0;r<s.length;r++){let i=s[r];if(i(n,t))return!0}return!1}function ss(s,e){if(s==null)throw new TypeError("anymatch: specify first argument");let n=$(s).map(r=>es(r));return e==null?(r,i)=>Ae(n,r,i):Ae(n,e)}var ve=s=>{let e=$(s).flat();if(!e.every(t=>typeof t===Xt))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(Oe)},De=s=>{let e=s.replace(Jt,te),t=!1;for(e.startsWith(Gt)&&(t=!0);e.match(Ne);)e=e.replace(Ne,te);return t&&(e=te+e),e},Oe=s=>De(p.normalize(De(s))),Fe=(s="")=>e=>typeof e=="string"?Oe(p.isAbsolute(e)?e:p.join(s,e)):e,ns=(s,e)=>p.isAbsolute(s)?s:p.join(e,s),rs=Object.freeze(new Set),ne=class{constructor(e,t){this.path=e,this._removeWatcher=t,this.items=new Set}add(e){let{items:t}=this;t&&e!==Ue&&e!==Vt&&t.add(e)}async remove(e){let{items:t}=this;if(!t||(t.delete(e),t.size>0))return;let n=this.path;try{await Kt(n)}catch{this._removeWatcher&&this._removeWatcher(p.dirname(n),p.basename(n))}}has(e){let{items:t}=this;if(t)return t.has(e)}getChildren(){let{items:e}=this;return e?[...e.values()]:[]}dispose(){this.items.clear(),this.path="",this._removeWatcher=B,this.items=rs,Object.freeze(this)}},is="stat",os="lstat",re=class{constructor(e,t,n){this.fsw=n;let r=e;this.path=e=e.replace(Zt,""),this.watchPath=r,this.fullWatchPath=p.resolve(r),this.dirParts=[],this.dirParts.forEach(i=>{i.length>1&&i.pop()}),this.followSymlinks=t,this.statMethod=t?is:os}entryPath(e){return p.join(this.watchPath,p.relative(this.watchPath,e.fullPath))}filterPath(e){let{stats:t}=e;if(t&&t.isSymbolicLink())return this.filterDir(e);let n=this.entryPath(e);return this.fsw._isntIgnored(n,t)&&this.fsw._hasReadPermissions(t)}filterDir(e){return this.fsw._isntIgnored(this.entryPath(e),e.stats)}},ie=class extends qt{constructor(e={}){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 t=e.awaitWriteFinish,n={stabilityThreshold:2e3,pollInterval:100},r={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...e,ignored:e.ignored?$(e.ignored):$([]),awaitWriteFinish:t===!0?n:typeof t=="object"?{...n,...t}:!1};be&&(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=B,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(e){if(se(e)){for(let t of this._ignoredPaths)if(se(t)&&t.path===e.path&&t.recursive===e.recursive)return}this._ignoredPaths.add(e)}_removeIgnoredPath(e){if(this._ignoredPaths.delete(e),typeof e=="string")for(let t of this._ignoredPaths)se(t)&&t.path===e&&this._ignoredPaths.delete(t)}add(e,t,n){let{cwd:r}=this.options;this.closed=!1,this._closePromise=void 0;let i=ve(e);return r&&(i=i.map(a=>ns(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,t);return o&&this._emitReady(),o})).then(a=>{this.closed||a.forEach(o=>{o&&this.add(p.dirname(o),p.basename(t||o))})}),this}unwatch(e){if(this.closed)return this;let t=ve(e),{cwd:n}=this.options;return t.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 e=[];return this._closers.forEach(t=>t.forEach(n=>{let r=n();r instanceof Promise&&e.push(r)})),this._streams.forEach(t=>t.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(t=>t.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=e.length?Promise.all(e).then(()=>{}):Promise.resolve(),this._closePromise}getWatched(){let e={};return this._watched.forEach((t,n)=>{let i=(this.options.cwd?p.relative(this.options.cwd,n):n)||Ue;e[i]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(e,...t),e!==_.ERROR&&this.emit(_.ALL,e,...t)}async _emit(e,t,n){if(this.closed)return;let r=this.options;ee&&(t=p.normalize(t)),r.cwd&&(t=p.relative(r.cwd,t));let i=[t];n!=null&&i.push(n);let a=r.awaitWriteFinish,o;if(a&&(o=this._pendingWrites.get(t)))return o.lastChange=new Date,this;if(r.atomic){if(e===_.UNLINK)return this._pendingUnlinks.set(t,[e,...i]),setTimeout(()=>{this._pendingUnlinks.forEach((c,d)=>{this.emit(...c),this.emit(_.ALL,...c),this._pendingUnlinks.delete(d)})},typeof r.atomic=="number"?r.atomic:100),this;e===_.ADD&&this._pendingUnlinks.has(t)&&(e=_.CHANGE,this._pendingUnlinks.delete(t))}if(a&&(e===_.ADD||e===_.CHANGE)&&this._readyEmitted){let c=(d,l)=>{d?(e=_.ERROR,i[0]=d,this.emitWithAll(e,i)):l&&(i.length>1?i[1]=l:i.push(l),this.emitWithAll(e,i))};return this._awaitWriteFinish(t,a.stabilityThreshold,e,c),this}if(e===_.CHANGE&&!this._throttle(_.CHANGE,t,50))return this;if(r.alwaysStat&&n===void 0&&(e===_.ADD||e===_.ADD_DIR||e===_.CHANGE)){let c=r.cwd?p.join(r.cwd,t):t,d;try{d=await zt(c)}catch{}if(!d||this.closed)return;i.push(d)}return this.emitWithAll(e,i),this}_handleError(e){let t=e&&e.code;return e&&t!=="ENOENT"&&t!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||t!=="EPERM"&&t!=="EACCES")&&this.emit(_.ERROR,e),e||this.closed}_throttle(e,t,n){this._throttled.has(e)||this._throttled.set(e,new Map);let r=this._throttled.get(e);if(!r)throw new Error("invalid throttle");let i=r.get(t);if(i)return i.count++,!1;let a,o=()=>{let d=r.get(t),l=d?d.count:0;return r.delete(t),clearTimeout(a),d&&clearTimeout(d.timeoutObject),l};a=setTimeout(o,n);let c={timeoutObject:a,clear:o,count:0};return r.set(t,c),c}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,t,n,r){let i=this.options.awaitWriteFinish;if(typeof i!="object")return;let a=i.pollInterval,o,c=e;this.options.cwd&&!p.isAbsolute(e)&&(c=p.join(this.options.cwd,e));let d=new Date,l=this._pendingWrites;function f(h){Yt(c,(m,g)=>{if(m||!l.has(e)){m&&m.code!=="ENOENT"&&r(m);return}let I=Number(new Date);h&&g.size!==h.size&&(l.get(e).lastChange=I);let at=l.get(e);I-at.lastChange>=t?(l.delete(e),r(void 0,g)):o=setTimeout(f,a,g)})}l.has(e)||(l.set(e,{lastChange:d,cancelWait:()=>(l.delete(e),clearTimeout(o),n)}),o=setTimeout(f,a))}_isIgnored(e,t){if(this.options.atomic&&Qt.test(e))return!0;if(!this._userIgnored){let{cwd:n}=this.options,i=(this.options.ignored||[]).map(Fe(n)),o=[...[...this._ignoredPaths].map(Fe(n)),...i];this._userIgnored=ss(o,void 0)}return this._userIgnored(e,t)}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e){return new re(e,this.options.followSymlinks,this)}_getWatchedDir(e){let t=p.resolve(e);return this._watched.has(t)||this._watched.set(t,new ne(t,this._boundRemove)),this._watched.get(t)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,t,n){let r=p.join(e,t),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(e,t,!0),this._getWatchedDir(r).getChildren().forEach(h=>this._remove(r,h));let c=this._getWatchedDir(e),d=c.has(t);c.remove(t),this._symlinkPaths.has(i)&&this._symlinkPaths.delete(i);let l=r;if(this.options.cwd&&(l=p.relative(this.options.cwd,r)),this.options.awaitWriteFinish&&this._pendingWrites.has(l)&&this._pendingWrites.get(l).cancelWait()===_.ADD)return;this._watched.delete(r),this._watched.delete(i);let f=n?_.UNLINK_DIR:_.UNLINK;d&&!this._isIgnored(r)&&this._emit(f,r),this._closePath(r)}_closePath(e){this._closeFile(e);let t=p.dirname(e);this._getWatchedDir(t).remove(p.basename(e))}_closeFile(e){let t=this._closers.get(e);t&&(t.forEach(n=>n()),this._closers.delete(e))}_addPathCloser(e,t){if(!t)return;let n=this._closers.get(e);n||(n=[],this._closers.set(e,n)),n.push(t)}_readdirp(e,t){if(this.closed)return;let n={type:_.ALL,alwaysStat:!0,lstat:!0,...t,depth:0},r=Pe(e,n);return this._streams.add(r),r.once(Ce,()=>{r=void 0}),r.once(Z,()=>{r&&(this._streams.delete(r),r=void 0)}),r}};function Le(s,e={}){let t=new ie(e);return t.add(s),t}import{build as cs}from"esbuild";import{jwtDecode as ls}from"jwt-decode";import{fork as ds}from"node:child_process";import{existsSync as We,promises as fs}from"node:fs";import{basename as ae,dirname as Y,join as le,relative as Be}from"node:path";import{fileURLToPath as us}from"node:url";import{Issuer as hs,custom as ps}from"openid-client";import{Logger as ms}from"@5minds/processcube_engine_sdk";import{EngineClient as as}from"@5minds/processcube_engine_client";var oe=process.env.PROCESSCUBE_ENGINE_URL??"http://localhost:10560",u=new as(oe);var ys={token:"ZHVtbXlfdG9rZW4=",userId:"dummy_token"},ws=.85,j=["external_task.ts","external_task.js"],D=process.env.PROCESSCUBE_AUTHORITY_URL!==void 0,E=new ms("processcube_app_sdk:external_task_adapter"),S={},de={},x,fe=!1,He=6,_s=3e5,gs=3e4,ce=10,Es=3e4,Me=10,Is=6e4;async function $e(s){if(s&&!We(s))throw new Error(`Invalid customExternalTasksDirPath. The given path '${s}' does not exist`);ps.setHttpOptionsDefaults({timeout:1e5});let e=await ze();x=he(e),await Ke(e);let t=ks(s);Le(t).on("add",async n=>{if(j.includes(ae(n)))return ue(n,t)}).on("change",async n=>{if(j.includes(ae(n)))return Ts(n,t)}).on("unlink",async n=>{j.includes(ae(n))&&je(n)}).on("error",n=>E.error(`Watcher error: ${n}`))}async function ue(s,e){let t=Y(s);if((await fs.readdir(t)).filter(f=>j.includes(f)).length>1){E.error(`Multiple external task files found in directory ${t}. Stopping all external task workers for this directory.`),S[t]&&je(s);return}let i=await qe(s),a=Be(e,t),o=Ge(a),c=typeof __dirname<"u"?__dirname:Y(us(import.meta.url)),d=le(c,"lib/ExternalTaskWorkerProcess.cjs"),l=ds(d,{stdio:["pipe","inherit","inherit","ipc"],env:{...process.env,PROCESSCUBE_ENGINE_URL:oe}});S[t]=l,l.once("disconnect",()=>{delete S[t]}),l.on("error",f=>{E.error(`External Task Worker process error for ${o}`,{error:f,topic:o,workerDirectory:t})}),l.on("exit",(f,h)=>{if(E.info(`External Task Worker process exited for ${o}`,{code:f,signal:h,topic:o,workerDirectory:t}),delete S[t],f===3||f===4)if(Rs(t)){let m=de[t]?.count??1,g=Math.min(1e3*Math.pow(2,m-1),gs);E.info(`Scheduling restart for ${o} in ${g}ms (attempt ${m}/${He})`,{delay:g,restartCount:m,exitCode:f,topic:o,workerDirectory:t}),setTimeout(async()=>{try{if(D&&!fe){E.info("Token refresh cycle is not active, restarting it before worker restart");let I=await ze();x=he(I),await Ke(I)}await ue(s,e)}catch(I){E.error(`Failed to restart External Task Worker process for ${o}`,{error:I,topic:o,workerDirectory:t})}},g)}else E.error(`External Task Worker process for ${o} reached maximum restart attempts`,{exitCode:f,topic:o,workerDirectory:t})}),l.send({action:"create",payload:{topic:o,identity:x,moduleString:i,workerPath:s}})}async function Ts(s,e){let t=Y(s),n=S[t];if(!n)return ue(s,e);let r=await qe(s),i=Be(e,t),a=Ge(i);n.send({action:"restart",payload:{topic:a,identity:x,moduleString:r,workerPath:s}})}function je(s){let e=Y(s),t=S[e];t&&t.kill()}async function Ye(){if(!D)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 hs.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 ze(){if(!D)return null;for(let s=1;s<=ce;s++)try{return await Ye()}catch(e){let t=Math.min(1e3*Math.pow(2,s-1),Es);if(E.error(`Failed to fetch initial token set (attempt ${s}/${ce}), retrying in ${t}ms`,{error:e,attempt:s,delay:t}),s===ce)throw e;await new Promise(n=>setTimeout(n,t))}return null}function he(s){if(!D||s===null)return ys;let e=s.access_token,t=ls(e);return{token:s.access_token,userId:t.sub}}async function Ke(s){if(!D||s===null||fe)return;fe=!0;let e=0,n=await Ps(s)*ws*1e3,r=async()=>{try{let i=await Ye();x=he(i);for(let[a,o]of Object.entries(S))try{o.send({action:"updateIdentity",payload:{identity:x}})}catch(c){E.warn(`Failed to send identity update to worker process ${a}`,{sendError:c})}e=0,setTimeout(r,n)}catch(i){e++;let a=Math.min(1e3*Math.pow(2,e-1),Is);e<=Me?E.error(`Could not refresh identity (attempt ${e}/${Me}), retrying in ${a}ms`,{error:i,attempt:e,delay:a}):E.error(`Could not refresh identity (attempt ${e}), continuing to retry every ${a}ms`,{error:i,attempt:e,delay:a}),setTimeout(r,a)}};setTimeout(r,n)}async function qe(s){let e=await cs({entryPoints:[s],write:!1,bundle:!0,platform:"node",target:"node18",format:"cjs",external:["@opentelemetry/api"]});if(e.errors.length>0)throw E.error(`Could not transpile file at '${s}'`,{errors:e.errors}),new Error(`Could not transpile file at '${s}'`);return e.warnings.length>0&&E.warn(`Transpiled file at '${s}' with warnings`,{warnings:e.warnings}),e.outputFiles[0].text}async function Ps(s){let e=s.expires_in;if(!e&&s.expires_at&&(e=Math.floor(s.expires_at-Date.now()/1e3)),e===void 0)throw new Error("Could not determine the time until the access token for external task workers expires");return e}function Ge(s){return s.replace(/^\.\/+|\([^)]+\)|^\/*|\/*$/g,"").replace(/[\/]{2,}/g,"/")}function ks(s){let e,t=[s,le(process.cwd(),"app"),le(process.cwd(),"src","app")];for(let n of t)if(n&&We(n)){e=n;break}if(!e)throw new Error("Could not find external tasks directory");return e}function Rs(s){let e=Date.now(),t=de[s];return!t||e-t.timestamp>_s?(de[s]={count:1,timestamp:e},!0):t.count>=He?!1:(t.count++,!0)}function Tn(){return u}import{getToken as Ve}from"next-auth/jwt";import{ResponseCookies as Ss}from"next/dist/compiled/@edge-runtime/cookies/index.js";import{cookies as z,headers as Xe}from"next/headers.js";async function w(){let s=await Ve({req:{cookies:await z(),headers:await Xe()}});if(s?.expiresAt&&Date.now()>=s.expiresAt*1e3){let t=await fetch(`${process.env.NEXTAUTH_URL}/api/auth/session`,{method:"GET",headers:{"Content-Type":"application/json",cookie:(await z()).toString()}}),n=new Ss(t.headers);if(n.getAll().length){let r=!1;try{for(let i of n.getAll())(await z()).set(i.name,i.value,{...i})}catch{r=!0}if(s=await Ve({req:{cookies:r?n:await z(),headers:await Xe()}}),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 F}from"@5minds/processcube_engine_client";async function U(){try{return w()}catch{return}}async function Je(s){let e=await U();return(await u.processInstances.query({processInstanceId:s},{identity:e,includeXml:!0})).processInstances[0]}async function Qe(s,e={sortSettings:{sortBy:F.FlowNodeInstances.FlowNodeInstanceSortableColumns.createdAt,sortDir:"ASC"}}){return(await u.flowNodeInstances.query({processInstanceId:s},{...e,identity:e.identity??await U()})).flowNodeInstances}async function Ze(s){let e=await U();return(await u.flowNodeInstances.query({triggeredByFlowNodeInstance:s},{identity:e})).flowNodeInstances}async function et(s,e,t){let n=await U();await u.processInstances.retryProcessInstance(s,{flowNodeInstanceId:e,newStartToken:t,identity:n})}async function tt(s){let e=await U();await u.processInstances.terminateProcessInstance(s,e)}async function An(s={options:{identity:!0}}){switch(s.options.identity){case!0:s.options.identity=await w();break;case!1:delete s.options.identity;break;case void 0:s.options.identity=await w();break}return await u.processInstances.query({...s?.query,state:F.ProcessInstances.ProcessInstanceState.running},s?.options)}async function vn(s={},e=!0){let{processInstanceId:t}=s,n=typeof e=="boolean"?e==!0?await w():void 0:e;return new Promise(async(r,i)=>{let a=[],o=async c=>{if(t!==void 0&&c.processInstanceId!==t)return;let l=await u.processInstances.query({processInstanceId:c.processInstanceId},{identity:n});for(let f of a)u.notification.removeSubscription(f,n);return l.totalCount===0?i(new Error(`Process with instance ID "${c.processInstanceId}" does not exist.`)):r(l.processInstances[0])};if(a.push(await u.notification.onProcessEnded(o,{identity:n})),a.push(await u.notification.onProcessError(o,{identity:n})),a.push(await u.notification.onProcessTerminated(o,{identity:n})),t){let c=await u.processInstances.query({processInstanceId:t,state:[F.ProcessInstances.ProcessInstanceState.finished,F.ProcessInstances.ProcessInstanceState.terminated,F.ProcessInstances.ProcessInstanceState.error]},{identity:n});if(c.totalCount>0){for(let d of a)u.notification.removeSubscription(d,n);r(c.processInstances[0])}}})}import{DataModels as k}from"@5minds/processcube_engine_client";import{mapUserTask as st,mapUserTaskList as C}from"../common/index.mjs";async function Bn(s={},e=!0){let{correlationId:t,processInstanceId:n,flowNodeId:r}=s,i=typeof e=="boolean"?e==!0?await w():void 0:e;return new Promise(async(a,o)=>{let c=await u.userTasks.onUserTaskWaiting(async l=>{let f=t!==void 0&&l.correlationId!==t,h=l.flowNodeInstanceId===void 0,m=n!==void 0&&l.processInstanceId!==n,g=r!==void 0&&l.flowNodeId!==r;if(f||h||m||g)return;let I=await bs(l.flowNodeInstanceId,{identity:i});return u.notification.removeSubscription(c,i),I===null?o(new Error(`UserTask with instance ID "${l.flowNodeInstanceId}" does not exist.`)):a(I)},{identity:i}),d=await Cs({correlationId:t,processInstanceId:n,flowNodeId:r,state:k.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:i});d.userTasks.length>0&&(u.notification.removeSubscription(c,i),a(d.userTasks[0]))})}async function Hn(s,e={},t={},n=!0){let r=typeof n=="boolean"?n==!0?await w():void 0:n;await u.userTasks.finishUserTask(s,t,r);let i={state:k.FlowNodeInstances.FlowNodeInstanceState.suspended,...e},a=await u.userTasks.query(i,{identity:r});return st(a.userTasks[0])}async function Cs(s,e={identity:!0}){switch(e?.identity){case!0:e.identity=await w();break;case!1:delete e.identity;break;case void 0:e.identity=await w();break}let t=await u.userTasks.query(s,e);return C(t)}async function $n(s={identity:!0}){switch(s?.identity){case!0:s.identity=await w();break;case!1:delete s.identity;break;case void 0:s.identity=await w();break}let e=await u.userTasks.query({state:k.FlowNodeInstances.FlowNodeInstanceState.suspended},s);return C(e)}async function jn(s,e={identity:!0}){switch(e?.identity){case!0:e.identity=await w();break;case!1:delete e.identity;break;case void 0:e.identity=await w();break}let t=await u.userTasks.query({processInstanceId:s,state:k.FlowNodeInstances.FlowNodeInstanceState.suspended},e);return C(t)}async function Yn(s,e={identity:!0}){switch(e?.identity){case!0:e.identity=await w();break;case!1:delete e.identity;break;case void 0:e.identity=await w();break}let t=await u.userTasks.query({flowNodeId:s,state:k.FlowNodeInstances.FlowNodeInstanceState.suspended},e);return C(t)}async function bs(s,e={identity:!0}){switch(e?.identity){case!0:e.identity=await w();break;case!1:delete e.identity;break;case void 0:e.identity=await w();break}let t=await u.userTasks.query({flowNodeInstanceId:s,state:k.FlowNodeInstances.FlowNodeInstanceState.suspended},{...e,limit:1});return t.userTasks.length===0?null:st(t.userTasks[0])}async function zn(s,e={identity:!0}){switch(e?.identity){case!0:e.identity=await w();break;case!1:delete e.identity;break;case void 0:e.identity=await w();break}let t=await u.userTasks.query({correlationId:s,state:k.FlowNodeInstances.FlowNodeInstanceState.suspended},e);return C(t)}async function Kn(s,e){let t=s||await w(),n=await u.userTasks.query({state:k.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:t,...e}),r=n.userTasks.filter(i=>i.actualOwnerId===t.userId);return n.userTasks=r,C(n)}async function qn(s,e,t){await u.userTasks.reserveUserTaskInstance(s,e,t||s.userId)}async function Gn(s,e){await u.userTasks.cancelUserTaskInstanceReservation(s,e)}async function Vn(s,e){let t=s||await w(),n=await u.userTasks.query({state:k.FlowNodeInstances.FlowNodeInstanceState.suspended},{identity:t,...e}),r=n.userTasks.filter(i=>i.assignedUserIds?.includes(t.userId));return n.userTasks=r,C(n)}import{PHASE_DEVELOPMENT_SERVER as xs,PHASE_PRODUCTION_BUILD as Ns,PHASE_PRODUCTION_SERVER as As}from"next/dist/shared/lib/constants.js";var nt=!1,pe=!1;function Zn(s={}){let{applicationSdk:e,...t}=s;return async(n,r)=>{pe=pe||n===Ns;let i=n===xs||n===As;return e?.useExternalTasks&&i&&!nt&&!pe&&(nt=!0,await $e(e?.customExternalTasksDirPath)),{...t,serverExternalPackages:[...t.serverExternalPackages||[],"esbuild"]}}}import{redirect as vs}from"next/navigation.js";function nr(s){vs(s)}async function or(...s){return await u.processModels.startProcessInstance(...s)}async function rt(...s){await u.manualTasks.finishManualTask(...s)}async function it(...s){await u.userTasks.finishUserTask(...s)}async function ot(...s){await u.untypedTasks.finishTask(...s)}import{DataModels as Ds}from"@5minds/processcube_engine_client";async function Fs(){try{return w()}catch{return}}var _r=async(s,e)=>{let t=await Fs();e==="bpmn:UserTask"?await it(s,{},t):e==="bpmn:ManualTask"?await rt(s,t):e==="bpmn:Task"?await ot(s,t):console.error(`[@5minds/processcube_app_sdk:handlePlay] Unsupported flow node type: ${e}`)},gr=async s=>{await tt(s)},Er=async(s,e,t)=>{await et(s,e,t)},Ir=async s=>Je(s),Tr=async s=>Qe(s,{sortSettings:{sortBy:Ds.FlowNodeInstances.FlowNodeInstanceSortableColumns.createdAt,sortDir:"DESC"}}),Pr=async s=>Ze(s);export{ye as AuthorityClient,Gn as cancelReservedUserTask,rt as finishManualTask,_r as finishTask,ot as finishUntypedTask,it as finishUserTask,Hn as finishUserTaskAndGetNext,An as getActiveProcessInstances,Vn as getAssignedUserTasksByIdentity,Tn as getEngineClient,Tr as getFlowNodeInstances,Qe as getFlowNodeInstancesByProcessInstanceId,Ze as getFlowNodeInstancesTriggeredByFlowNodeInstanceIds,w as getIdentity,Ir as getProcessInstance,Je as getProcessInstanceById,Kn as getReservedUserTasksByIdentity,q as getServerAccessToken,Ms as getServerIdentity,Pr as getTriggeredFlowNodeInstances,Cs as getUserTasks,bs as getWaitingUserTaskByFlowNodeInstanceId,$n as getWaitingUserTasks,zn as getWaitingUserTasksByCorrelationId,Yn as getWaitingUserTasksByFlowNodeId,jn as getWaitingUserTasksByProcessInstanceId,nr as navigateToUrl,qn as reserveUserTask,Er as retryProcess,et as retryProcessInstance,or as startProcess,gr as terminateProcess,tt as terminateProcessInstance,vn as waitForProcessEnd,Bn as waitForUserTask,Zn 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.5.0",
3
+ "version": "8.6.1",
4
4
  "description": "The SDK for ProcessCube Apps",
5
5
  "type": "module",
6
6
  "main": "build/common/index.cjs",
@@ -26,6 +26,7 @@
26
26
  "require": "./build/client/index.cjs",
27
27
  "default": "./build/client/index.mjs"
28
28
  },
29
+ "./client/styles": "./build/client/root.css",
29
30
  "./client/components/*.css": {
30
31
  "import": "./build/client/components/*.css",
31
32
  "require": "./build/client/components/*.css",
@@ -1 +0,0 @@
1
- .heatmap-flow-shadow{filter:drop-shadow(0 0 10px rgb(128,171,188)) drop-shadow(0 0 10px rgb(128,171,188)) drop-shadow(0 0 10px rgb(128,171,188))}.heatmap-critical{filter:drop-shadow(0 0 2px rgb(255,0,0)) drop-shadow(0 0 4px rgb(255,0,0)) drop-shadow(0 0 6px rgb(255,0,0)) drop-shadow(0 0 14px rgb(255,0,0))}.heatmap-warning{filter:drop-shadow(0 0 2px rgb(255,220,0)) drop-shadow(0 0 4px rgb(255,220,0)) drop-shadow(0 0 6px rgb(255,220,0)) drop-shadow(0 0 10px rgb(255,220,0))}.heatmap-stable{filter:drop-shadow(0 0 4px rgb(50,205,50)) drop-shadow(0 0 6px rgb(50,205,50))}.flow-node-running-state-overlay{background-color:#54c8ff80;opacity:.4;pointer-events:none;border-radius:10px}.flow-node-suspended-state-overlay{background-color:#2185d080;opacity:.4;pointer-events:none;border-radius:10px}.flow-node-finished-state-overlay{background-color:#18b91880;opacity:.4;pointer-events:none;border-radius:10px}.flow-node-terminated-state-overlay{background-color:#e66e0080;opacity:.4;pointer-events:none;border-radius:10px}.flow-node-error-state-overlay{background-color:#ff010180;opacity:.4;pointer-events:none;border-radius:10px}.flow-node-canceled-state-overlay{background-color:#64647d80;opacity:.4;pointer-events:none;border-radius:10px}.flow-node-unknown-state-overlay{background-color:#e9b3ff80;opacity:.4;pointer-events:none;border-radius:10px}.bpmn-element-overlay-backdrop--gateway{position:absolute;border-radius:0;transform:rotate(45deg) translate(10px)}.bpmn-element-overlay-backdrop--rounded{border-radius:50%}.connection-done .djs-visual>*{stroke:#11ca00!important}.bpmn-element-overlay-backdrop{border-radius:10px;display:flex;align-items:stretch;justify-content:stretch;flex-direction:column}.flownode-overlay{pointer-events:all;display:flex;justify-content:center;z-index:99999;margin-top:7px}.bpmn-element-overlay__below{display:flex;border-radius:.125rem}.bpmn-element-overlay__below-item{display:flex;flex-flow:column;align-items:center;padding:.25rem 0;margin:0 .075rem;min-width:32px;font-size:.75rem;border-radius:.25rem}.bpmn-element-overlay__below-item--execution-count{color:#fff;background-color:#777;font-weight:700}.bpmn-element-overlay__below-item--action{background-color:#607d8b;color:#fff;cursor:pointer;line-height:16px;&:hover .action-icon-hovered,.action-icon{display:unset}&:hover .action-icon,.action-icon-hovered{display:none}}.monaco-editor{border:1px solid black}.flex-row{display:flex;flex-direction:row}.token-area{width:40%}.documentation-area{margin-left:20px;flex:1 1 100%}#markdown-container{max-height:450px;width:100%;overflow-y:auto}