@5minds/processcube_app_sdk
Version:
The SDK for ProcessCube Apps
7 lines (5 loc) • 40 kB
JavaScript
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};
/*! Bundled license information:
chokidar/esm/index.js:
(*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) *)
*/