@kern0x1b/penstock-cli 26.10.5 → 26.10.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (194) hide show
  1. package/dist/{chunk-account-C8EHysMH.js → chunk-account-CMvFjqGw.js} +1 -1
  2. package/dist/{chunk-agentFailure-piRAFLGH.js → chunk-agentFailure-BiU8hJ-k.js} +1 -1
  3. package/dist/{chunk-agentLaunch-C5Uo40vv.js → chunk-agentLaunch-CRWlfuXv.js} +1 -1
  4. package/dist/{chunk-agentServe-4O0syoYQ.js → chunk-agentServe-M3jzEiHj.js} +1 -1
  5. package/dist/{chunk-analyze-Brxlb4U1.js → chunk-analyze-CCZJQpbU.js} +1 -1
  6. package/dist/chunk-analyze-D_2dPr5n.js +1 -0
  7. package/dist/chunk-apply-Dmo_XdOA.js +1 -0
  8. package/dist/{chunk-bot-I4kuhjyv.js → chunk-bot-51CfGKVL.js} +3 -3
  9. package/dist/chunk-codeFactSet-BqEOkvBS.js +1 -0
  10. package/dist/{chunk-codeIndex-CzENd6hG.js → chunk-codeIndex-olvCG85q.js} +1 -1
  11. package/dist/{chunk-codeLinks-D-gzUjYv.js → chunk-codeLinks-DW721PAt.js} +1 -1
  12. package/dist/chunk-codeLinks-S_BEJVPa.js +1 -0
  13. package/dist/{chunk-command-BctoT00W.js → chunk-command-B-7DfFou.js} +1 -1
  14. package/dist/chunk-command-CyUljAAc.js +1 -0
  15. package/dist/{chunk-command-Jl1msVwF.js → chunk-command-D7WS1aRl.js} +1 -1
  16. package/dist/chunk-commands-CMEkVxle.js +1 -0
  17. package/dist/{chunk-compose-BV9Jg348.js → chunk-compose-DCAQQndd.js} +1 -1
  18. package/dist/{chunk-connectors-CVfz5pSg.js → chunk-connectors-DG6IqkGl.js} +1 -1
  19. package/dist/{chunk-connectors-eXPldvkc.js → chunk-connectors-UpMjbdpU.js} +1 -1
  20. package/dist/{chunk-context-DPJmldqg.js → chunk-context-B-5CZFAT.js} +1 -1
  21. package/dist/{chunk-convert-B1sgT9kl.js → chunk-convert-B7srqZpZ.js} +1 -1
  22. package/dist/chunk-deploy-CGLF2dB1.js +1 -0
  23. package/dist/{chunk-deploy-DOXu2-8q.js → chunk-deploy-Clj9f2y-.js} +1 -1
  24. package/dist/chunk-diagram-CIy-F5iz.js +1 -0
  25. package/dist/{chunk-diagram-BaVwLa4h.js → chunk-diagram-DYoeuAJx.js} +1 -1
  26. package/dist/{chunk-diagramDefects-7UG_Iwsr.js → chunk-diagramDefects-DlVCfZci.js} +1 -1
  27. package/dist/{chunk-diagrams-6suPQBVQ.js → chunk-diagrams-wnFsPOKv.js} +1 -1
  28. package/dist/{chunk-diff-D1m_eKvv.js → chunk-diff-BJ2sJwcs.js} +1 -1
  29. package/dist/chunk-diff-BelMuQhT.js +1 -0
  30. package/dist/chunk-dispatch-CescmVW-.js +6 -0
  31. package/dist/{chunk-docs-CwY3Ce9M.js → chunk-docs-DzOiA9zg.js} +4 -4
  32. package/dist/{chunk-doctor-m0mnVdDE.js → chunk-doctor-GDNwRCg3.js} +1 -1
  33. package/dist/{chunk-drawing-shRfnrs9.js → chunk-drawing-C2qewK8L.js} +1 -1
  34. package/dist/{chunk-editPreview-BgH1JVOD.js → chunk-editPreview-DGu4slO6.js} +1 -1
  35. package/dist/chunk-export-CDFdw7Eh.js +1 -0
  36. package/dist/{chunk-export-D5kPD4Or.js → chunk-export-DP1Hab-_.js} +1 -1
  37. package/dist/{chunk-facts-DA3Y-k9a.js → chunk-facts-CfA8qH5b.js} +1 -1
  38. package/dist/{chunk-failure-BsimkHy_.js → chunk-failure-BK7fu4Yo.js} +1 -1
  39. package/dist/{chunk-features-BfRg2kR5.js → chunk-features-CiC2Yoej.js} +1 -1
  40. package/dist/chunk-features-Dq1Gvqp3.js +1 -0
  41. package/dist/chunk-folders-BO8qUHUV.js +1 -0
  42. package/dist/{chunk-folders-13vx0i0n.js → chunk-folders-yTMgOqLo.js} +1 -1
  43. package/dist/chunk-formChecks-BOiD8Idv.js +1 -0
  44. package/dist/chunk-help-DKtpVSxI.js +85 -0
  45. package/dist/chunk-importCommand-_CnKIoNk.js +1 -0
  46. package/dist/{chunk-init-AIh_7yE0.js → chunk-init-3zEab7KI.js} +3 -3
  47. package/dist/chunk-license-Cvnp1Aee.js +1 -0
  48. package/dist/{chunk-license-x3oHbKe2.js → chunk-license-DU4P8P8A.js} +1 -1
  49. package/dist/{chunk-lint-C_fAcLIg.js → chunk-lint-Df2davEY.js} +1 -1
  50. package/dist/{chunk-load-BVJUBU5S.js → chunk-load-CRmIvn7e.js} +1 -1
  51. package/dist/chunk-main-BY7JEoe1.js +1 -0
  52. package/dist/chunk-mcp-DKX2xT8d.js +77 -0
  53. package/dist/{chunk-mcpLaunch-C13ViiIP.js → chunk-mcpLaunch-DpDE0hW-.js} +1 -1
  54. package/dist/chunk-migrate-BaNzQNyD.js +2 -0
  55. package/dist/chunk-migrate-DcxIkacG.js +1 -0
  56. package/dist/{chunk-penstockCli-CqiOKC75.js → chunk-penstockCli-B0_wWDGy.js} +1 -1
  57. package/dist/chunk-plural-Di3FH8HP.js +1 -0
  58. package/dist/{chunk-pr-tC3-PSNM.js → chunk-pr-DXs1coaS.js} +1 -1
  59. package/dist/{chunk-project-qT-Fk_Rz.js → chunk-project-BS-4dy5o.js} +1 -1
  60. package/dist/{chunk-report-CDz78nCI.js → chunk-report-CtkTRSGT.js} +1 -1
  61. package/dist/{chunk-review-BqZSohXR.js → chunk-review-WIpFGKkc.js} +1 -1
  62. package/dist/{chunk-rules-DJlL7K_Q.js → chunk-rules-CoJAmvwu.js} +1 -1
  63. package/dist/{chunk-security-5SU-bq3A.js → chunk-security-BKVRwb6V.js} +10 -10
  64. package/dist/{chunk-share-YSewfw3F.js → chunk-share-B3W30sbt.js} +3 -3
  65. package/dist/chunk-src-CxTpK8wk.js +890 -0
  66. package/dist/{chunk-stages-C-nhLoBW.js → chunk-stages-Gm5BZUp5.js} +1 -1
  67. package/dist/chunk-status-X9Ny-Nu8.js +1 -0
  68. package/dist/{chunk-systemError-B-1nL94i.js → chunk-systemError-F6bMRwXU.js} +1 -1
  69. package/dist/chunk-systemError-cGwrYkmo.js +1 -0
  70. package/dist/{chunk-table-CJtiXv0e.js → chunk-table-B2WTbpMl.js} +1 -1
  71. package/dist/chunk-taskTest-B3gfOti1.js +1 -0
  72. package/dist/{chunk-taskTest-4rIxp0rL.js → chunk-taskTest-D-WDCLD5.js} +2 -2
  73. package/dist/{chunk-templates-Bxe3J0qy.js → chunk-templates-BdsiNRJ3.js} +1 -1
  74. package/dist/chunk-testCases-ba8k3BJD.js +4 -0
  75. package/dist/chunk-testCases-gXzkCxF5.js +1 -0
  76. package/dist/chunk-tests-BLBZ1eh2.js +1 -0
  77. package/dist/chunk-tests-DxL0JMtB.js +23 -0
  78. package/dist/chunk-translator-BAjzyPKE.js +22 -0
  79. package/dist/{chunk-trust-u1vZ6Yk0.js → chunk-trust-Ci9pDa27.js} +1 -1
  80. package/dist/{chunk-trust-yKw_pXRj.js → chunk-trust-DlJIoKs8.js} +1 -1
  81. package/dist/{chunk-workerVariables-CCLcoR0U.js → chunk-workerVariables-BnLSud8o.js} +1 -1
  82. package/dist/{chunk-wrapper-AJWl6ru-.js → chunk-wrapper-DqqRt0FZ.js} +1 -1
  83. package/dist/chunk-wrapper-E_u1_-Db.js +1 -0
  84. package/dist/locales/de.json +103 -2
  85. package/dist/locales/es.json +103 -2
  86. package/dist/locales/fr.json +103 -2
  87. package/dist/locales/ja.json +103 -2
  88. package/dist/locales/ko.json +103 -2
  89. package/dist/locales/pt-BR.json +103 -2
  90. package/dist/locales/ru.json +103 -2
  91. package/dist/locales/zh.json +103 -2
  92. package/dist/penstock.js +1 -1
  93. package/dist/web/assets/{AgentSettings-C3Er_rlW.js → AgentSettings-4B4hSxBk.js} +1 -1
  94. package/dist/web/assets/{AgentsDialog-Bo7kikb6.js → AgentsDialog-C32ALLtE.js} +1 -1
  95. package/dist/web/assets/{BpmnCanvas-Dw5zgCN3.js → BpmnCanvas-CZOJiq6t.js} +1 -1
  96. package/dist/web/assets/{BpmnDocument-CuU0biX9.js → BpmnDocument-BNLfXWLG.js} +4 -4
  97. package/dist/web/assets/{ConflictDialog-GxZ-d8SK.js → ConflictDialog-mUJYs1zz.js} +1 -1
  98. package/dist/web/assets/{DiffDocument-Bh3hFmmi.js → DiffDocument-C7csJl3x.js} +1 -1
  99. package/dist/web/assets/{DmnDocument-C8HpJAcE.js → DmnDocument-B2dyX49k.js} +1 -1
  100. package/dist/web/assets/{FormDocument-CH-4KB3x.js → FormDocument-ChSqEPE5.js} +1 -1
  101. package/dist/web/assets/{FormStepView-DraPVoAN.js → FormStepView-j4C0Qovo.js} +1 -1
  102. package/dist/web/assets/{GraphAwareLayoutService-C8J8YHJI.js → GraphAwareLayoutService-DD2iXfXi.js} +1 -1
  103. package/dist/web/assets/{NewFileDialog-j09JqpPj.js → NewFileDialog-eeIqqmXc.js} +1 -1
  104. package/dist/web/assets/{QuickOpen-CeBhsCzA.js → QuickOpen-C0I0FRt2.js} +1 -1
  105. package/dist/web/assets/{ScriptPane-DDikZDv6.js → ScriptPane-BAvcgLWX.js} +2 -2
  106. package/dist/web/assets/{ScriptRunDialog-DdzJ0pvT.js → ScriptRunDialog-DLlMiJiK.js} +1 -1
  107. package/dist/web/assets/{SettingsDialog-JUc5zUR9.js → SettingsDialog-C3ts5aiN.js} +1 -1
  108. package/dist/web/assets/{ShortcutsDialog-DECqWPNE.js → ShortcutsDialog-DVV504pS.js} +1 -1
  109. package/dist/web/assets/{SourceDocument-X8ajUcxM.js → SourceDocument-DRgUPazk.js} +1 -1
  110. package/dist/web/assets/{TextDocument-0z7qojAh.js → TextDocument-Bm0sPjft.js} +1 -1
  111. package/dist/web/assets/{UnreadableFileLayer-D3G59F4u.js → UnreadableFileLayer-DbW33CnE.js} +1 -1
  112. package/dist/web/assets/{UploadDialog-CiahYkTc.js → UploadDialog-BSl3zFNn.js} +1 -1
  113. package/dist/web/assets/{apply-HqvoGwLE.js → apply-B3FkgxjU.js} +1 -1
  114. package/dist/web/assets/{bpmnTheme-cOvp4qFc.js → bpmnTheme-C3HdVV1D.js} +1 -1
  115. package/dist/web/assets/bridgeInstance-BZBhe5hF.js +851 -0
  116. package/dist/web/assets/{commands-nPznxvPp.js → commands-DHPxsavW.js} +1 -1
  117. package/dist/web/assets/de-BH_bnU4H.js +1 -0
  118. package/dist/web/assets/{dialog-CtGB1LHI.js → dialog-LcHsiQKJ.js} +1 -1
  119. package/dist/web/assets/{diff-NgYeO98t.js → diff-bpdDl0KE.js} +1 -1
  120. package/dist/web/assets/{documentBridge-QW0IZ9Bq.js → documentBridge-4fZNBdp4.js} +2 -2
  121. package/dist/web/assets/{documents-KeXEdK1U.js → documents-FOVGbYYF.js} +1 -1
  122. package/dist/web/assets/{duplicate-DNPpPVse.js → duplicate-CdCuOnUl.js} +1 -1
  123. package/dist/web/assets/{engines-DU0BfbYM.js → engines-C884tl-T.js} +1 -1
  124. package/dist/web/assets/es-D7v7zkxC.js +1 -0
  125. package/dist/web/assets/{formChecks-sU20kKkU.js → formChecks-Bvuzw2sb.js} +1 -1
  126. package/dist/web/assets/fr-CuzAJTai.js +1 -0
  127. package/dist/web/assets/frontend-Y1MvD_Uo.js +1 -0
  128. package/dist/web/assets/httpHost-CnF86WJB.js +1 -0
  129. package/dist/web/assets/{index.es-BqVUpGyA.js → index.es-0rLw__5_.js} +1 -1
  130. package/dist/web/assets/{index.es-DqkfrvWI.js → index.es-BP1Cc_0e.js} +1 -1
  131. package/dist/web/assets/{intelligence-Ck_Q9upa.js → intelligence-E2EBYhHr.js} +1 -1
  132. package/dist/web/assets/ja-BgElyPpa.js +1 -0
  133. package/dist/web/assets/{jspdf.es.min-CM3S4IDt.js → jspdf.es.min-BSRrqhq_.js} +3 -3
  134. package/dist/web/assets/ko-j1Oi9MKH.js +1 -0
  135. package/dist/web/assets/{lib-DAKOOgix.js → lib-De3fPoUi.js} +1 -1
  136. package/dist/web/assets/{platform-CkWAyNst.js → platform-CjEV0T5t.js} +1 -1
  137. package/dist/web/assets/{preferences-nBrFGN89.js → preferences-CmXdxfFo.js} +1 -1
  138. package/dist/web/assets/pt-BR-CRWG2th4.js +1 -0
  139. package/dist/web/assets/ru-KJyuYSUL.js +1 -0
  140. package/dist/web/assets/{run-B3YvrVeP.js → run-B9EUa035.js} +1 -1
  141. package/dist/web/assets/{samples-BVuIm-bu.js → samples-03zukOEM.js} +1 -1
  142. package/dist/web/assets/{testCaseRuns-DYKnccnc.js → testCaseRuns-BYhJPipg.js} +1 -1
  143. package/dist/web/assets/translator-OIpY8kTG.js +1 -0
  144. package/dist/web/assets/{ui-3pEQJ50t.js → ui-BLMlfdD3.js} +1 -1
  145. package/dist/web/assets/{useTrace-BAXnn0Bt.js → useTrace-Cr28sh4A.js} +1 -1
  146. package/dist/web/assets/{web-B2zkonPE.js → web-Q9VZNxQi.js} +5 -5
  147. package/dist/web/assets/zh-CukDLcVz.js +1 -0
  148. package/dist/web/index.html +19 -19
  149. package/package.json +1 -1
  150. package/dist/chunk-analyze-CUxuBgNS.js +0 -1
  151. package/dist/chunk-apply-BAMwoXG9.js +0 -1
  152. package/dist/chunk-baseline-DvS2S0am.js +0 -1
  153. package/dist/chunk-codeFactSet-DOOlbIIj.js +0 -1
  154. package/dist/chunk-codeLinks-DLxEBWPi.js +0 -1
  155. package/dist/chunk-command-BR4memGJ.js +0 -1
  156. package/dist/chunk-commands-CeRlfHY-.js +0 -1
  157. package/dist/chunk-deploy-C4KJK-tw.js +0 -1
  158. package/dist/chunk-diagram-CCA1-fT5.js +0 -1
  159. package/dist/chunk-diff-BC8gZX5w.js +0 -1
  160. package/dist/chunk-dispatch-CW2CJI0C.js +0 -6
  161. package/dist/chunk-export-9AWsr5ai.js +0 -1
  162. package/dist/chunk-features-BwnwB6jL.js +0 -1
  163. package/dist/chunk-folders-C1Nes4Ap.js +0 -1
  164. package/dist/chunk-formChecks-acRgARZ3.js +0 -1
  165. package/dist/chunk-help-CFhmAhz8.js +0 -85
  166. package/dist/chunk-importCommand-5SJxu2k4.js +0 -1
  167. package/dist/chunk-license-B_To2110.js +0 -1
  168. package/dist/chunk-main-D3S4Xr__.js +0 -1
  169. package/dist/chunk-mcp-ByMCWlXC.js +0 -76
  170. package/dist/chunk-migrate-CLQ-hrae.js +0 -1
  171. package/dist/chunk-migrate-CVUR1K7f.js +0 -1
  172. package/dist/chunk-plural-Bq_4vgOr.js +0 -1
  173. package/dist/chunk-src-BLyg_6UX.js +0 -879
  174. package/dist/chunk-status-DgeSOz3A.js +0 -1
  175. package/dist/chunk-systemError-2me5k57V.js +0 -1
  176. package/dist/chunk-taskTest-rng12v_b.js +0 -1
  177. package/dist/chunk-testCases-CwQ-Mi7L.js +0 -1
  178. package/dist/chunk-testCases-xculyxH_.js +0 -4
  179. package/dist/chunk-tests-C-kNQNpq.js +0 -1
  180. package/dist/chunk-tests-C3XJ9LMT.js +0 -23
  181. package/dist/chunk-translator-BFUJmSkR.js +0 -21
  182. package/dist/chunk-wrapper-Bxz1Lgp5.js +0 -1
  183. package/dist/web/assets/bridgeInstance-DQk-c8L1.js +0 -850
  184. package/dist/web/assets/de-Dj813wjn.js +0 -1
  185. package/dist/web/assets/es-CyJDEw4H.js +0 -1
  186. package/dist/web/assets/fr-B1lqrd3d.js +0 -1
  187. package/dist/web/assets/frontend-caI7mOAL.js +0 -1
  188. package/dist/web/assets/httpHost-Dqit__mm.js +0 -1
  189. package/dist/web/assets/ja-BUAM_DzQ.js +0 -1
  190. package/dist/web/assets/ko-7l4EjTF9.js +0 -1
  191. package/dist/web/assets/pt-BR-CxxRL7kF.js +0 -1
  192. package/dist/web/assets/ru-C4gbkVXL.js +0 -1
  193. package/dist/web/assets/translator-B2N3PQBL.js +0 -1
  194. package/dist/web/assets/zh-DIYPlVjz.js +0 -1
@@ -1,18 +1,18 @@
1
- import{n as e}from"./chunk-version-CdS8_QQd.js";import{t}from"./chunk-atomicWrite-C6J1gDtO.js";import{C as n,S as r,a as i,b as a,d as o,f as s,m as c,n as l,r as u,u as d}from"./chunk-license-x3oHbKe2.js";import{r as f,t as p}from"./chunk-translator-BFUJmSkR.js";import{t as m}from"./chunk-features-BfRg2kR5.js";import{n as ee,r as te,t as h}from"./chunk-preferencesFile-F6bAlNrk.js";import{F as ne,G as re,J as ie,K as ae,L as oe,N as se,O as ce,P as le,S as ue,T as de,U as fe,W as pe,X as me,Y as he,Z as ge,f as _e,i as ve,j as ye,p as g,q as be,t as xe,u as Se,w as Ce,x as we}from"./chunk-mcpLaunch-C13ViiIP.js";import{At as Te,Nt as Ee,Ot as De,Qt as Oe,Rt as ke,Tt as Ae,_n as je,an as Me,cn as Ne,ct as Pe,d as Fe,dt as Ie,en as Le,gt as Re,ht as ze,jt as Be,kt as Ve,lt as He,mt as Ue,nn as We,on as Ge,pt as _,sn as Ke,tn as qe,vn as Je}from"./chunk-src-BLyg_6UX.js";import{o as Ye,r as Xe}from"./chunk-agentFailure-piRAFLGH.js";import{a as Ze}from"./chunk-moddle-Dlk0NR-u.js";import{c as Qe,l as $e,s as et}from"./chunk-engine-CxgdJ2wO.js";import{n as tt,r as nt,t as rt}from"./chunk-workerVariables-CCLcoR0U.js";import{r as it,t as at}from"./chunk-connectors-eXPldvkc.js";import{o as ot}from"./chunk-failure-BsimkHy_.js";import{_ as st,c as ct,f as lt,g as ut,h as dt,i as ft,l as pt,m as mt,o as ht,p as gt}from"./chunk-load-BVJUBU5S.js";import{t as _t}from"./chunk-context-DPJmldqg.js";import{a as vt}from"./chunk-trust-yKw_pXRj.js";import{a as yt,i as bt,o as xt,r as St,s as Ct,t as wt}from"./chunk-codeFactSet-DOOlbIIj.js";import{t as Tt}from"./chunk-codeIndex-CzENd6hG.js";import{n as Et,t as Dt}from"./chunk-penstockCli-CqiOKC75.js";import v from"node:path";import{constants as Ot,homedir as kt}from"node:os";import{accessSync as At,constants as y,createReadStream as jt,existsSync as b,lstatSync as Mt,mkdirSync as Nt,readFileSync as x,readdirSync as Pt,readlinkSync as Ft,realpathSync as S,renameSync as It,rmSync as Lt,statSync as C,watch as Rt,writeFileSync as zt}from"node:fs";import{execFile as Bt,spawn as Vt}from"node:child_process";import{createHash as Ht,randomBytes as Ut,randomUUID as Wt,timingSafeEqual as Gt}from"node:crypto";import{copyFile as Kt,link as qt,lstat as w,mkdir as T,open as Jt,opendir as Yt,readFile as Xt,readdir as E,realpath as Zt,rename as D,rm as O,stat as k,unlink as Qt,writeFile as $t}from"node:fs/promises";import{crc32 as en,createDeflateRaw as tn,deflateRaw as nn}from"node:zlib";import{Document as rn,parseDocument as an}from"yaml";import on from"node:http";import{PROTOCOL_VERSION as sn,RequestError as cn,client as ln,ndJsonStream as un}from"@agentclientprotocol/sdk";import{Readable as dn,Writable as fn}from"node:stream";import{pipeline as pn}from"node:stream/promises";import{promisify as mn}from"node:util";import{isIP as hn}from"node:net";function gn(e){let t=/* @__PURE__ */ new Map,n=e=>{e?.id&&(t.set(e.id,typeof e.name==`string`&&e.name.trim()?e.name.trim():e.id),(e.flowElements??[]).forEach(n))};return(e?.rootElements??[]).filter(e=>e.$type===`bpmn:Process`).forEach(e=>(e.flowElements??[]).forEach(n)),t}function _n(e,t,n){return e.path===null?{label:t.get(e.elementId)??e.elementId,elementId:e.elementId,...n?{diagramPath:n}:{},...e.sample===null?{}:{sample:e.sample}}:{label:`${tt(e.path)}:${e.line??0}`,elementId:e.elementId,path:e.path,...e.line===null?{}:{line:e.line},...e.offset===null?{}:{offset:e.offset}}}function vn(e,t,n,r){return{name:e.name,...e.type===null?{}:{type:e.type},declaredByScript:Je(n,e.name),writers:e.writers.map(e=>_n(e,t,r))}}function yn(e,t,n){let r={variables:[...je(e.definitions).uses,...nt(e.workers)]},i=Ne(e.definitions).flows.get(t)?.target??t,a=De({model:r,order:Ke(e.definitions),types:e.workers?.types??[],inputs:e.inputs},i,{wholeProcess:!0}),o=gn(e.definitions);return a.variables.map(t=>vn(t,o,n,e.diagramPath))}function bn(e){return[...[...e.jobTypes.keys()].map(e=>({kind:`JOB_TYPE`,value:e})),...[...e.topics.keys()].map(e=>({kind:`TOPIC`,value:e})),...[...e.classes.keys()].map(e=>({kind:`CLASS`,value:e})),...[...e.beans.keys()].map(e=>({kind:`BEAN`,value:e}))]}const xn=/^[\w][\w.-]{0,63}$/;function Sn(e,t){return xn.test(t)?v.join(e,`agents`,t,`options.json`):null}function Cn(e,n,r,i=/* @__PURE__ */ new Date){let a=Sn(e,n);if(a!==null&&r.length!==0)try{let e={readAt:i.toISOString(),options:r.map(({legacy:e,...t})=>t)};t(a,`${JSON.stringify(e,null,2)}\n`)}catch{}}function wn(e,t){let n=Sn(e,t);if(n===null)return null;try{let e=JSON.parse(x(n,`utf8`)),t=de(e.options);return typeof e.readAt!=`string`||t.length===0?null:{readAt:e.readAt,options:t}}catch{return null}}var Tn=class extends Error{},En=class extends Error{},Dn=class extends Error{how;tail;constructor(e,t){super(e),this.how=e,this.tail=t}};const On=/* @__PURE__ */ new Set;let kn=!1;function An(){kn||(kn=!0,process.once(`exit`,()=>{for(let e of On)e.pid!==void 0&&Se(e.pid,`SIGKILL`)}))}function A(e,t){return e.catch(()=>void 0),new Promise((n,r)=>{let i=setTimeout(()=>r(new Tn),t);e.then(n,r).finally(()=>clearTimeout(i))})}function jn(e){let t=e.split(`
1
+ import{n as e}from"./chunk-version-CdS8_QQd.js";import{t}from"./chunk-atomicWrite-C6J1gDtO.js";import{C as n,S as r,a as i,b as a,d as o,f as s,m as c,n as l,r as u,u as d}from"./chunk-license-DU4P8P8A.js";import{r as f,t as p}from"./chunk-translator-BAjzyPKE.js";import{t as m}from"./chunk-features-CiC2Yoej.js";import{n as ee,r as te,t as h}from"./chunk-preferencesFile-F6bAlNrk.js";import{F as ne,G as re,J as ie,K as ae,L as oe,N as se,O as ce,P as le,S as ue,T as de,U as fe,W as pe,X as me,Y as he,Z as ge,f as _e,i as ve,j as ye,p as g,q as be,t as xe,u as Se,w as Ce,x as we}from"./chunk-mcpLaunch-DpDE0hW-.js";import{Bt as Te,Ft as Ee,Gt as De,It as Oe,Pt as ke,Rt as Ae,St as je,Tn as Me,_ as Ne,_t as Pe,an as Fe,bt as Ie,cn as Le,fn as Re,hn as ze,ht as Be,jt as Ve,ln as He,mn as Ue,mt as We,pn as Ge,sn as Ke,wn as qe,xt as Je,yt as _}from"./chunk-src-CxTpK8wk.js";import{o as Ye,r as Xe}from"./chunk-agentFailure-BiU8hJ-k.js";import{a as Ze}from"./chunk-moddle-Dlk0NR-u.js";import{c as Qe,l as $e,s as et}from"./chunk-engine-CxgdJ2wO.js";import{n as tt,r as nt,t as rt}from"./chunk-workerVariables-BnLSud8o.js";import{r as it,t as at}from"./chunk-connectors-UpMjbdpU.js";import{o as ot}from"./chunk-failure-BK7fu4Yo.js";import{_ as st,c as ct,f as lt,g as ut,h as dt,i as ft,l as pt,m as mt,o as ht,p as gt}from"./chunk-load-CRmIvn7e.js";import{t as _t}from"./chunk-context-B-5CZFAT.js";import{a as vt}from"./chunk-trust-DlJIoKs8.js";import{a as yt,i as bt,o as xt,r as St,s as Ct,t as wt}from"./chunk-codeFactSet-BqEOkvBS.js";import{t as Tt}from"./chunk-codeIndex-olvCG85q.js";import{n as Et,t as Dt}from"./chunk-penstockCli-B0_wWDGy.js";import v from"node:path";import{constants as Ot,homedir as kt}from"node:os";import{accessSync as At,constants as y,createReadStream as jt,existsSync as b,lstatSync as Mt,mkdirSync as Nt,readFileSync as x,readdirSync as Pt,readlinkSync as Ft,realpathSync as S,renameSync as It,rmSync as Lt,statSync as C,watch as Rt,writeFileSync as zt}from"node:fs";import{execFile as Bt,spawn as Vt}from"node:child_process";import{createHash as Ht,randomBytes as Ut,randomUUID as Wt,timingSafeEqual as Gt}from"node:crypto";import{copyFile as Kt,link as qt,lstat as w,mkdir as T,open as Jt,opendir as Yt,readFile as Xt,readdir as E,realpath as Zt,rename as D,rm as O,stat as k,unlink as Qt,writeFile as $t}from"node:fs/promises";import{crc32 as en,createDeflateRaw as tn,deflateRaw as nn}from"node:zlib";import{Document as rn,parseDocument as an}from"yaml";import on from"node:http";import{PROTOCOL_VERSION as sn,RequestError as cn,client as ln,ndJsonStream as un}from"@agentclientprotocol/sdk";import{Readable as dn,Writable as fn}from"node:stream";import{pipeline as pn}from"node:stream/promises";import{promisify as mn}from"node:util";import{isIP as hn}from"node:net";function gn(e){let t=/* @__PURE__ */ new Map,n=e=>{e?.id&&(t.set(e.id,typeof e.name==`string`&&e.name.trim()?e.name.trim():e.id),(e.flowElements??[]).forEach(n))};return(e?.rootElements??[]).filter(e=>e.$type===`bpmn:Process`).forEach(e=>(e.flowElements??[]).forEach(n)),t}function _n(e,t,n){return e.path===null?{label:t.get(e.elementId)??e.elementId,elementId:e.elementId,...n?{diagramPath:n}:{},...e.sample===null?{}:{sample:e.sample}}:{label:`${tt(e.path)}:${e.line??0}`,elementId:e.elementId,path:e.path,...e.line===null?{}:{line:e.line},...e.offset===null?{}:{offset:e.offset}}}function vn(e,t,n,r){return{name:e.name,...e.type===null?{}:{type:e.type},declaredByScript:Me(n,e.name),writers:e.writers.map(e=>_n(e,t,r))}}function yn(e,t,n){let r={variables:[...qe(e.definitions).uses,...nt(e.workers)]},i=ze(e.definitions).flows.get(t)?.target??t,a=ke({model:r,order:Ue(e.definitions),types:e.workers?.types??[],inputs:e.inputs},i,{wholeProcess:!0}),o=gn(e.definitions);return a.variables.map(t=>vn(t,o,n,e.diagramPath))}function bn(e){return[...[...e.jobTypes.keys()].map(e=>({kind:`JOB_TYPE`,value:e})),...[...e.topics.keys()].map(e=>({kind:`TOPIC`,value:e})),...[...e.classes.keys()].map(e=>({kind:`CLASS`,value:e})),...[...e.beans.keys()].map(e=>({kind:`BEAN`,value:e}))]}const xn=/^[\w][\w.-]{0,63}$/;function Sn(e,t){return xn.test(t)?v.join(e,`agents`,t,`options.json`):null}function Cn(e,n,r,i=/* @__PURE__ */ new Date){let a=Sn(e,n);if(a!==null&&r.length!==0)try{let e={readAt:i.toISOString(),options:r.map(({legacy:e,...t})=>t)};t(a,`${JSON.stringify(e,null,2)}\n`)}catch{}}function wn(e,t){let n=Sn(e,t);if(n===null)return null;try{let e=JSON.parse(x(n,`utf8`)),t=de(e.options);return typeof e.readAt!=`string`||t.length===0?null:{readAt:e.readAt,options:t}}catch{return null}}var Tn=class extends Error{},En=class extends Error{},Dn=class extends Error{how;tail;constructor(e,t){super(e),this.how=e,this.tail=t}};const On=/* @__PURE__ */ new Set;let kn=!1;function An(){kn||(kn=!0,process.once(`exit`,()=>{for(let e of On)e.pid!==void 0&&Se(e.pid,`SIGKILL`)}))}function A(e,t){return e.catch(()=>void 0),new Promise((n,r)=>{let i=setTimeout(()=>r(new Tn),t);e.then(n,r).finally(()=>clearTimeout(i))})}function jn(e){let t=e.split(`
2
2
  `).map(e=>e.trim()).filter(e=>e!==``);return Ye(t[t.length-1]??``)}var Mn=class e{agentId;command;loadSession=!1;signInMethods=[];child;settings;connection;stderr=``;ours=!1;gone=!1;how=``;exitWaiters=[];constructor(e,t,n,r){this.agentId=e,this.child=t,this.settings=n,this.command=r}get pid(){return this.child.pid}get alive(){return!this.gone}get tail(){return jn(this.stderr)}get killedByUs(){return this.ours}get exitCause(){return this.gone?new Dn(this.how,this.tail):null}static async launch(t,n,r){let i=ge(t),a=Vt(i.command,i.args,{cwd:n.folder,env:ce(n.env,t.env),stdio:[`pipe`,`pipe`,`pipe`],windowsHide:!0,windowsVerbatimArguments:i.verbatim,detached:process.platform!==`win32`}),o=new e(t.id,a,n,[t.command,...t.args].join(` `));On.add(a),An();let s=new Promise((e,t)=>{a.once(`spawn`,e),a.once(`error`,t)});a.on(`error`,()=>void 0),a.stderr.on(`data`,e=>{o.stderr=(o.stderr+e.toString(`utf8`)).slice(-4096)}),a.stdin.on(`error`,()=>void 0),a.once(`exit`,(e,t)=>{On.delete(a),o.gone=!0,o.how=e===null?`${t}`:`${e}`;for(let e of o.exitWaiters.splice(0))e();r.gone(o,o.how,o.tail,o.ours)});try{await s}catch(e){throw On.delete(a),o.gone=!0,e}let c=un(fn.toWeb(a.stdin),dn.toWeb(a.stdout));o.connection=ln({name:`penstock`}).onRequest(`session/request_permission`,e=>r.permission(e.params,e.signal)).onRequest(`fs/read_text_file`,e=>r.read(e.params)).onRequest(`fs/write_text_file`,async e=>{await r.write(e.params)}).onNotification(`session/update`,e=>r.update(e.params)).connect(c);let l=()=>o.kill(!1);o.connection.closed.then(l,l);try{let e=await A(o.connection.agent.request(`initialize`,{protocolVersion:sn,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0},terminal:!1},clientInfo:{name:`penstock`,title:`Penstock`,version:n.version??`0`}}),n.connectMs);o.loadSession=e.agentCapabilities?.loadSession===!0,o.signInMethods=(e.authMethods??[]).filter(e=>!(`type`in e&&e.type===`terminal`)).map(e=>e.id)}catch(e){throw o.kill(!1),await o.exited(n.killMs),o.gone&&!o.ours&&o.tail!==``&&!(e instanceof Tn)?new Dn(o.how,o.tail):e}return o}exited(e){return this.gone?Promise.resolve():new Promise(t=>{let n=setTimeout(t,e);n.unref(),this.exitWaiters.push(()=>{clearTimeout(n),t()})})}async newSession(e,t){let n=await A(this.connection.agent.request(`session/new`,{cwd:e,mcpServers:t}),this.settings.connectMs);return{sessionId:n.sessionId,options:Ce(n.configOptions,n.modes)}}async loadSessionById(e,t,n){let r=await A(this.connection.agent.request(`session/load`,{sessionId:e,cwd:t,mcpServers:n}),this.settings.connectMs);return Ce(r.configOptions,r.modes)}async setOption(e,t,n){if(t.legacy)return await A(this.connection.agent.request(`session/set_mode`,{sessionId:e,modeId:n}),this.settings.connectMs),null;let r=await A(this.connection.agent.request(`session/set_config_option`,{sessionId:e,configId:t.id,value:n}),this.settings.connectMs);return Ce(r.configOptions,null)}prompt(e,t){return this.connection.agent.request(`session/prompt`,{sessionId:e,prompt:t}).then(e=>e.stopReason)}async authenticate(e,t){await A(this.connection.agent.request(`authenticate`,{methodId:e}),t)}cancel(e){this.connection.agent.notify(`session/cancel`,{sessionId:e}).catch(()=>void 0)}kill(e){e&&(this.ours=!0);let t=this.child;if(t.exitCode===null&&t.signalCode===null){try{this.connection?.close()}catch{}try{t.stdin?.end()}catch{}t.pid!==void 0&&Se(t.pid,`SIGTERM`),setTimeout(()=>{t.pid!==void 0&&Se(t.pid,`SIGKILL`)},this.settings.killMs).unref()}}};function Nn(e){return e instanceof cn&&e.code===-32e3}var j=class extends Error{key;constructor(e,t=``){super(t),this.key=e}};const Pn={update:()=>void 0,permission:async()=>({outcome:{outcome:`cancelled`}}),read:()=>{throw Error(`refused`)},write:async()=>{throw Error(`refused`)},gone:()=>void 0};async function Fn(e,t,n){if(e===null)throw new j(`app.agent.notFound`);let r=pe(t.home,e.id);await T(r,{recursive:!0});let i=t.connectMs??3e4,a=t.killMs??2e3,o=null,s=()=>o?.kill(!0);n?.addEventListener(`abort`,s,{once:!0});try{try{if(o=await Mn.launch(e,{folder:r,env:t.env,version:t.version,connectMs:i,killMs:a},Pn),n?.aborted)throw new j(`app.agents.reason.cancelled`);let s=await o.newSession(r,[]);if(n?.aborted)throw new j(`app.agents.reason.cancelled`);if(s.options.length===0)throw new j(`app.agents.reason.noOptions`);return Cn(t.home,e.id,s.options),s.options.map(ue)}catch(e){if(e instanceof j)throw e;if(n?.aborted)throw new j(`app.agents.reason.cancelled`);if(Nn(e))throw new j(`app.agent.authRequired`);if(e instanceof Dn)throw new j(Xe(e.tail),e.tail===``?e.how:`${e.how}: ${e.tail}`);if(e instanceof Tn)throw new j(`app.agent.timeout`);let t=e?.code;throw e instanceof En||t===`ENOENT`||t===`EACCES`?new j(`app.agent.notFound`):e instanceof me?new j(`app.agent.unsafe`):new j(`app.agent.failed`,Ye(e instanceof Error?e.message:String(e)))}}finally{n?.removeEventListener(`abort`,s),o?.kill(!0)}}function In(e,t){let n=wn(e,t);if(!n)return null;let r=n.options.filter(e=>we.includes(e.category)).map(e=>({id:e.id,name:e.name,category:e.category,current:e.current,values:e.values.map(e=>({id:e.id,name:e.name}))}));return r.length===0?null:{readAt:n.readAt,options:r}}const Ln=/* @__PURE__ */ new Map;function Rn(e){let t=Ln.get(e.home);return t||(t=new fe({home:e.home,env:e.env,folder:e.folder,fetcher:e.fetcher??((e,t)=>fetch(e,t))}),Ln.set(e.home,t)),t}const zn=/* @__PURE__ */ new Map;function Bn(e){let t=zn.get(e.home);return t||(t=new Wn(e),zn.set(e.home,t)),t}function Vn(e){Ln.get(e)?.dispose(),Ln.delete(e)}const Hn=/* @__PURE__ */ new Map;function Un(e){let t=Hn.get(e);return t||(t=/* @__PURE__ */ new Map,Hn.set(e,t)),t}var Wn=class{host;refreshError=null;constructor(e){this.host=e}get models(){return Un(this.host.home)}get registry(){return oe(this.host.home)}get installer(){return Rn(this.host)}view(){let e=new Set(ye(this.host.home)),t=new h(this.host.home).agentChoices(),n=this.registry.read(),r=le(this.host.home).map(n=>this.entry(n,e.has(n.id),t[n.id]??{}));return r.sort((e,t)=>e.name.localeCompare(t.name,void 0,{sensitivity:`base`})),{agents:r,updated:n.updated,source:n.source,stale:this.registry.stale(),node:be(`npx`,this.host.env,this.host.folder)!==null,uv:be(`uvx`,this.host.env,this.host.folder)!==null,busy:this.installer.busy()||[...this.models.values()].some(e=>e.state===`running`),refreshError:this.refreshError}}async refresh(e){try{await this.registry.refresh(e),this.refreshError=null}catch(t){if(e?.aborted)throw t;this.refreshError=t instanceof ie?{key:t.key,params:{},detail:t.message}:{key:`app.agents.reason.offline`,params:{},detail:t instanceof Error?t.message:String(t)}}return this.view()}entryOf(e){let t=this.view().agents.find(t=>t.id===e);if(!t)throw g(404,`app.agent.reason.unknownAgent`,{agent:e.slice(0,80)});return t}known(e){let t=le(this.host.home).find(t=>t.id===e);if(!t)throw g(404,`app.agent.reason.unknownAgent`,{agent:e.slice(0,80)});return t}install(e){let t=this.known(e);if(!t.registry)throw g(409,`app.agents.reason.notInstallable`);this.installer.start(t.registry);let n=this.installer;return n.settled(e).then(()=>{try{n.job(e)===null&&re(this.host.home,e)!==null&&this.turn(e,!0,!1)}catch{}}),this.entryOf(e)}async uninstall(e){let t=this.known(e);if(t.custom)throw g(409,`app.agents.reason.notInstallable`);try{await this.installer.uninstall(e)}catch{throw g(409,`app.agents.reason.busy`)}return re(this.host.home,e)===null&&!this.available(t)&&this.turn(e,!1,!1),this.entryOf(e)}turn(e,t,n=!0){let r=this.known(e);if(t&&n&&!this.available(r))throw g(409,`app.agents.reason.notInstalled`);let i=new h(this.host.home),a=ye(this.host.home),o=t?[...a.filter(t=>t!==e),e]:a.filter(t=>t!==e);return i.setEnabledAgents(o),this.entryOf(e)}choose(e,t,n){this.known(e);let r=In(this.host.home,e)?.options.find(e=>(e.category??e.id)===t);if(n!==null&&(!r||!r.values.some(e=>e.id===n)))throw g(400,`app.agent.reason.badOption`,{option:String(n).slice(0,80)});return new h(this.host.home).setAgentChoice(e,t,n),this.entryOf(e)}refreshModels(e){let t=this.known(e);if(this.models.get(e)?.state===`running`)return this.entryOf(e);let n=new AbortController,r={state:`running`,error:null,abort:n};this.models.set(e,r);let i=setTimeout(()=>n.abort(),9e4);return i.unref(),Fn(ne(t,this.host.env,this.host.home,this.host.folder),{home:this.host.home,env:this.host.env,version:this.host.version,connectMs:this.host.connectMs,killMs:this.host.killMs},n.signal).then(()=>{this.models.get(e)===r&&this.models.delete(e)}).catch(e=>{if(r.state=`failed`,e instanceof j){let t=n.signal.aborted&&e.key!==`app.agents.reason.cancelled`?`app.agent.timeout`:e.key;r.error={key:t,params:{},detail:e.message}}else r.error={key:`app.agent.failed`,params:{},detail:e instanceof Error?e.message:String(e)}}).finally(()=>clearTimeout(i)),this.entryOf(e)}dispose(){for(let e of this.models.values())e.abort.abort();this.models.clear(),Vn(this.host.home)}available(e){return ne(e,this.host.env,this.host.home,this.host.folder)!==null}entry(e,t,n){let r=se(e,this.host.env,this.host.home,this.host.folder),i=e.custom?null:re(this.host.home,e.id),a=e.registry,o=a?ae(a,this.host.env,this.host.folder):null,s=this.installer.job(e.id),c=this.models.get(e.id),l=null;return s?l={kind:s.kind,state:s.state,percent:s.percent,error:s.error}:c&&(l={kind:`models`,state:c.state,percent:null,error:c.error}),{id:e.id,name:e.name,version:a?.version??null,description:a?.description??(e.custom?f(`app.agents.customDescription`,{command:e.custom.command}):``),website:a?.website??a?.repository??null,repository:a?.repository??null,license:a?.license??null,icon:e.icon,source:e.source,installed:r!==null,installedVia:r,installedVersion:i?.version??null,updateAvailable:i!==null&&a!==null&&he(a.version,i.version),enabled:t,how:e.custom?`custom`:o===null||o.kind===`blocked`?`none`:o.kind,blocked:o?.kind===`blocked`?o.reason:null,install:e.source===`preset`?e.preset?.install??null:null,job:l,options:In(this.host.home,e.id),chosen:n}}},M=class extends Error{constructor(){super(`cancelled`)}};const Gn=/* @__PURE__ */ new Set([`chats`,`enabled`]),Kn=/* @__PURE__ */ new Set([`queue`,`permission`,`error`,`options`]);function qn(e){return typeof e==`object`&&e?String(e.id??``):``}function Jn(e){let t=String(e.chatId??``);return Gn.has(e.type)?{key:e.type,inPlace:!1}:Kn.has(e.type)?{key:`${e.type}:${t}`,inPlace:!1}:e.type===`plan`?{key:`plan:${t}`,inPlace:!0}:e.type===`entry`?{key:`entry:${t}:${qn(e.entry)}`,inPlace:!0}:e.type===`tool`?{key:`tool:${t}:${qn(e.tool)}`,inPlace:!0}:null}var Yn=class{subscribers=/* @__PURE__ */ new Map;idleMs;maxQueue;pollMs;now;start;sweeper=null;closed=!1;constructor(e,t={}){this.start=e,this.idleMs=t.idleMs??6e4,this.maxQueue=t.maxQueue??1024,this.pollMs=t.pollMs??25e3,this.now=t.now??Date.now}get size(){return this.subscribers.size}get waiting(){let e=0;for(let t of this.subscribers.values())t.waiter&&(e+=1);return e}publish(e){if(this.closed)return;let t=Jn(e);for(let n of this.subscribers.values()){let r=n.waiter;if(r&&n.queue.length===0)n.waiter=null,n.seen=this.now(),r.timer&&clearTimeout(r.timer),r.resolve(e);else{if(t!==null){let r=n.queue.findIndex(e=>Jn(e)?.key===t.key);if(r>=0&&t.inPlace){n.queue[r]=e;continue}r>=0&&n.queue.splice(r,1)}n.queue.push(e),n.queue.length>this.maxQueue&&(n.queue=this.start())}}}next(e,t){if(this.closed||t.aborted)return Promise.reject(new M);let n=this.subscribers.get(e);n||=this.enrol(e),n.seen=this.now();let r=n.queue.shift();if(r)return Promise.resolve(r);if(n.waiter){let e=n.waiter;n.waiter=null,e.timer&&clearTimeout(e.timer),e.resolve(void 0)}let i=n;return new Promise((e,n)=>{let r={resolve:n=>{t.removeEventListener(`abort`,a),e(n)},reject:n,timer:null},a=()=>{i.waiter===r&&(i.waiter=null),r.timer&&clearTimeout(r.timer),i.seen=this.now(),n(new M)};r.timer=setTimeout(()=>{i.waiter===r&&(i.waiter=null),i.seen=this.now(),r.resolve(void 0)},this.pollMs),r.timer.unref(),t.addEventListener(`abort`,a,{once:!0}),i.waiter=r})}close(){this.closed=!0,this.sweeper&&clearInterval(this.sweeper),this.sweeper=null;for(let e of this.subscribers.values()){let t=e.waiter;e.waiter=null,t?.timer&&clearTimeout(t.timer),t?.reject(new M)}this.subscribers.clear()}enrol(e){let t={queue:this.start(),waiter:null,seen:this.now()};return this.subscribers.set(e,t),this.sweeper||(this.sweeper=setInterval(()=>this.sweep(),Math.max(10,Math.floor(this.idleMs/2))),this.sweeper.unref()),t}sweep(){let e=this.now()-this.idleMs;for(let[t,n]of this.subscribers)!n.waiter&&n.seen<e&&this.subscribers.delete(t);this.subscribers.size===0&&this.sweeper&&(clearInterval(this.sweeper),this.sweeper=null)}};const N=1048576,P=25165824,Xn=12e4,Zn=/^git~\d+$/;function Qn(e){let t=e.split(`:`,1)[0].replace(/^ +/,``).replace(/[. ]+$/,``).toLowerCase();return t===`.git`||Zn.test(t)}function $n(e){return e.some(Qn)}var F=class extends Error{status;failure;constructor(e,t,n=null){super(t),this.name=`WebFailure`,this.status=e,this.failure=n}};function I(e,t,n){return new F(e,f(t,n))}function er(e){if(e instanceof F)return e;if(e instanceof _e)return new F(e.status,e.message,e.failure);let t=e?.code;return t===`ENOENT`||t===`ENOTDIR`?I(404,`app.cli.web.reason.noSuchFile`):t===`EACCES`||t===`EPERM`?I(403,`app.cli.web.reason.noAccess`):t===`EISDIR`?I(400,`app.cli.web.reason.isAFolder`):t===`ENOSPC`?I(507,`app.cli.web.reason.diskFull`):t===`EEXIST`||t===`ENOTEMPTY`?I(409,`app.cli.web.reason.exists`):t===`EBUSY`?I(409,`app.cli.web.reason.busy`):t===`EROFS`?I(403,`app.cli.web.reason.readOnly`):t===`ENAMETOOLONG`?I(400,`app.cli.web.reason.nameLong`):t===`EXDEV`?I(400,`app.cli.web.reason.otherDisk`):I(500,`app.cli.web.reason.internal`)}const tr=/\.(bpmn|bpmn\.xml|bpmn20\.xml)$/i,nr=/^penstock\.(yaml|yml|json)$/i,rr=/* @__PURE__ */ new Set([`.camunda`]);function ir(e){return Mt(e,{throwIfNoEntry:!1})}function ar(e,t=0){let n=e,r=[];for(;!b(n);){if(t<40&&ir(n)?.isSymbolicLink()){let e;try{e=Ft(n)}catch{return v.join(n,...r)}return ar(v.join(v.resolve(v.dirname(n),e),...r),t+1)}let i=v.dirname(n);if(i===n)return e;r.unshift(v.basename(n)),n=i}return v.join(S.native(n),...r)}function or(e,t,n=v){let r=n.relative(t,e);return r===``||r!==`..`&&!r.startsWith(`..${n.sep}`)&&!n.isAbsolute(r)}function sr(e){return String(e).replace(/[\u0000-\u001f\u007f]/g,`?`).slice(0,200)}var cr=class{root;checkedAt=0;constructor(e){this.root=ar(v.resolve(e))}stands(){let e=Date.now();if(e-this.checkedAt<250)return!0;let t=C(this.root,{throwIfNoEntry:!1})?.isDirectory()===!0;return t&&(this.checkedAt=e),t}resolve(e){if(typeof e!=`string`||e.length===0||e.length>4096||e.includes(`\0`))throw I(400,`app.cli.web.reason.badPath`,{path:sr(e)});if(e.split(/[\\/]/).includes(`..`))throw I(403,`app.cli.web.reason.outside`,{path:sr(e)});if(!this.stands())throw I(409,`app.cli.web.reason.projectGone`);let t=ar(v.resolve(this.root,e));if(!or(t,this.root)||$n(this.segments(t)))throw I(403,`app.cli.web.reason.outside`,{path:sr(e)});return t}segments(e){return v.relative(this.root,e).split(v.sep).filter(e=>e!==``)}relative(e){return this.segments(e).join(`/`)}writeKind(e){let t=this.segments(e);if(t.length===0)return null;let n=t.slice(0,-1);if(n.some(e=>_.has(e)||e.startsWith(`.`)&&!rr.has(e)))return null;let r=t[t.length-1];if(tr.test(r))return`diagram`;if(/\.dmn$/i.test(r))return`decision`;if(/\.form$/i.test(r))return`form`;if(nr.test(r))return`penstock`;if(/\.json$/i.test(r)){if(n[n.length-1]===`test-cases`)return`test-case`;if(n.includes(`element-templates`))return`element-template`}return null}writable(e,t){let n=this.writeKind(e);if(!n)throw I(403,`app.cli.web.reason.notEditable`,{path:sr(t)});return n}};const lr=/* @__PURE__ */ new Set([`projectChanged`,`codeChanged`]);var ur=class{clients=/* @__PURE__ */ new Map;idleMs;maxQueue;now;forgetting=/* @__PURE__ */ new Set;sweeper=null;closed=!1;constructor(e={}){this.idleMs=e.idleMs??6e4,this.maxQueue=e.maxQueue??64,this.now=e.now??Date.now}get size(){return this.clients.size}get waiting(){let e=0;for(let t of this.clients.values())e+=t.waiters.length+t.lspWaiters.length;return e}knows(e){return this.clients.has(e)}seed(e,t){this.closed||(this.clients.get(e)??this.enrol(e)).queue.push(...t)}publish(e){if(!this.closed)for(let t of this.clients.values()){let n=t.waiters.shift();n?(t.seen=this.now(),n.resolve(e)):lr.has(e.type)&&t.queue.some(t=>t.type===e.type)||(t.queue.push(e),t.queue.length>this.maxQueue&&t.queue.splice(0,t.queue.length-this.maxQueue))}}publishTo(e,t){if(this.closed)return;let n=this.clients.get(e)??this.enrol(e),r=n.lspWaiters.shift();r?(n.seen=this.now(),r.resolve([t])):n.lsp.push(t)}nextMessages(e,t){if(this.closed||t.aborted)return Promise.reject(new M);let n=this.clients.get(e)??this.enrol(e);return n.seen=this.now(),n.lsp.length>0?Promise.resolve(n.lsp.splice(0)):new Promise((e,r)=>{let i={resolve:n=>{t.removeEventListener(`abort`,a),e(n)},reject:r},a=()=>{let e=n.lspWaiters.indexOf(i);e>=0&&n.lspWaiters.splice(e,1),n.seen=this.now(),r(new M)};t.addEventListener(`abort`,a,{once:!0}),n.lspWaiters.push(i)})}onForget(e){return this.forgetting.add(e),()=>this.forgetting.delete(e)}next(e,t){if(this.closed||t.aborted)return Promise.reject(new M);let n=this.clients.get(e)??this.enrol(e);n.seen=this.now();let r=n.queue.shift();return r?Promise.resolve(r):new Promise((e,r)=>{let i={resolve:n=>{t.removeEventListener(`abort`,a),e(n)},reject:r},a=()=>{let e=n.waiters.indexOf(i);e>=0&&n.waiters.splice(e,1),n.seen=this.now(),r(new M)};t.addEventListener(`abort`,a,{once:!0}),n.waiters.push(i)})}drop(){for(let e of this.clients.values())e.queue.length=0,e.lsp.length=0}close(){this.closed=!0,this.sweeper&&clearInterval(this.sweeper),this.sweeper=null;for(let e of this.clients.values()){for(let t of e.waiters.splice(0))t.reject(new M);for(let t of e.lspWaiters.splice(0))t.reject(new M)}this.clients.clear()}enrol(e){let t={queue:[],waiters:[],lsp:[],lspWaiters:[],seen:this.now()};return this.clients.set(e,t),this.sweeper||(this.sweeper=setInterval(()=>this.sweep(),Math.max(10,Math.floor(this.idleMs/2))),this.sweeper.unref()),t}sweep(){let e=this.now()-this.idleMs;for(let[t,n]of this.clients)if(n.waiters.length===0&&n.lspWaiters.length===0&&n.seen<e){this.clients.delete(t);for(let e of this.forgetting)e(t)}this.clients.size===0&&this.sweeper&&(clearInterval(this.sweeper),this.sweeper=null)}};function L(e){if(typeof e!=`object`||!e||Array.isArray(e))throw I(400,`app.cli.web.reason.notAnObject`);return e}function R(e,t){let n=e[t];if(typeof n!=`string`)throw I(400,`app.cli.web.reason.missingField`,{field:t});return n}function z(e,t){let n=e[t];if(n!=null){if(typeof n!=`string`)throw I(400,`app.cli.web.reason.wrongField`,{field:t});return n}}function B(e,t){let n=e[t];if(n==null)return!1;if(typeof n!=`boolean`)throw I(400,`app.cli.web.reason.wrongField`,{field:t});return n}function V(e,t){let n=e[t];if(!Array.isArray(n))throw I(400,`app.cli.web.reason.missingField`,{field:t});return n}function dr(e,t){let n=V(e,t);if(!n.every(e=>typeof e==`string`))throw I(400,`app.cli.web.reason.wrongField`,{field:t});return n}const fr=/^[\w.-]{1,64}$/;function pr(e){let t=e.context;if(t==null)return null;let n=L(t);return{file:z(n,`file`)??null,elementIds:n.elementIds===void 0||n.elementIds===null?[]:dr(n,`elementIds`)}}const mr=/^[^\u0000-\u001f\u007f]{1,128}$/;function hr(e){let t=e.params.agentId;if(t===void 0||!mr.test(t))throw I(400,`app.cli.web.reason.wrongField`,{field:`agentId`});return t}const gr=[{method:`GET`,path:`/api/agent/catalog`,operationId:`getAgentCatalog`,run:(e,t)=>t.view()},{method:`POST`,path:`/api/agent/catalog/refresh`,operationId:`refreshAgentCatalog`,held:!0,run:(e,t)=>t.refresh(e.signal)},{method:`POST`,path:`/api/agent/agents/{agentId}/install`,operationId:`installAgent`,run:(e,t)=>t.install(hr(e))},{method:`POST`,path:`/api/agent/agents/{agentId}/uninstall`,operationId:`uninstallAgent`,run:(e,t)=>t.uninstall(hr(e))},{method:`POST`,path:`/api/agent/agents/{agentId}/turn`,operationId:`turnAgent`,limit:N,run:(e,t)=>{let n=L(e.body);if(typeof n.enabled!=`boolean`)throw I(400,`app.cli.web.reason.wrongField`,{field:`enabled`});return t.turn(hr(e),B(n,`enabled`))}},{method:`POST`,path:`/api/agent/agents/{agentId}/models/refresh`,operationId:`refreshAgentModels`,run:(e,t)=>t.refreshModels(hr(e))},{method:`PUT`,path:`/api/agent/agents/{agentId}/options`,operationId:`chooseAgentOption`,limit:N,run:(e,t)=>{let n=L(e.body),r=R(n,`category`);if(r===``||r.length>256)throw I(400,`app.cli.web.reason.wrongField`,{field:`category`});return t.choose(hr(e),r,z(n,`value`)??null)}},{method:`POST`,path:`/api/agent/settings/open`,operationId:`openAgentSettings`,run:()=>{throw I(501,`app.agents.reason.noHostPage`)}}],_r=[{method:`GET`,path:`/api/agent/choices`,operationId:`getAgentChoices`,run:(e,t)=>({agents:t.choices()})},{method:`GET`,path:`/api/agent/chats`,operationId:`listAgentChats`,run:(e,t)=>t.list()},{method:`POST`,path:`/api/agent/chats`,operationId:`createAgentChat`,limit:N,run:(e,t)=>{let n=e.body===void 0||e.body===null?null:z(L(e.body),`agentId`)??null;return t.create(n)}},{method:`GET`,path:`/api/agent/chats/{chatId}`,operationId:`getAgentChat`,run:(e,t)=>t.get(e.params.chatId)},{method:`PATCH`,path:`/api/agent/chats/{chatId}`,operationId:`renameAgentChat`,limit:N,run:(e,t)=>t.rename(e.params.chatId,R(L(e.body),`title`))},{method:`DELETE`,path:`/api/agent/chats/{chatId}`,operationId:`deleteAgentChat`,run:(e,t)=>{t.remove(e.params.chatId)}},{method:`POST`,path:`/api/agent/chats/{chatId}/prompt`,operationId:`promptAgent`,limit:1048576,run:(e,t)=>{let n=L(e.body);return t.prompt(e.params.chatId,R(n,`text`),pr(n))}},{method:`DELETE`,path:`/api/agent/chats/{chatId}/queue/{queueId}`,operationId:`unqueueAgentPrompt`,run:(e,t)=>{t.unqueue(e.params.chatId,e.params.queueId)}},{method:`POST`,path:`/api/agent/chats/{chatId}/stop`,operationId:`stopAgentTurn`,run:(e,t)=>{t.stop(e.params.chatId)}},{method:`POST`,path:`/api/agent/chats/{chatId}/sign-in`,operationId:`signInAgent`,held:!0,run:(e,t)=>t.signIn(e.params.chatId)},{method:`POST`,path:`/api/agent/chats/{chatId}/permission`,operationId:`answerAgentPermission`,limit:N,run:(e,t)=>{let n=L(e.body),r=R(n,`permissionId`),i=R(n,`optionId`);if(r===``||i===``)throw I(400,`app.cli.web.reason.wrongField`,{field:i===``?`optionId`:`permissionId`});t.answer(e.params.chatId,r,i)}},{method:`POST`,path:`/api/agent/chats/{chatId}/options`,operationId:`setAgentConfigOption`,limit:N,run:(e,t)=>{let n=L(e.body),r=R(n,`optionId`),i=R(n,`valueId`);if(r===``||i===``)throw I(400,`app.cli.web.reason.wrongField`,{field:r===``?`optionId`:`valueId`});return t.setOption(e.params.chatId,r,i)}},{method:`GET`,path:`/api/agent/events`,operationId:`nextAgentEvent`,held:!0,run:(e,t)=>{let n=e.query.get(`client`);if(n===null||!fr.test(n))throw g(400,`app.agent.reason.noClient`);return t.next(n,e.signal)}}],vr=[..._r,...gr.map(e=>({...e,run:(t,n)=>e.run(t,n.catalog())}))],yr=new Set(gr.map(e=>e.operationId));function br(e,t){return e.replace(/\{(\w+)\}/g,(e,n)=>encodeURIComponent(t[n]??``))}const xr=[..._r.map(e=>({method:e.method,path:e.path,operationId:e.operationId,limit:e.limit,held:e.held,run:(t,n)=>n.agent.request(e.method,br(e.path,t.params),t.body,{query:t.query,signal:t.signal})})),...gr.map(t=>({method:t.method,path:t.path,operationId:t.operationId,limit:t.limit,held:t.held,run:(n,r)=>t.run(n,Bn({home:r.home,env:r.env,folder:r.open?r.folder:r.home,version:e()}))}))],Sr={"X-Content-Type-Options":`nosniff`,"Referrer-Policy":`no-referrer`,"X-Frame-Options":`DENY`,"Cross-Origin-Resource-Policy":`same-origin`,"Content-Security-Policy":`frame-ancestors 'none'; base-uri 'self'; object-src 'none'; script-src 'self' 'unsafe-eval' 'wasm-unsafe-eval'`};function Cr(e){for(let[t,n]of Object.entries(Sr))e.setHeader(t,n)}function wr(e,t,n,r={}){if(e.headersSent||e.destroyed)return;for(let[t,n]of Object.entries(r))e.setHeader(t,n);if(e.setHeader(`Cache-Control`,`no-store`),t===204||n===void 0){e.writeHead(t===200?204:t),e.end();return}let i=JSON.stringify(n);e.writeHead(t,{"Content-Type":`application/json; charset=utf-8`,"Content-Length":Buffer.byteLength(i)}),e.end(i)}function Tr(e,t,n={}){let r=t.failure?{message:t.message,key:t.failure.key,detail:t.failure.detail}:{message:t.message};wr(e,t.status,r,n)}function Er(e){return I(413,`app.cli.web.reason.tooLarge`,{limit:Math.floor(e/1048576)})}function Dr(e,t){return new Promise((n,r)=>{let i=[],a=0,o=!1,s=null,c=()=>{o||(o=!0,i.length=0,s=setTimeout(()=>e.destroy(),1e4),s.unref(),r(Er(t)))};e.on(`data`,n=>{if(a+=n.length,o)a>67108864&&e.destroy();else{if(a>t)return c();i.push(n)}}),e.once(`end`,()=>{s&&clearTimeout(s),o||n(Buffer.concat(i))}),e.once(`close`,()=>{s&&clearTimeout(s),!e.complete&&!o&&r(/* @__PURE__ */ Error(`the request was cut short`))}),e.once(`error`,e=>{o||r(e)});let l=Number(e.headers[`content-length`]);Number.isFinite(l)&&l>t&&c()})}var Or=class{headers;body;constructor(e,t){this.headers=e,this.body=t}};function kr(e){try{return e()}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return;throw e}}function Ar(e){return kr(()=>C(e))}function jr(e){return kr(()=>Mt(e))}function Mr(e){return Ar(e)?.isFile()===!0}function H(e){return Ar(e)?.isDirectory()===!0}const Nr=/^[A-Za-z0-9._-]{1,128}$/,Pr=`The response is larger than 64 MB`;function Fr(e=process.env,t=kt()){return v.resolve(e.PENSTOCK_HOME||v.join(t,`.penstock`),`connectors`)}let Ir=!1;function Lr(){if(Ir)return;Ir=!0;let e=process.env;if(!(e.HTTPS_PROXY||e.https_proxy||e.HTTP_PROXY||e.http_proxy))return;let t=on.setGlobalProxyFromEnv;typeof t==`function`&&t.call(on)}async function Rr(e,t){let n=e.body?.getReader();if(!n)return/* @__PURE__ */ new Uint8Array;let r=[],i=0;for(;;){let{done:e,value:a}=await n.read();if(e)break;if(i+=a.byteLength,i>t)return await n.cancel().catch(()=>void 0),null;r.push(a)}let a=new Uint8Array(i),o=0;for(let e of r)a.set(e,o),o+=e.byteLength;return a}function zr(e){return{status:0,body:``,failure:e}}async function Br(e,t=fetch,n=2e4){if(!it(e))throw Error(`Not a connector catalogue URL: ${e}`);Lr();let r;try{r=await t(e,{redirect:`manual`,headers:{"User-Agent":`Penstock`},signal:AbortSignal.timeout(n)})}catch(e){let t=e.cause?.message;return zr(t??(e instanceof Error?e.message:`GitHub could not be reached`))}if(r.status>=300&&r.status<400)return await r.body?.cancel().catch(()=>void 0),zr(`GitHub answered with a redirect, which is not followed`);if(Number(r.headers.get(`content-length`)??0)>67108864)return await r.body?.cancel().catch(()=>void 0),zr(Pr);try{let e=await Rr(r,at);return e?{status:r.status,body:Buffer.from(e).toString(`base64`)}:zr(Pr)}catch(e){return zr(e instanceof Error?e.message:`The download was interrupted`)}}function Vr(e){return e!==`.`&&e!==`..`&&Nr.test(e)}function Hr(e){return jr(e)?.isSymbolicLink()===!0}var Ur=class{base;constructor(e){this.base=v.resolve(e)}root(){return Nt(this.base,{recursive:!0}),S(this.base)}resolve(e){let t=e.split(`/`);if(t.length>16||t.some(e=>!Vr(e)))throw Error(`Not a path inside the connectors directory: ${e}`);let n=this.root(),r=n;for(let i of t){r=v.join(r,i);let t=jr(r);if(t?.isSymbolicLink())throw Error(`The connectors directory holds a link at ${e}`);if(!t)break;if(!S(r).startsWith(n))throw Error(`Not a path inside the connectors directory: ${e}`)}return v.join(n,...t)}mkdirsFor(e){let t=this.root(),n=t;for(let r of v.relative(t,e).split(v.sep))if(r.length!==0){if(n=v.join(n,r),Hr(n))throw Error(`The connectors directory holds a link`);if(b(n)||Nt(n),!C(n).isDirectory())throw Error(`A file is in the way`)}}handle(e){if(e.path.length===0){if(e.op!==`list`)throw Error(`Only list may name the connectors directory itself`);return this.list(this.root())}let t=this.resolve(e.path);switch(e.op){case`exists`:return{pathExists:b(t)};case`read`:return this.read(t);case`write`:return this.write(t,e.content);case`delete`:return this.delete(t);case`list`:return this.list(t);case`mkdirs`:return this.mkdirsFor(t),{};case`rename`:return this.rename(t,e.dest);default:throw Error(`Unknown operation: ${String(e.op)}`)}}read(e){let t=Ar(e);if(!t?.isFile())return{content:null};if(t.size>67108864)throw Error(`The file is larger than 64 MB`);return{content:x(e).toString(`base64`)}}write(e,t){let n=t?Buffer.from(t,`base64`):Buffer.alloc(0);if(n.length>67108864)throw Error(`The content is larger than 64 MB`);if(H(e))throw Error(`A directory is in the way`);return this.mkdirsFor(v.dirname(e)),zt(e,n),{}}delete(e){return b(e)&&Lt(e,{recursive:!0,force:!0}),{}}list(e){return H(e)?{entries:Pt(e).sort()}:{entries:[]}}rename(e,t){if(!t)throw Error(`Rename needs a destination`);let n=this.resolve(t);if(!b(e))throw Error(`Nothing to move`);if(b(n))throw Error(`The destination already exists`);return this.mkdirsFor(v.dirname(n)),It(e,n),{}}};const Wr=/* @__PURE__ */ new Set([`read`,`write`,`delete`,`list`,`exists`,`mkdirs`,`rename`]),Gr=[{method:`POST`,path:`/api/connectors/fetch`,operationId:`fetchConnectorUrl`,limit:N,run:async(e,t)=>{try{return await Br(R(L(e.body),`url`),t.fetch)}catch(e){throw I(400,`app.cli.web.reason.connectorRefused`,{detail:e instanceof Error?e.message:String(e)})}}},{method:`POST`,path:`/api/connectors/file`,operationId:`connectorFile`,limit:P,run:(e,t)=>{let n=L(e.body),r=R(n,`op`);if(!Wr.has(r))throw I(400,`app.cli.web.reason.wrongField`,{field:`op`});try{return new Ur(Fr(t.env)).handle({op:r,path:R(n,`path`),content:z(n,`content`),dest:z(n,`dest`)})}catch(e){throw I(400,`app.cli.web.reason.connectorRefused`,{detail:e instanceof Error?e.message:String(e)})}}}];function U(e){return typeof e==`string`&&e.trim()?e.trim():void 0}function Kr(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:{}}const qr=[`penstock.yaml`,`penstock.yml`,`penstock.json`],W=[`penstock.local.yaml`,`penstock.local.yml`,`penstock.local.json`],Jr=()=>`# ${f(`app.config.local.writtenBy`)}\n# ${f(`app.config.local.valuesWin`)}\n`;function Yr(e,t){for(let n of t){let t=v.join(e,n);if(Mr(t))return t}return null}function Xr(e){return e.authType??`none`}function Zr(e){let t=Xr(e),n=[],r=U(e.url);r&&n.push([[`url`],r]),n.push([[`auth`,`type`],t]);let i=t=>{let r=U(e[t]);r&&n.push([[`auth`,t],r])};return t===`basic`&&i(`username`),t===`oauth`&&(i(`clientId`),i(`tokenUrl`),i(`audience`)),n}function Qr(e,t,n){Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0})}function $r(e,t,n){let r=e;for(let e of t.slice(0,-1)){let t=Object.hasOwn(r,e)?r[e]:void 0;(!t||typeof t!=`object`||Array.isArray(t))&&Qr(r,e,{}),r=r[e]}Qr(r,t[t.length-1],n)}function ei(e){let n=v.join(e,`.gitignore`);if(!b(n))return;let r=x(n,`utf8`);r.split(`
3
3
  `).some(e=>e.trim()===W[0])||t(n,`${r.replace(/\n+$/,``)}\n\n# Penstock, this machine only\n${W[0]}\n`)}function ti(e,t){let n=e.slice(0,t.pos[0]).split(`
4
- `).length;return f(`app.vscode.host.notValidYaml`,{code:t.code,line:n})}function ni(e){let t;try{t=JSON.parse(x(e,`utf8`)||`{}`)}catch{throw Error(f(`app.vscode.host.unreadable`,{file:v.basename(e),reason:f(`app.vscode.host.notValidJson`)}))}if(!t||typeof t!=`object`||Array.isArray(t))throw Error(f(`app.vscode.host.unreadable`,{file:v.basename(e),reason:`the top level is not an object`}));return t}function ri(e,n,r){let i=n===null?[`deployment`]:[`profiles`,n,`deployment`],a=Zr(r),o=Yr(e,W),s=o??v.join(e,W[0]);if(o?.endsWith(`.json`)){let e=ni(o);a.forEach(([t,n])=>$r(e,[...i,...t],n)),t(o,`${JSON.stringify(e,null,2)}\n`)}else{let e=o?x(o,`utf8`):``,n=o?an(e):new rn({});if(n.errors.length>0)throw Error(f(`app.vscode.host.unreadable`,{file:v.basename(s),reason:ti(e,n.errors[0])}));a.forEach(([e,t])=>n.setIn([...i,...e],t)),t(s,o?n.toString():Jr()+n.toString())}return ei(e),s}function ii(e){return Qe(e)??`camunda-7`}function ai(e){let t=[`# yaml-language-server: $schema=${ke}`,`# ${f(`app.config.file.readsInstead`)}`,`# ${f(`app.config.file.overrides`)}`,``,`engine: ${ii(e.engine)}`];e.scriptType!==`NONE`&&e.scriptType&&t.push(`scriptType: ${e.scriptType.toLowerCase()}`),t.push(``);let n=e.elementTemplates??[];if(n.length===0)t.push(`# ${f(`app.config.file.templatesFrom`)}`,`# elementTemplates:`,`# - .camunda/element-templates`);else{let e=new rn({elementTemplates:n}).toString().trimEnd();t.push(e)}return`${t.join(`
4
+ `).length;return f(`app.vscode.host.notValidYaml`,{code:t.code,line:n})}function ni(e){let t;try{t=JSON.parse(x(e,`utf8`)||`{}`)}catch{throw Error(f(`app.vscode.host.unreadable`,{file:v.basename(e),reason:f(`app.vscode.host.notValidJson`)}))}if(!t||typeof t!=`object`||Array.isArray(t))throw Error(f(`app.vscode.host.unreadable`,{file:v.basename(e),reason:`the top level is not an object`}));return t}function ri(e,n,r){let i=n===null?[`deployment`]:[`profiles`,n,`deployment`],a=Zr(r),o=Yr(e,W),s=o??v.join(e,W[0]);if(o?.endsWith(`.json`)){let e=ni(o);a.forEach(([t,n])=>$r(e,[...i,...t],n)),t(o,`${JSON.stringify(e,null,2)}\n`)}else{let e=o?x(o,`utf8`):``,n=o?an(e):new rn({});if(n.errors.length>0)throw Error(f(`app.vscode.host.unreadable`,{file:v.basename(s),reason:ti(e,n.errors[0])}));a.forEach(([e,t])=>n.setIn([...i,...e],t)),t(s,o?n.toString():Jr()+n.toString())}return ei(e),s}function ii(e){return Qe(e)??`camunda-7`}function ai(e){let t=[`# yaml-language-server: $schema=${De}`,`# ${f(`app.config.file.readsInstead`)}`,`# ${f(`app.config.file.overrides`)}`,``,`engine: ${ii(e.engine)}`];e.scriptType!==`NONE`&&e.scriptType&&t.push(`scriptType: ${e.scriptType.toLowerCase()}`),t.push(``);let n=e.elementTemplates??[];if(n.length===0)t.push(`# ${f(`app.config.file.templatesFrom`)}`,`# elementTemplates:`,`# - .camunda/element-templates`);else{let e=new rn({elementTemplates:n}).toString().trimEnd();t.push(e)}return`${t.join(`
5
5
  `)}\n`}function oi(e,n){let r=Yr(e,qr);if(!r)return t(v.join(e,qr[0]),ai(n)),`created`;if(r.endsWith(`.json`))return`skipped`;let i=x(r,`utf8`),a=an(i);if(a.errors.length>0)throw Error(f(`app.vscode.host.unreadable`,{file:v.basename(r),reason:ti(i,a.errors[0])}));return a.set(`engine`,ii(n.engine)),!a.has(`scriptType`)&&n.scriptType&&n.scriptType!==`NONE`&&a.set(`scriptType`,n.scriptType.toLowerCase()),!a.has(`elementTemplates`)&&(n.elementTemplates??[]).length>0&&a.set(`elementTemplates`,n.elementTemplates),t(r,a.toString()),`updated`}const si=/^\/[\w\-./?=&%]*$/,ci=/* @__PURE__ */ new Set([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`]),li=[/^\/deployments$/,/^\/deployment\/create$/,/^\/process-definitions\/search$/,/^\/process-definitions\/[^/]+\/variable-names\/search$/,/^\/process-definitions\/[^/]+\/statistics\/element-instances$/,/^\/process-instances\/search$/,/^\/decision-requirements\/search$/,/^\/decision-instances\/search$/,/^\/element-instances\/search$/,/^\/user-tasks\/search$/,/^\/jobs\/search$/,/^\/jobs\/statistics\/by-types$/,/^\/variables\/search$/,/^\/incidents\/search$/,/^\/expression\/evaluation$/],ui=/%[0-9A-Fa-f]{2}/g;function di(e){return ci.has(e)}function fi(e){if(!si.test(e)||e.includes(`..`)||e.includes(`//`))return!1;let t=e.replace(ui,e=>String.fromCharCode(parseInt(e.slice(1),16)));return!t.includes(`..`)&&!t.includes(`//`)}function pi(e,t){if(e===`PUT`||e===`PATCH`||e===`DELETE`)return!0;let n=t.split(`?`)[0];return e===`POST`&&!li.some(e=>e.test(n))}function mi(e){return e===`localhost`||e.endsWith(`.localhost`)||e===`::1`?!0:/^127(\.\d{1,3}){3}$/.test(e)}function hi(e,t){if(t)return!0;let n;try{n=new URL(e).hostname.replace(/^\[/,``).replace(/\]$/,``).toLowerCase()}catch{return!1}return mi(n)}function gi(e){return e.trim().replace(/\/+$/,``)}function _i(e,t){return e.endsWith(t)?e.slice(0,-t.length):e}function vi(e){return _i(gi(e),`/deployment/create`)}function yi(e){return`${_i(_i(gi(e),`/deployments`),`/v2`)}/v2`}function bi(e){return e.replace(/"/g,`%22`).replace(/\r/g,`%0D`).replace(/\n/g,`%0A`)}function xi(e,t){let n=[],r=e=>n.push(Buffer.from(e));for(let n of t)r(`--${e}\r\n`),r(`Content-Disposition: form-data; name="${bi(n.name)}"${n.filename?`; filename="${bi(n.filename)}"`:``}\r\n`),n.contentType&&r(`Content-Type: ${n.contentType.replace(/[\r\n]+/g,` `)}\r\n`),r(`\r
6
6
  `),r(n.content),r(`\r
7
7
  `);return r(`--${e}--\r\n`),Buffer.concat(n)}function Si(e,t){let n=e.parts??[];if(n.length>0){let e=`----PenstockBoundary${Wt()}`;return{init:{method:`POST`,headers:{"Content-Type":`multipart/form-data; boundary=${e}`,...t},body:new Uint8Array(xi(e,n))},timeout:3e4}}let r=e.method===`POST`||e.method===`PUT`||e.method===`PATCH`;return{init:{method:e.method,headers:{Accept:`application/json`,...r?{"Content-Type":`application/json`}:{},...t},body:r?e.body??``:void 0},timeout:2e4}}function Ci(e){if(!fi(e.path))throw Error(`${e.path} is not a path on the engine's API`);if(!di(e.method))throw Error(`The engine is asked with GET, POST, PUT, PATCH or DELETE only`)}function wi(e,t){if(Ci(e),(e.testRun===!0||pi(e.method,e.path))&&!hi(t.base,t.forTests))throw Error(`A test-case run changes only an engine marked deployment.forTests or one on this machine, and ${t.base} is neither`)}async function Ti(e,t){let n=Number(e.headers.get(`content-length`)),r=()=>Error(f(`app.cli.web.reason.engineAnswerTooLarge`,{limit:Math.floor(t/1048576)}));if(Number.isFinite(n)&&n>t)throw await e.body?.cancel().catch(()=>void 0),r();if(!e.body)return``;let i=e.body.getReader(),a=[],o=0;for(;;){let{done:e,value:n}=await i.read();if(e)break;if(o+=n.length,o>t)throw await i.cancel().catch(()=>void 0),r();a.push(n)}return Buffer.concat(a).toString(`utf8`)}async function Ei(e,t,n=fetch,r){wi(e,t);let i=t.base+e.path,{init:a,timeout:o}=Si(e,t.headers);if(r?.aborted)throw r.reason;let s=r?AbortSignal.any([r,AbortSignal.timeout(o)]):AbortSignal.timeout(o),c;try{c=await n(i,{...a,signal:s})}catch(e){throw r?.aborted?r.reason:Error(`Could not reach the engine at ${i}: ${ot(e)}`)}return{status:c.status,body:await Ti(c,67108864),url:i}}const Di={classic:`CLASSIC_BPMN`,"classic-bpmn":`CLASSIC_BPMN`,"camunda-7":`CAMUNDA_7`,camunda7:`CAMUNDA_7`,"camunda-8":`CAMUNDA_8`,camunda8:`CAMUNDA_8`},Oi={none:`NONE`,groovy:`GROOVY`,javascript:`JAVASCRIPT`},ki=[`none`,`basic`,`oauth`];function Ai(e){return ki.find(t=>t===e?.toLowerCase())??`none`}function ji(e,t){let n=U(e)?.toLowerCase().replace(/_/g,`-`);return n===void 0?null:t[n]??null}function Mi(e){return ji(e,Di)}function Ni(e){return ji(e,Oi)}var Pi=class{last=/* @__PURE__ */ new Map;record(e,t,n=/* @__PURE__ */ new Date){let r=`${String(n.getHours()).padStart(2,`0`)}:${String(n.getMinutes()).padStart(2,`0`)}`;this.last.set(e??``,{resource:t.join(`, `),time:r})}lastOf(e){let t=this.last.get(e??``);return t?`${t.resource} at ${t.time}`:void 0}};function Fi(e,t){let n=e.config.values(t),r=Kr(n.deployment),i=Kr(r.auth);return{profile:t,engine:Mi(n.engine)??e.detected,url:U(r.url)??``,name:U(r.name)??`Penstock deployment`,tenantId:U(r.tenantId)??``,source:U(r.source)??`penstock`,changedOnly:typeof r.changedOnly!=`boolean`||r.changedOnly,forTests:r.forTests===!0,activationTime:U(r.activationTime)??``,authType:Ai(U(i.type)),username:U(i.username)??``,clientId:U(i.clientId)??``,tokenUrl:U(i.tokenUrl)??``,audience:U(i.audience)??``}}async function Ii(e,t){return t.url?t.authType===`basic`?!!t.username&&await e.secrets.get(t.profile,`password`)!==void 0:t.authType!==`oauth`||!!t.clientId&&!!t.tokenUrl&&await e.secrets.get(t.profile,`clientSecret`)!==void 0:!1}async function Li(e){let t=[null,...e.config.profiles()],n=await Promise.all(t.map(async t=>{let n=Fi(e,t),r={profile:t,url:n.url||null,ready:await Ii(e,n),deployment:{name:n.name,source:n.source,tenantId:n.tenantId||null,changedOnly:n.changedOnly,forTests:n.forTests,activationTime:n.activationTime||null}};n.engine&&(r.engine=n.engine);let i=e.history?.lastOf(t);return i&&(r.lastDeploy=i),r}));return{active:e.config.activeProfile(),targets:n}}async function Ri(e,t){let n=Fi(e,t);return{profile:t,url:n.url||null,authType:n.authType,username:n.username||null,clientId:n.clientId||null,tokenUrl:n.tokenUrl||null,audience:n.audience||null,passwordSaved:await e.secrets.get(t,`password`)!==void 0,clientSecretSaved:await e.secrets.get(t,`clientSecret`)!==void 0}}function zi(e,t){return t==null?e.config.activeProfile():t===``?null:t}function Bi(e){return e.profile===null?f(`app.vscode.deploy.deploymentSection`):`profile ${e.profile}`}const Vi=/^[A-Za-z0-9_.-]{1,64}$/;function Hi(e,t){let n=``;try{let e=JSON.parse(t).error;typeof e==`string`&&Vi.test(e)&&(n=e)}catch{}return n?f(`app.vscode.deploy.tokenAnsweredWith`,{status:e,code:n}):f(`app.vscode.deploy.tokenAnswered`,{status:e})}async function Ui(e,t,n){let r=new URLSearchParams({grant_type:`client_credentials`,client_id:e.clientId,client_secret:t});e.audience&&r.set(`audience`,e.audience);let i;try{i=await n(e.tokenUrl,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:r.toString(),signal:AbortSignal.timeout(15e3)})}catch(t){throw Error(`Could not reach the token endpoint ${e.tokenUrl}: ${t instanceof Error?t.message:String(t)}`)}let a=await i.text();if(!i.ok)throw Error(Hi(i.status,a));let o;try{o=JSON.parse(a).access_token}catch{o=void 0}if(typeof o!=`string`)throw Error(`The token endpoint's answer has no access_token`);return o}async function Wi(e,t){if(t.authType===`basic`){let n=await e.secrets.get(t.profile,`password`);if(n===void 0)throw Error(f(`app.vscode.deploy.noPassword`,{user:t.username,where:Bi(t)}));return{Authorization:`Basic ${Buffer.from(`${t.username}:${n}`).toString(`base64`)}`}}if(t.authType===`oauth`){let n=await e.secrets.get(t.profile,`clientSecret`);if(n===void 0)throw Error(f(`app.vscode.deploy.noClientSecret`,{where:Bi(t)}));return{Authorization:`Bearer ${await Ui(t,n,e.fetch??fetch)}`}}return{}}async function Gi(e,t){let n=Fi(e,zi(e,t));if(!n.url)throw Error(f(`app.vscode.deploy.noEngineAddress`,{where:Bi(n)}));return{base:(n.engine===`CAMUNDA_8`?yi:vi)(n.url),headers:await Wi(e,n),forTests:n.forTests}}async function Ki(e,t,n){let r=n.authType??`none`,i=async(n,r,i)=>{i?r&&await e.set(t,n,r):await e.set(t,n,null)};await i(`password`,n.password,r===`basic`),await i(`clientSecret`,n.clientSecret,r===`oauth`)}function qi(e,t){let n=v.relative(t,e);return n===``||n!==`..`&&!n.startsWith(`..${v.sep}`)&&!v.isAbsolute(n)}const Ji=v.join(`.camunda`,`element-templates`),Yi=/* @__PURE__ */ new Map;function Xi(e,t,n){let r;try{r=Pt(e,{withFileTypes:!0})}catch{return}for(let i of r){let r=v.join(e,i.name);i.isFile()&&i.name.endsWith(`.json`)?n.push(r):i.isDirectory()&&t<8&&Xi(r,t+1,n)}}function Zi(e){if(H(e)){let t=[];return Xi(e,1,t),t.sort().slice(0,512)}return Mr(e)?[e]:[]}function Qi(e,t,n){let r=t.trim();if(!r)return null;try{let t=S(e),i=S(v.resolve(t,r));return!n.has(r)&&!qi(i,t)?null:i}catch{return null}}function $i(e,t){let n=[],r=t?v.dirname(t):e;for(;;){let t=v.join(r,Ji);H(t)&&n.push(t);let i=v.dirname(r);if(r===e||i===r)break;r=i}return n}function ea(e){try{let t=C(e);if(t.size>10485760)return console.warn(`Element template file too large, skipping: ${e}`),[];let n=Yi.get(e);if(n&&n.modified===t.mtimeMs)return n.templates;let r=JSON.parse(x(e,`utf8`)),i=(Array.isArray(r)?r:[r]).filter(e=>typeof e==`object`&&!!e&&!Array.isArray(e));return Yi.set(e,{modified:t.mtimeMs,templates:i}),i}catch(t){return console.error(`Error processing element template file: ${e}`,t),[]}}function ta(e,t,n,r=/* @__PURE__ */ new Set){let i=[...n.flatMap(t=>Qi(e,t,r)??[]),...$i(e,t)];return[...new Set(i.flatMap(Zi))].flatMap(ea)}function na(e){if(e.pid!==void 0){if(process.platform===`win32`)Vt(`taskkill`,[`/T`,`/F`,`/PID`,String(e.pid)],{stdio:`ignore`});else try{process.kill(-e.pid,`SIGKILL`)}catch{e.kill(`SIGKILL`)}}}function ra(e,t){let n=e.hooks;if(!n||typeof n!=`object`||Array.isArray(n))return;let r=n[t];return typeof r==`string`&&r.trim()?r.trim():void 0}function ia(e,t){let n={};for(let[r,i]of Object.entries(e))i!==void 0&&(!r.startsWith(`PENSTOCK_`)||r in t)&&(n[r]=i);return{...n,...t}}function aa(e,t,n,r){let i=ra(r.values,e);if(!i)return Promise.resolve({ok:!0,lines:[]});if(!r.trusted)return Promise.resolve({ok:!1,lines:[`hook ${e}: not run, because the workspace is not trusted`]});let a=process.platform===`win32`?[`cmd`,`/c`,i]:[`/bin/sh`,`-c`,i];return new Promise(o=>{let s=Vt(a[0],a.slice(1),{cwd:r.root,env:ia(r.env??process.env,{PENSTOCK_FILES:t.join(`
8
8
  `),PENSTOCK_ROOT:r.root,PENSTOCK_STAGE:e,PENSTOCK_PROFILE:n??``}),stdio:[`ignore`,`pipe`,`pipe`],detached:process.platform!==`win32`}),c=``,l=!1,u=!1,d=()=>{u=!0,na(s)};r.signal?.addEventListener(`abort`,d,{once:!0});let f=!1,p=e=>{let t=1e6-c.length,n=e.toString(`utf8`);n.length>t&&(f=!0),t>0&&(c+=n.slice(0,t))};s.stdout.on(`data`,p),s.stderr.on(`data`,p);let m=setTimeout(()=>{l=!0,na(s)},r.timeoutMs??12e4),ee=(t,n)=>{clearTimeout(m),r.signal?.removeEventListener(`abort`,d);let a=[`hook ${e}: ${i}`],s=c.trimEnd();s&&a.push(...s.split(`
9
- `).map(e=>` ${e}`)),f&&a.push(` output cut off`),n&&a.push(` ${n.message}`);let p=!l&&!u&&!n&&t===0;!p&&!n&&a.push(l?` timed out`:u?` cancelled`:` exited ${t}`),o({ok:p,lines:a})};r.signal?.aborted&&d(),s.on(`error`,e=>ee(null,e)),s.on(`close`,e=>ee(e))})}function oa(e=process.env){return s(e)}function sa(e){return v.join(e,`license.json`)}function ca(e){try{if(!b(e))return null;let t=JSON.parse(x(e,`utf8`));return typeof t.token==`string`?t.token:null}catch{return null}}function la(e,t,i=n,a=Date.now()){let o=ca(sa(e));if(!o)return{token:null,machine:t};let s=r(o,{machine:t,now:a,keys:i});return s.status!==`valid`||s.claims.source===`pipeline`?{token:null,machine:t}:{token:o,machine:t}}function ua(e){return e?`RIGHT`:`LEFT`}const da=/* @__PURE__ */ new Set([`AUTO_LAYOUT`,`CODE_LINKS`,`CONVENTIONS`,`FLOW_ANALYSIS`,`MIGRATION`,`TEST_RUNS`,`AI_CHAT`,`VARIABLE_CHECKS`]),G=/* @__PURE__ */ new WeakMap;function fa(e,t=Date.now()){let n=G.get(e);if(n&&t-n.at<5e3)return n.state;let r=d({env:e.env});return G.set(e,{at:t,state:r}),r.catch(()=>{G.get(e)?.state===r&&G.delete(e)}),r}function pa(e){G.delete(e)}async function K(e){return u[(await fa(e)).tier]>=u.pro}async function ma(e){let t=await fa(e),n=t.tier===`team`?`TEAM`:t.tier===`pro`?`PRO`:`FREE`,r=t.source===`trial`&&t.trialEndsAt?Math.max(0,Math.ceil((Date.parse(t.trialEndsAt)-Date.now())/864e5)):void 0,i=c({env:e.env});return{tier:n,detail:t.detail,trialDaysLeft:r,trialEndsAt:t.trialEndsAt??null,token:la(oa(e.env),i).token,machine:i}}function ha(e){let t=ga(e).text(`theme`);return t===`light`?{theme:`LIGHT`,dark:!1}:t===`dark`?{theme:`DARK`,dark:!0}:t===`dracula`?{theme:`DRACULA`,dark:!0}:{theme:`SYSTEM`,dark:!1}}function ga(e){return new h(e.home)}const _a=[{method:`GET`,path:`/api/license`,operationId:`getLicense`,run:(e,t)=>ma(t)},{method:`POST`,path:`/api/license/feature`,operationId:`requestFeature`,run:async(e,t)=>{let n=R(L(e.body),`feature`);if(!da.has(n))throw I(400,`app.cli.web.reason.unknownFeature`,{feature:n.slice(0,60)});let r=n===`AI_CHAT`?m(await fa(t),{env:t.env}):await K(t),i=c({env:t.env});return{allowed:r,token:r?la(oa(t.env),i).token:null}}},{method:`POST`,path:`/api/license/offer`,operationId:`showLicenceOffer`,run:()=>({opened:!1})},{method:`GET`,path:`/api/theme`,operationId:`getTheme`,run:(e,t)=>({...ha(t),tokens:{}})},{method:`GET`,path:`/api/preferences`,operationId:`getPreferences`,run:(e,t)=>ee(t.home)?ga(t).read():{}},{method:`PUT`,path:`/api/preferences`,operationId:`savePreferences`,limit:N,run:(e,t)=>(L(e.body),ga(t).write(e.body))},{method:`GET`,path:`/api/host/dialog-order`,operationId:`getDialogButtonOrder`,run:()=>({primary:ua(process.platform===`darwin`)})}],va=33554432,ya=/^[\w .-]{1,80}$/,ba=/* @__PURE__ */ new Set([`CLASSIC_BPMN`,`CAMUNDA_7`,`CAMUNDA_8`,`OPERATON`,`CIB_SEVEN`,`FLOWABLE`,`ACTIVITI`]),xa=/* @__PURE__ */ new Set([`NONE`,`GROOVY`,`JAVASCRIPT`]),Sa=/* @__PURE__ */ new Set([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`]),Ca=/* @__PURE__ */ new WeakMap,q=/* @__PURE__ */ new WeakMap;function J(e,...t){let n=t.find(e=>typeof e==`string`&&e!==``);return n?e.confine.resolve(n):null}async function wa(e){if(!e)return``;try{let t=await k(e);if(!t.isFile())return``;if(t.size>va)throw I(413,`app.cli.web.reason.fileTooLarge`,{limit:va/1048576});return await Xt(e,`utf8`)}catch(e){if(e instanceof F)throw e;return``}}function Ta(e,t,n){let r=et(n);return{config:e.configs.viewFor(t),detected:r?Mi(r)??null:null,secrets:e.secrets,history:e.history,fetch:e.fetch}}async function Ea(e,t){return Ta(e,t,await wa(t))}async function Da(e,t,n,r){let i;try{i=await Gi(await Ea(e,r),n)}catch(e){throw new F(409,e instanceof Error?e.message:String(e))}try{return await Ei(t,i,e.fetch)}catch(e){throw new F(502,e instanceof Error?e.message:String(e))}}function Oa(e){if(e==null||e===``)return null;if(typeof e!=`string`||!ya.test(e))throw I(400,`app.cli.web.reason.badProfile`);return e}function ka(e,t){if(e==null||e===``)return null;if(typeof e!=`string`)throw I(400,`app.cli.web.reason.wrongField`,{field:t});try{let t=new URL(e.trim());if(t.protocol===`http:`||t.protocol===`https:`)return e.trim()}catch{}throw I(400,`app.cli.web.reason.notAnAddress`,{field:t})}function Aa(e,t){let n=z(e,t);return n===void 0||n===``?null:n}function ja(e){let t=L(e),n=t.authType??`none`;if(typeof n!=`string`||!ki.includes(n))throw I(400,`app.cli.web.reason.wrongField`,{field:`authType`});return{profile:Oa(t.profile),url:ka(t.url,`url`),authType:n,username:Aa(t,`username`),clientId:Aa(t,`clientId`),tokenUrl:ka(t.tokenUrl,`tokenUrl`),audience:Aa(t,`audience`),password:Aa(t,`password`),clientSecret:Aa(t,`clientSecret`)}}function Ma(e,t){if(!t)return null;let n=v.resolve(e,t);return or(n,e)&&Mr(n)?n:null}function Na(e,t){let n=t?v.dirname(t):e,r=v.join(n,`.camunda`,`element-templates`);for(;;){let t=v.join(n,`.camunda`,`element-templates`);if(H(t))return t;if(n===e||v.dirname(n)===n)return r;n=v.dirname(n)}}function Pa(e,t){let n=Ca.get(e)??/* @__PURE__ */ new Map;Ca.set(e,n);for(let{file:r,problems:i}of e.configs.viewFor(t).problems()){let t=`${String(Mr(r)?`present`:`gone`)}:${i.map(e=>JSON.stringify(e)).join(`|`)}`;if(n.get(r)===t)continue;n.set(r,t);let a=v.relative(e.folder,r)||v.basename(r);e.say([f(`app.config.brokenTitle`,{0:a}),...i.flatMap(e=>pt(e,a,`stopped`))].join(`
10
- `))}}async function Fa(t,n){let r=J(n,t.resource),i=n.configs.viewFor(r);Pa(n,r);let a=i.values(),o=await wa(r),s=Qe(U(a.engine))??et(o),c=Kr(a.lint),l=Kr(a.conventions),u=Object.keys(l).length>0&&await K(n),d=Array.isArray(a.elementTemplates)?a.elementTemplates.filter(e=>typeof e==`string`):[],f=new h(n.home).text(`theme`);return{theme:f===`light`?`LIGHT`:f===`dark`?`DARK`:f===`dracula`?`DRACULA`:`SYSTEM`,locale:p(),engine:s?$e(s):null,scriptType:Ni(a.scriptType)??`NONE`,bpmnLint:{configPath:Ma(n.folder,U(c.configPath))??Ma(n.folder,`.bpmnlintrc`),clientBundlePath:Ma(n.folder,U(c.clientBundlePath))},elementTemplates:d,elementTemplatesContent:ta(n.folder,r,d,i.machineLocalEntries(`elementTemplates`)),elementTemplatesFolder:Na(n.folder,r),project:v.basename(n.folder),bpmnFilePath:r??``,bpmnXml:o,conventions:u?l:null,palette:lt(a.palette),pluginVersion:e()??null}}function Ia(e,t){let n=L(t),r=R(n,`engine`),i=R(n,`scriptType`);if(!ba.has(r))throw I(400,`app.cli.web.reason.wrongField`,{field:`engine`});if(!xa.has(i))throw I(400,`app.cli.web.reason.wrongField`,{field:`scriptType`});return{engine:r,scriptType:i,elementTemplates:dr(n,`elementTemplates`).map(t=>{let n=e.confine.resolve(t);return e.confine.relative(n)||`.`})}}function La(e){if(e.parts===void 0||e.parts===null)return;let t=V(e,`parts`);if(t.length>64)throw I(400,`app.cli.web.reason.tooMany`);return t.map(e=>{let t=L(e);return{name:R(t,`name`),filename:z(t,`filename`),contentType:z(t,`contentType`),content:R(t,`content`)}})}async function Ra(e,t){let n=L(e.body),r=R(n,`method`);if(!Sa.has(r))throw I(400,`app.cli.web.reason.wrongField`,{field:`method`});let i={method:r,path:R(n,`path`),body:z(n,`body`),parts:La(n),testRun:B(n,`testRun`)};try{Ci(i)}catch{throw I(400,`app.cli.web.reason.badEnginePath`)}return Da(t,i,Oa(n.profile),J(t,z(n,`resource`),e.resource))}async function za(e,t){let n=L(e.body),r=R(n,`stage`);if(r!==`preDeploy`&&r!==`postDeploy`)throw I(400,`app.cli.web.reason.wrongField`,{field:`stage`});let i=dr(n,`resources`);if(i.length>1e3)throw I(400,`app.cli.web.reason.tooMany`);let a=i.map(e=>t.confine.resolve(e)),o=Oa(n.profile),s=J(t,z(n,`resource`),e.resource);if((q.get(t)??0)>=4)throw I(429,`app.cli.web.reason.tooManyHooks`);let c=t.configs.viewFor(s).values(o),l=ra(c,r);return q.set(t,(q.get(t)??0)+1),{run:t.hooks.start(async e=>{try{if(!l)return{ok:!0,lines:[]};let n=await vt(t.folder,r,l,void 0,t.env);return n.allowed?await aa(r,a,o,{root:t.folder,values:c,trusted:!0,signal:e,env:t.env}):{ok:!1,lines:n.lines}}finally{q.set(t,Math.max(0,(q.get(t)??1)-1))}})}}const Ba=[{method:`GET`,path:`/api/config`,operationId:`getConfig`,run:Fa},{method:`POST`,path:`/api/config`,operationId:`saveConfig`,limit:N,run:(e,t)=>{oi(t.folder,Ia(t,e.body)),t.configs.invalidate()}},{method:`GET`,path:`/api/deploy/targets`,operationId:`getDeployTargets`,run:async(e,t)=>Li(await Ea(t,J(t,e.query.get(`resource`),e.resource)))},{method:`GET`,path:`/api/deploy/settings`,operationId:`getDeploymentSettings`,run:async(e,t)=>Ri(await Ea(t,J(t,e.resource)),Oa(e.query.get(`profile`)))},{method:`POST`,path:`/api/deploy/settings`,operationId:`saveDeploymentSettings`,limit:N,run:async(e,t)=>{let n=ja(e.body);ri(t.folder,n.profile,n),await Ki(t.secrets,n.profile,n),t.configs.invalidate()}},{method:`POST`,path:`/api/host/engine`,operationId:`askEngine`,limit:P,run:Ra},{method:`POST`,path:`/api/host/hook`,operationId:`runHook`,limit:N,run:za},{method:`GET`,path:`/api/host/hook/{run}`,operationId:`hookState`,run:(e,t)=>{let n=t.hooks.state(e.params.run);if(!n)throw I(404,`app.cli.web.reason.noSuchRun`);return n}},{method:`DELETE`,path:`/api/host/hook/{run}`,operationId:`cancelHook`,run:(e,t)=>t.hooks.cancel(e.params.run)},{method:`POST`,path:`/api/host/deployed`,operationId:`recordDeployment`,limit:N,run:(e,t)=>{let n=L(e.body);t.history.record(Oa(n.profile),dr(n,`resources`))}}],Va=67108864,Ha=16777216,Ua=/^[A-Za-z0-9-]{1,64}$/,Wa=/^[a-z0-9-]{1,120}$/;function Ga(e){return Math.floor(e.mtimeMs)}async function Ka(e,t,n=async()=>void 0){if((typeof t==`string`?Buffer.byteLength(t):t.length)>16777216)throw I(413,`app.cli.web.reason.fileTooLarge`,{limit:Ha/1048576});let r=await k(e).catch(()=>null);if(r?.isDirectory())throw I(400,`app.cli.web.reason.isAFolder`);let i=v.join(v.dirname(e),`.${v.basename(e)}.${process.pid}.${Ut(4).toString(`hex`)}.tmp`);try{await $t(i,t,{mode:r?r.mode&511:420});let a=Ga(await k(i));return await n(),await D(i,e),a}catch(e){throw await O(i,{force:!0}).catch(()=>void 0),e}}async function qa(e,t,n){let r=e.confine.resolve(t),i=await k(r);if(i.isDirectory())throw I(400,`app.cli.web.reason.isAFolder`);if(i.size>67108864)throw I(413,`app.cli.web.reason.fileTooLarge`,{limit:Va/1048576});let a=await Xt(r);return n?{content:a.toString(`base64`),isBase64:!0}:{content:a.toString(`utf8`)}}function Ja(e,t){e.project.invalidate(),e.changed([t]).catch(()=>void 0)}async function Ya(e,t,n,r){let i=e.confine.resolve(t);e.confine.writable(i,String(t));let a=r?Buffer.from(n,`base64`):n;await T(v.dirname(i),{recursive:!0}),await Ka(i,a),Ja(e,i)}async function Xa(e,t,n,r){let i=e.confine.resolve(t);e.confine.writable(i,String(t)),await T(v.dirname(i),{recursive:!0});let a=await Ka(i,n,async()=>{if(r===null)return;let t=await k(i).catch(()=>null);if(!t||Ga(t)!==r)throw I(409,`app.cli.web.reason.changedOnDisk`,{path:e.confine.relative(i).slice(0,200)})});return Ja(e,i),a}async function Za(e,t){let n=await Jt(e,y.O_WRONLY|y.O_CREAT|y.O_EXCL,420);try{await n.writeFile(t,`utf8`)}finally{await n.close()}}async function Qa(e,t,n){if(e.confine.resolve(t)!==e.folder)throw I(400,`app.cli.web.reason.notTheProject`,{path:String(t).slice(0,200)});if(n.length===0||n.length>500)throw I(400,`app.cli.web.reason.badFileList`);let r=[];for(let t of n){let n=L(t),i=R(n,`path`);if(/^[/\\]/.test(i)||/^[A-Za-z]:/.test(i))throw I(403,`app.cli.web.reason.outside`,{path:i.slice(0,200)});let a=e.confine.resolve(i);e.confine.writable(a,i);let o=R(n,`content`);if(Buffer.byteLength(o)>16777216)throw I(413,`app.cli.web.reason.fileTooLarge`,{limit:Ha/1048576});if(r.some(e=>e.target===a))throw I(409,`app.cli.web.reason.listedTwice`,{path:i.slice(0,200)});r.push({target:a,content:o,shown:i})}let i=[];try{for(let{target:e,content:t,shown:n}of r){await T(v.dirname(e),{recursive:!0});try{await Za(e,t)}catch(e){throw e.code===`EEXIST`?I(409,`app.cli.web.reason.alreadyExists`,{path:n.slice(0,200)}):e}i.push(e)}}catch(e){throw await Promise.all(i.map(e=>Qt(e).catch(()=>void 0))),e}}async function $a(e,t,n,r){if(!Ua.test(t)||!Wa.test(n))throw I(400,`app.cli.web.reason.badTraceName`);let i=v.join(e.folder,`.penstock`,`runs`),a=v.join(i,t),o=e.confine.resolve(a);await T(o,{recursive:!0}),await $t(v.join(i,`.gitignore`),`*
11
- `);let s=v.join(o,`${n}.json`);return await Ka(s,r),s}const eo=[{method:`POST`,path:`/api/file/read`,operationId:`readFile`,run:(e,t)=>{let n=L(e.body);return qa(t,n.path,B(n,`asBase64`))}},{method:`POST`,path:`/api/file/save`,operationId:`saveFile`,limit:P,run:async(e,t)=>{let n=L(e.body);await Ya(t,n.path,R(n,`content`),B(n,`isBase64`))}},{method:`POST`,path:`/api/file/create-project-files`,operationId:`createProjectFiles`,limit:P,run:async(e,t)=>{let n=L(e.body);await Qa(t,n.root,V(n,`files`))}},{method:`POST`,path:`/api/host/run-trace`,operationId:`saveRunTrace`,limit:P,run:async(e,t)=>{let n=L(e.body);return{path:await $a(t,R(n,`runId`),R(n,`name`),R(n,`content`))}}},{method:`GET`,path:`/api/project/files`,operationId:`getProjectFiles`,run:(e,t)=>t.project.listing()}];function to(e){return e.replace(/[\u0000-\u001f\u007f]+/g,` `).slice(0,500)}function no(e){try{let t=new URL(e);if(t.protocol===`https:`||t.protocol===`http:`)return t.href}catch{}throw I(400,`app.cli.web.reason.notWebAddress`,{url:to(e).slice(0,120)})}const ro=[{method:`POST`,path:`/api/host/notify`,operationId:`notifyUser`,limit:N,run:(e,t)=>{let n=L(e.body),r=to(R(n,`text`));B(n,`error`),t.say(r)}},{method:`POST`,path:`/api/host/open-link`,operationId:`openExternalLink`,limit:N,run:async(e,t)=>{await t.openLink(no(R(L(e.body),`url`)))}},{method:`POST`,path:`/api/host/test-output`,operationId:`sendTestOutput`,limit:N,run:()=>void 0},{method:`POST`,path:`/api/actions`,operationId:`publishActions`,limit:N,run:()=>void 0},{method:`POST`,path:`/api/view/code-lenses`,operationId:`publishCodeLenses`,limit:N,run:()=>void 0},{method:`GET`,path:`/vscode/events`,operationId:`nextHostEvent`,held:!0,run:(e,t)=>t.events.next(e.client,e.signal)}],io=/* @__PURE__ */ new Set([`PROCESS`,`ELEMENT`,`JOB_TYPE`,`TOPIC`,`MESSAGE`,`SIGNAL`,`DECISION`,`FORM`,`CLASS`,`BEAN`,`VARIABLE`,`ERROR`]);function ao(e){let t=L(e),n=R(t,`kind`);if(!io.has(n))throw I(400,`app.cli.web.reason.wrongField`,{field:`kind`});return{kind:n,value:R(t,`value`)}}function oo(e,t,n){return{precise:!1,results:t.flatMap(t=>{let r=n.paid?bt(e,t,e=>yt(e.file,e.line)).map(({implements:e,...t})=>({...t,implementation:e})):[],i=ze(e,t).map(e=>({path:e.file,line:e.line,offset:e.offset}));return r.length>0||i.length>0?[{kind:t.kind,value:t.value,links:r,places:i}]:[]}),...n.names?{names:bn(e).map(e=>({...e,origin:`code`}))}:{}}}const so=[{method:`POST`,path:`/api/project/code`,operationId:`findCode`,limit:N,run:async(e,t)=>{let n=L(e.body),r=V(n,`subjects`).map(ao);if(r.length>2e3)throw I(400,`app.cli.web.reason.tooMany`);let{index:i,sources:a}=await t.code.state(()=>t.project.listing()),o=oo(i,r,{paid:await K(t),names:n.names===!0});if(n.facts!==!0)return o;let s=o.results.flatMap(e=>e.places.map(e=>({file:e.path,offset:e.offset})));return{...o,facts:await wt(a,s)}}},{method:`POST`,path:`/api/project/worker-variables`,operationId:`findWorkerVariables`,run:async(e,t)=>{let{values:n}=_t(t.folder),r=m(await fa(t),{env:t.env}),{workers:i}=await t.code.state(()=>t.project.listing());return Ae(i,{codeLinks:await K(t),values:n,entitled:r})}},{method:`POST`,path:`/api/project/snapshot`,operationId:`reportSnapshot`,limit:P,run:()=>void 0},{method:`POST`,path:`/api/project/findings`,operationId:`reportFindings`,limit:P,run:()=>void 0},{method:`GET`,path:`/api/debug/state`,operationId:`getDebugState`,run:()=>({positions:[]})}];function Y(e,t,n,r){return{method:e,path:t,operationId:n,run:()=>{throw I(501,`app.cli.web.unsupported.${r}`)}}}const co=[Y(`POST`,`/api/script`,`createScript`,`script`),Y(`POST`,`/api/script/slot`,`reportScriptSlot`,`script`),Y(`GET`,`/api/preview-diff`,`getPreviewDiff`,`diff`),Y(`POST`,`/api/diff/open`,`openDiff`,`diff`),Y(`GET`,`/api/clipboard`,`getClipboard`,`clipboard`),Y(`POST`,`/api/clipboard`,`saveClipboard`,`clipboard`),Y(`POST`,`/api/clipboard/image`,`saveClipboardImage`,`clipboard`),Y(`POST`,`/api/file/choose`,`chooseFile`,`chooser`),Y(`POST`,`/api/navigate/class`,`navigateToClass`,`navigation`),Y(`POST`,`/api/view/tool-window`,`publishToolWindow`,`view`),Y(`POST`,`/api/host/reveal`,`revealElement`,`reveal`),Y(`POST`,`/api/host/open-code`,`openCode`,`navigation`),Y(`POST`,`/api/host/run-tests`,`runTestHandles`,`tests`),Y(`POST`,`/api/host/linked-rename`,`offerLinkedRename`,`rename`),Y(`POST`,`/api/host/confirm`,`confirmWithUser`,`confirm`),Y(`POST`,`/api/host/migration-preview`,`previewMigration`,`migration`),Y(`GET`,`/api/host/migration-answer`,`getMigrationAnswer`,`migration`),Y(`PUT`,`/vscode/document`,`saveDocumentText`,`document`),Y(`POST`,`/vscode/undo`,`undo`,`document`),Y(`POST`,`/vscode/redo`,`redo`,`document`)],lo={files:2e4,bytes:1073741824,depth:40};var uo=class extends Error{};const fo=/* @__PURE__ */ new Set([`.DS_Store`,`Thumbs.db`]),po=4294967295,mo=mn(nn);async function ho(e,t=lo,n){let r=[],i=0,a=[{directory:e,depth:0}];for(;a.length>0;){if(n?.aborted)throw Error(`cancelled`);let{directory:o,depth:s}=a.pop(),c;try{c=await Yt(o)}catch{continue}try{for await(let n of c){let c=v.join(o,n.name);if(!n.isSymbolicLink()){if(n.isDirectory()){if(_.has(n.name)||s>=t.depth)continue;a.push({directory:c,depth:s+1})}else if(n.isFile()&&!fo.has(n.name)&&!/\.tmp$/.test(n.name)){let n;try{n=await k(c)}catch{continue}if(r.length>=t.files||n.size>po||i+n.size>t.bytes)throw new uo;i+=n.size,r.push({rel:v.relative(e,c).split(v.sep).join(`/`),absolute:c,size:n.size,modified:n.mtimeMs})}}}}finally{await c.close().catch(()=>void 0)}}return r.sort((e,t)=>e.rel<t.rel?-1:+(e.rel>t.rel))}function go(e){let t=new Date(e),n=Math.min(2107,Math.max(1980,t.getFullYear()));return{time:t.getHours()<<11|t.getMinutes()<<5|t.getSeconds()>>1,date:n-1980<<9|t.getMonth()+1<<5|t.getDate()}}const _o=2056;function vo(e,t){let n=Buffer.alloc(30+e.length);return n.writeUInt32LE(67324752,0),n.writeUInt16LE(20,4),n.writeUInt16LE(_o,6),n.writeUInt16LE(8,8),n.writeUInt16LE(t.time,10),n.writeUInt16LE(t.date,12),n.writeUInt16LE(e.length,26),e.copy(n,30),n}function yo(e,t,n){let r=Buffer.alloc(16);return r.writeUInt32LE(134695760,0),r.writeUInt32LE(e>>>0,4),r.writeUInt32LE(t,8),r.writeUInt32LE(n,12),r}function bo(e){let t=Buffer.alloc(46+e.name.length);return t.writeUInt32LE(33639248,0),t.writeUInt16LE(788,4),t.writeUInt16LE(20,6),t.writeUInt16LE(_o,8),t.writeUInt16LE(8,10),t.writeUInt16LE(e.stamp.time,12),t.writeUInt16LE(e.stamp.date,14),t.writeUInt32LE(e.crc>>>0,16),t.writeUInt32LE(e.compressed,20),t.writeUInt32LE(e.size,24),t.writeUInt16LE(e.name.length,28),t.writeUInt32LE(33188<<16>>>0,38),t.writeUInt32LE(e.offset,42),e.name.copy(t,46),t}function xo(e,t,n){let r=Buffer.alloc(22);return r.writeUInt32LE(101010256,0),r.writeUInt16LE(e,8),r.writeUInt16LE(e,10),r.writeUInt32LE(t,12),r.writeUInt32LE(n,16),r}async function*So(e,t){let n=[],r=0,i=e=>(r+=e.length,e);for(let a of e){let e=Buffer.from(`${t}/${a.rel}`,`utf8`),o=go(a.modified),s=r;yield i(vo(e,o));let c=0,l=0,u=0;if(a.size<=524288){let e=await Xt(a.absolute),t=await mo(e);c=en(e),l=e.length,u=t.length,yield i(t)}else{let e=jt(a.absolute),t=tn();e.on(`data`,e=>{let t=e;c=en(t,c),l+=t.length});let n=pn(e,t);n.catch(()=>void 0);for await(let e of t)u+=e.length,yield i(e);await n}if(l>po||u>po)throw new uo;yield i(yo(c,u,l)),n.push({name:e,stamp:o,crc:c,compressed:u,size:l,offset:s})}let a=r;for(let e of n)yield i(bo(e));yield i(xo(n.length,r-a,a))}function Co(e,t){return dn.from(So(e,t),{objectMode:!1})}function wo(e){return`attachment; filename="${e.replace(/[^\x20-\x7e]|["\\;]/g,`_`)}"; filename*=UTF-8''${encodeURIComponent(e).replace(/['()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}`}const To=[{method:`GET`,path:`/web/project/archive`,operationId:`downloadProjectArchive`,run:async(e,t)=>{let n=e.query.get(`expect`);if(n&&n!==t.id)throw I(409,`app.cli.web.reason.projectChanged`);if(!t.confine.stands())throw I(409,`app.cli.web.reason.projectGone`);let r=v.basename(t.folder)||`project`,i;try{i=await ho(t.folder,void 0,e.signal)}catch(e){throw e instanceof uo?I(413,`app.cli.web.reason.archiveTooLarge`,{files:2e4,size:1}):e}return new Or({"Content-Type":`application/zip`,"Content-Disposition":wo(`${r}.zip`),"X-Content-Type-Options":`nosniff`},Co(i,r))}}],Eo=/[\\/\u0000-\u001f\u007f:*?"<>|]/,Do=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i,Oo=/\.(bpmn\.xml|bpmn20\.xml|bpmn|dmn|form|json|ya?ml)$/i;function ko(e){return e.trim()===``?`empty`:Eo.test(e)?`characters`:e===`.`||e===`..`||e.endsWith(`.`)||e.endsWith(` `)||e.startsWith(` `)?`dots`:Do.test(e)?`reserved`:Buffer.byteLength(e)>255?`long`:null}const Ao={empty:`app.cli.web.reason.nameEmpty`,characters:`app.cli.web.reason.nameCharacters`,dots:`app.cli.web.reason.nameDots`,reserved:`app.cli.web.reason.nameReserved`,long:`app.cli.web.reason.nameLong`};function jo(e){return Ao[e]}function Mo(e,t){let n=Oo.exec(e)?.[0]??``,r=e.slice(0,e.length-n.length);return t<=1?`${r} copy${n}`:`${r} copy ${t}${n}`}const No=/* @__PURE__ */ new Set([`EPERM`,`ENOTSUP`,`EOPNOTSUPP`,`EINVAL`,`ENOSYS`,`EXDEV`,`EMLINK`]);function X(e){return e.replace(/[\u0000-\u001f\u007f]/g,`?`).slice(0,200)}function Po(e){if(e==null)return null;if(typeof e!=`number`||!Number.isFinite(e))throw I(400,`app.cli.web.reason.wrongField`,{field:`stamp`});return e}function Fo(e){let t=ko(e);if(t)throw I(400,jo(t),{name:X(e)})}function Io(e,t){if(e.confine.segments(t).some(e=>_.has(e)||e.startsWith(`.`)))throw I(403,`app.cli.web.reason.notEditable`,{path:X(e.confine.relative(t))})}async function Lo(e,t,n,r){let i=e.confine.resolve(t);if(i===e.folder)throw I(400,`app.cli.web.reason.notTheRoot`);let a=await w(i).catch(()=>null);if(!a)throw I(404,`app.cli.web.reason.noSuchFile`);if(a.isSymbolicLink())throw I(400,`app.cli.web.reason.isALink`,{path:X(String(t))});if(a.isDirectory()){if(r===`file`)throw I(400,`app.cli.web.reason.isAFolder`);Io(e,i)}else if(a.isFile()){if(e.confine.writable(i,String(t))===`penstock`)throw I(403,`app.cli.web.reason.notEditable`,{path:X(String(t))});if(n!==null&&Math.floor(a.mtimeMs)!==n)throw I(409,`app.cli.web.reason.changedOnDisk`,{path:X(e.confine.relative(i))})}else throw I(400,`app.cli.web.reason.notEditable`,{path:X(String(t))});return{target:i,info:a,shown:e.confine.relative(i)}}async function Ro(e,t){let[n,r]=await Promise.all([w(e).catch(()=>null),w(t).catch(()=>null)]);return!!n&&!!r&&n.ino!==0&&n.ino===r.ino&&n.dev===r.dev}async function zo(e,t,n){if(await w(t).catch(()=>null)){if(e.toLowerCase()===t.toLowerCase()&&await Ro(e,t))return void await D(e,t);throw I(409,`app.cli.web.reason.alreadyExists`,{path:X(n)})}try{await qt(e,t)}catch(r){let i=r.code;if(i===`EEXIST`)throw I(409,`app.cli.web.reason.alreadyExists`,{path:X(n)});if(typeof i==`string`&&No.has(i))return void await D(e,t);throw r}await Qt(e)}async function Bo(e,t,n){if(await w(t).catch(()=>null)){if(e.toLowerCase()===t.toLowerCase()&&await Ro(e,t))return void await D(e,t);throw I(409,`app.cli.web.reason.alreadyExists`,{path:X(n)})}await D(e,t)}function Z(e,...t){e.project.invalidate(),e.changed(t).catch(()=>void 0)}async function Vo(e,t){let n=e.confine.resolve(t);if(n===e.folder)throw I(400,`app.cli.web.reason.notTheRoot`);let r=e.confine.segments(n);if(r.length>24)throw I(400,`app.cli.web.reason.tooDeep`);for(let e of r)if(Fo(e),_.has(e)||e.startsWith(`.`))throw I(403,`app.cli.web.reason.notEditable`,{path:X(String(t))});if(await w(n).catch(()=>null))throw I(409,`app.cli.web.reason.alreadyExists`,{path:X(e.confine.relative(n))});await T(n,{recursive:!0}),Z(e,n)}async function Ho(e,t,n,r){let i=await Lo(e,t,r,`any`);Fo(n);let a=v.join(v.dirname(i.target),n);if(a===i.target)return i.target;let o=e.confine.relative(a);if(i.info.isDirectory()){if(_.has(n)||n.startsWith(`.`))throw I(403,`app.cli.web.reason.notEditable`,{path:X(o)});await Bo(i.target,a,o)}else{let t=e.confine.writeKind(i.target),n=e.confine.writeKind(a);if(!n)throw I(403,`app.cli.web.reason.notEditable`,{path:X(o)});if(t!==n)throw I(400,`app.cli.web.reason.kindChange`,{path:X(o)});await zo(i.target,a,o)}return Z(e,i.target,a),a}async function Uo(e,t,n,r){let i=await Lo(e,t,r,`any`),a=e.confine.resolve(n===``?`.`:n);if(!(await w(a).catch(()=>null))?.isDirectory())throw I(404,`app.cli.web.reason.noSuchFolder`,{folder:X(n)});a!==e.folder&&Io(e,a);let o=v.join(a,v.basename(i.target));if(o===i.target)return o;if(i.info.isDirectory()&&or(a,i.target))throw I(400,`app.cli.web.reason.moveIntoItself`);let s=e.confine.relative(o);if(i.info.isDirectory())await Bo(i.target,o,s);else{if(!e.confine.writeKind(o))throw I(403,`app.cli.web.reason.notEditable`,{path:X(s)});await zo(i.target,o,s)}return Z(e,i.target,o),o}async function Wo(e,t){let n=await Lo(e,t,null,`file`);if(n.info.size>67108864)throw I(413,`app.cli.web.reason.fileTooLarge`,{limit:Va/1048576});let r=v.dirname(n.target),i=v.join(r,`.${v.basename(n.target)}.${process.pid}.${Ut(4).toString(`hex`)}.tmp`);try{await Kt(n.target,i,y.COPYFILE_EXCL);for(let t=1;t<=1e3;t+=1){let a=v.join(r,Mo(v.basename(n.target),t));if(!await w(a).catch(()=>null)){try{await zo(i,a,e.confine.relative(a))}catch(e){if(e.status===409)continue;throw e}return Z(e,a),a}}throw I(409,`app.cli.web.reason.exists`)}finally{await O(i,{force:!0}).catch(()=>void 0)}}async function Go(e,t,n=0,r={seen:0}){if(n>24)return!1;let i=await E(t,{withFileTypes:!0});for(let a of i){if(r.seen+=1,r.seen>5e3)return!1;let i=v.join(t,a.name);if(a.isSymbolicLink())return!1;if(a.isDirectory()){if(!await Go(e,i,n+1,r))return!1}else if(!a.isFile()||!e.confine.writeKind(i)||e.confine.writeKind(i)===`penstock`)return!1}return!0}async function Ko(e,t,n){let r=await Lo(e,t,n,`any`);if(r.info.isDirectory()){if(!await Go(e,r.target))throw I(409,`app.cli.web.reason.folderHoldsOthers`,{path:X(r.shown)});await O(r.target,{recursive:!0})}else await Qt(r.target);Z(e,r.target)}const qo=[{method:`POST`,path:`/web/files/create-folder`,operationId:`createFolder`,limit:N,run:async(e,t)=>{await Vo(t,R(L(e.body),`path`))}},{method:`POST`,path:`/web/files/rename`,operationId:`renameEntry`,limit:N,run:async(e,t)=>{let n=L(e.body);return{path:await Ho(t,R(n,`path`),R(n,`name`),Po(n.stamp))}}},{method:`POST`,path:`/web/files/move`,operationId:`moveEntry`,limit:N,run:async(e,t)=>{let n=L(e.body);return{path:await Uo(t,R(n,`path`),R(n,`folder`),Po(n.stamp))}}},{method:`POST`,path:`/web/files/save`,operationId:`saveProjectFile`,limit:P,run:async(e,t)=>{let n=L(e.body);return{stamp:await Xa(t,R(n,`path`),R(n,`content`),Po(n.stamp))}}},{method:`POST`,path:`/web/files/duplicate`,operationId:`duplicateEntry`,limit:N,run:async(e,t)=>({path:await Wo(t,R(L(e.body),`path`))})},{method:`POST`,path:`/web/files/delete`,operationId:`deleteEntry`,limit:N,run:async(e,t)=>{let n=L(e.body);await Ko(t,R(n,`path`),Po(n.stamp))}}];function Jo(e,t,n){let r=t&&b(t)?t:e,i=e??(r?ht(r):process.cwd()),a=r&&qi(v.resolve(r),v.resolve(i))&&b(r)?r:i,o=H(i)?ft(i,a):[],s=o.map(e=>({name:e,...ct(e)})),c=s.map(e=>({name:e.name,values:e.values})),l=dt(c);return{root:i,files:o,values(e){if(e===void 0)return st(c,n);let t={name:`profile`,values:{profile:e??``}};return st([...c,t],{...n,[gt]:void 0})},profiles:()=>ut(l),activeProfile:()=>mt(l,n),machineLocalEntries:e=>new Set(s.filter(e=>W.includes(v.basename(e.name))).flatMap(t=>Array.isArray(t.values[e])?t.values[e]:[]).filter(e=>typeof e==`string`&&e.trim()!==``).map(e=>e.trim())),problems:()=>s.filter(e=>e.problems.length>0).map(e=>({file:e.name,problems:e.problems}))}}var Yo=class{root;env;views=/* @__PURE__ */ new Map;builds=0;generation=0;constructor(e,t){this.root=e,this.env=t}invalidate(){this.generation+=1,this.views.clear()}viewFor(e){let t=e?v.dirname(e):this.root,n=this.views.get(t);if(n)return n;this.builds+=1;let r=Jo(this.root,e,this.env);return this.views.set(t,r),r}};const Xo={files:2e4,fileBytes:1048576,totalBytes:100663296,depth:24},Zo=/* @__PURE__ */ new Set([`JOB_TYPE`,`TOPIC`,`CLASS`,`BEAN`]);async function Qo(e,t){let n=[],r=[{directory:e,depth:0}];for(;r.length>0&&n.length<t.files;){let{directory:e,depth:i}=r.pop(),a;try{a=await E(e,{withFileTypes:!0})}catch{continue}for(let o of a){if(o.isSymbolicLink()||o.name.startsWith(`.`)||_.has(o.name))continue;let a=v.join(e,o.name);o.isDirectory()?i<t.depth&&r.push({directory:a,depth:i+1}):o.isFile()&&Ue.test(o.name)&&n.length<t.files&&n.push(a)}}return n.sort()}async function $o(e,t){let n;try{let r=await k(e);return!r.isFile()||r.size>t?null:(n=await Jt(e,`r`),await n.readFile(`utf8`))}catch{return null}finally{await n?.close().catch(()=>void 0)}}async function es(e,t){let n=await Qo(e,t),r=[],i=0;for(let e=0;e<n.length&&i<t.totalBytes;e+=32)(await Promise.all(n.slice(e,e+32).map(e=>$o(e,t.fileBytes)))).forEach((a,o)=>{a===null||i+a.length>t.totalBytes||(i+=a.length,r.push({path:n[e+o],text:a}))});return r}async function ts(e,t){let n=[],r=[],i=0;for(let a=0;a<e.files.length;a+=32){let o=await Promise.all(e.files.slice(a,a+32).map(async({path:e})=>{let t=await $o(e,33554432);if(t===null)return null;try{return{text:t,loaded:{path:e,model:await Me(e,t)}}}catch{return null}}));for(let e of o)e&&(n.push(e.loaded),i+e.text.length<=t&&(i+=e.text.length,r.push({path:e.loaded.path,text:e.text})))}return{models:n,texts:r}}var ns=class{root;limits;pending=null;builds=0;constructor(e,t=Xo){this.root=e,this.limits=t}invalidate(){this.pending=null}state(e){if(!this.pending){this.builds+=1;let t=this.build(e);this.pending=t,t.catch(()=>{this.pending===t&&(this.pending=null)})}return this.pending}async build(e){let[t,n]=await Promise.all([es(this.root,this.limits),e().then(e=>ts(e,Math.floor(this.limits.totalBytes/2)))]),{models:r}=n,i=We(r),a=i.filter(e=>Zo.has(e.kind)&&e.elementId!==void 0).map(e=>({kind:e.kind,value:e.value,elementId:e.elementId}));return{index:await Tt(t.map(e=>({file:e.path,text:e.text}))),sources:t,models:r,diagrams:n.texts,targets:i,workers:await rt(t,a)}}};const rs=[{id:`jdtls`,languages:[`java`],command:`jdtls`,args:[]},{id:`kotlin-language-server`,languages:[`kotlin`],command:`kotlin-language-server`,args:[]},{id:`typescript-language-server`,languages:[`typescript`,`javascript`],command:`typescript-language-server`,args:[`--stdio`]},{id:`vscode-json-language-server`,languages:[`json`],command:`vscode-json-language-server`,args:[`--stdio`]},{id:`vscode-json-languageserver`,languages:[`json`],command:`vscode-json-languageserver`,args:[`--stdio`]},{id:`yaml-language-server`,languages:[`yaml`],command:`yaml-language-server`,args:[`--stdio`]},{id:`lemminx`,languages:[`xml`],command:`lemminx`,args:[]},{id:`marksman`,languages:[`markdown`],command:`marksman`,args:[`server`]},{id:`pyright-langserver`,languages:[`python`],command:`pyright-langserver`,args:[`--stdio`]},{id:`gopls`,languages:[`go`],command:`gopls`,args:[]}],is=/^[\w.-]+$/;function as(e){return e.length>0&&e.length<=80&&is.test(e)}function os(e){let t=[];try{t=(new h(e).read().languageServers??[]).map(e=>({id:e.id,languages:e.languages,command:e.command,args:e.args??[],env:e.env??{},configured:!0}))}catch{t=[]}let n=new Set(t.map(e=>e.id));return[...t,...rs.filter(e=>!n.has(e.id)).map(e=>({...e,env:{},configured:!1}))]}function ss(e){try{return C(e).isFile()?(At(e,process.platform===`win32`?y.F_OK:y.X_OK),!0):!1}catch{return!1}}function cs(e,t,n=process.platform){let r=n===`win32`,i=r?[``,...(t.PATHEXT??`.COM;.EXE;.BAT;.CMD`).split(`;`).filter(Boolean)]:[``];if(v.isAbsolute(e))return i.map(t=>e+t).find(ss)??null;if(e.includes(`/`)||e.includes(`\\`))return null;let a=(t.PATH??t.Path??``).split(r?`;`:`:`).filter(Boolean);for(let t of a)for(let n of i){let r=v.join(t,e+n);if(ss(r))return r}return null}function ls(e,t){return os(e).map(e=>({...e,found:cs(e.command,{...t,...e.env})}))}const us=Buffer.from(`\r
9
+ `).map(e=>` ${e}`)),f&&a.push(` output cut off`),n&&a.push(` ${n.message}`);let p=!l&&!u&&!n&&t===0;!p&&!n&&a.push(l?` timed out`:u?` cancelled`:` exited ${t}`),o({ok:p,lines:a})};r.signal?.aborted&&d(),s.on(`error`,e=>ee(null,e)),s.on(`close`,e=>ee(e))})}function oa(e=process.env){return s(e)}function sa(e){return v.join(e,`license.json`)}function ca(e){try{if(!b(e))return null;let t=JSON.parse(x(e,`utf8`));return typeof t.token==`string`?t.token:null}catch{return null}}function la(e,t,i=n,a=Date.now()){let o=ca(sa(e));if(!o)return{token:null,machine:t};let s=r(o,{machine:t,now:a,keys:i});return s.status!==`valid`||s.claims.source===`pipeline`?{token:null,machine:t}:{token:o,machine:t}}function ua(e){return e?`RIGHT`:`LEFT`}const da=/* @__PURE__ */ new Set([`AUTO_LAYOUT`,`CODE_LINKS`,`CONVENTIONS`,`FLOW_ANALYSIS`,`MIGRATION`,`TEST_RUNS`,`AI_CHAT`,`VARIABLE_CHECKS`]),G=/* @__PURE__ */ new WeakMap;function fa(e,t=Date.now()){let n=G.get(e);if(n&&t-n.at<5e3)return n.state;let r=d({env:e.env});return G.set(e,{at:t,state:r}),r.catch(()=>{G.get(e)?.state===r&&G.delete(e)}),r}function pa(e){G.delete(e)}async function K(e){return u[(await fa(e)).tier]>=u.pro}function ma(e,t,n=Date.now()){let r=e.tier===`team`?`TEAM`:e.tier===`pro`?`PRO`:`FREE`,i=e.source===`trial`&&e.trialEndsAt?Math.max(0,Math.ceil((Date.parse(e.trialEndsAt)-n)/864e5)):void 0,a=c({env:t.env});return{tier:r,detail:e.detail,trialDaysLeft:i,trialEndsAt:e.trialEndsAt??null,token:la(oa(t.env),a).token,machine:a}}async function ha(e){return ma(await fa(e),e)}function ga(e){let t=_a(e).text(`theme`);return t===`light`?{theme:`LIGHT`,dark:!1}:t===`dark`?{theme:`DARK`,dark:!0}:t===`dracula`?{theme:`DRACULA`,dark:!0}:{theme:`SYSTEM`,dark:!1}}function _a(e){return new h(e.home)}const va=[{method:`GET`,path:`/api/license`,operationId:`getLicense`,run:(e,t)=>ha(t)},{method:`POST`,path:`/api/license/feature`,operationId:`requestFeature`,run:async(e,t)=>{let n=R(L(e.body),`feature`);if(!da.has(n))throw I(400,`app.cli.web.reason.unknownFeature`,{feature:n.slice(0,60)});let r=n===`AI_CHAT`?m(await fa(t),{env:t.env}):await K(t),i=c({env:t.env});return{allowed:r,token:r?la(oa(t.env),i).token:null}}},{method:`POST`,path:`/api/license/offer`,operationId:`showLicenceOffer`,run:()=>({opened:!1})},{method:`GET`,path:`/api/theme`,operationId:`getTheme`,run:(e,t)=>({...ga(t),tokens:{}})},{method:`GET`,path:`/api/preferences`,operationId:`getPreferences`,run:(e,t)=>ee(t.home)?_a(t).read():{}},{method:`PUT`,path:`/api/preferences`,operationId:`savePreferences`,limit:N,run:(e,t)=>(L(e.body),_a(t).write(e.body))},{method:`GET`,path:`/api/host/dialog-order`,operationId:`getDialogButtonOrder`,run:()=>({primary:ua(process.platform===`darwin`)})}],ya=33554432,ba=/^[\w .-]{1,80}$/,xa=/* @__PURE__ */ new Set([`CLASSIC_BPMN`,`CAMUNDA_7`,`CAMUNDA_8`,`OPERATON`,`CIB_SEVEN`,`FLOWABLE`,`ACTIVITI`]),Sa=/* @__PURE__ */ new Set([`NONE`,`GROOVY`,`JAVASCRIPT`]),Ca=/* @__PURE__ */ new Set([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`]),wa=/* @__PURE__ */ new WeakMap,q=/* @__PURE__ */ new WeakMap;function J(e,...t){let n=t.find(e=>typeof e==`string`&&e!==``);return n?e.confine.resolve(n):null}async function Ta(e){if(!e)return``;try{let t=await k(e);if(!t.isFile())return``;if(t.size>ya)throw I(413,`app.cli.web.reason.fileTooLarge`,{limit:ya/1048576});return await Xt(e,`utf8`)}catch(e){if(e instanceof F)throw e;return``}}function Ea(e,t,n){let r=et(n);return{config:e.configs.viewFor(t),detected:r?Mi(r)??null:null,secrets:e.secrets,history:e.history,fetch:e.fetch}}async function Da(e,t){return Ea(e,t,await Ta(t))}async function Oa(e,t,n,r){let i;try{i=await Gi(await Da(e,r),n)}catch(e){throw new F(409,e instanceof Error?e.message:String(e))}try{return await Ei(t,i,e.fetch)}catch(e){throw new F(502,e instanceof Error?e.message:String(e))}}function ka(e){if(e==null||e===``)return null;if(typeof e!=`string`||!ba.test(e))throw I(400,`app.cli.web.reason.badProfile`);return e}function Aa(e,t){if(e==null||e===``)return null;if(typeof e!=`string`)throw I(400,`app.cli.web.reason.wrongField`,{field:t});try{let t=new URL(e.trim());if(t.protocol===`http:`||t.protocol===`https:`)return e.trim()}catch{}throw I(400,`app.cli.web.reason.notAnAddress`,{field:t})}function ja(e,t){let n=z(e,t);return n===void 0||n===``?null:n}function Ma(e){let t=L(e),n=t.authType??`none`;if(typeof n!=`string`||!ki.includes(n))throw I(400,`app.cli.web.reason.wrongField`,{field:`authType`});return{profile:ka(t.profile),url:Aa(t.url,`url`),authType:n,username:ja(t,`username`),clientId:ja(t,`clientId`),tokenUrl:Aa(t.tokenUrl,`tokenUrl`),audience:ja(t,`audience`),password:ja(t,`password`),clientSecret:ja(t,`clientSecret`)}}function Na(e,t){if(!t)return null;let n=v.resolve(e,t);return or(n,e)&&Mr(n)?n:null}function Pa(e,t){let n=t?v.dirname(t):e,r=v.join(n,`.camunda`,`element-templates`);for(;;){let t=v.join(n,`.camunda`,`element-templates`);if(H(t))return t;if(n===e||v.dirname(n)===n)return r;n=v.dirname(n)}}function Fa(e,t){let n=wa.get(e)??/* @__PURE__ */ new Map;wa.set(e,n);for(let{file:r,problems:i}of e.configs.viewFor(t).problems()){let t=`${String(Mr(r)?`present`:`gone`)}:${i.map(e=>JSON.stringify(e)).join(`|`)}`;if(n.get(r)===t)continue;n.set(r,t);let a=v.relative(e.folder,r)||v.basename(r);e.say([f(`app.config.brokenTitle`,{0:a}),...i.flatMap(e=>pt(e,a,`stopped`))].join(`
10
+ `))}}async function Ia(t,n){let r=J(n,t.resource),i=n.configs.viewFor(r);Fa(n,r);let a=i.values(),o=await Ta(r),s=Qe(U(a.engine))??et(o),c=Kr(a.lint),l=Kr(a.conventions),u=Object.keys(l).length>0&&await K(n),d=Array.isArray(a.elementTemplates)?a.elementTemplates.filter(e=>typeof e==`string`):[],f=new h(n.home).text(`theme`);return{theme:f===`light`?`LIGHT`:f===`dark`?`DARK`:f===`dracula`?`DRACULA`:`SYSTEM`,locale:p(),engine:s?$e(s):null,scriptType:Ni(a.scriptType)??`NONE`,bpmnLint:{configPath:Na(n.folder,U(c.configPath))??Na(n.folder,`.bpmnlintrc`),clientBundlePath:Na(n.folder,U(c.clientBundlePath))},elementTemplates:d,elementTemplatesContent:ta(n.folder,r,d,i.machineLocalEntries(`elementTemplates`)),elementTemplatesFolder:Pa(n.folder,r),project:v.basename(n.folder),bpmnFilePath:r??``,bpmnXml:o,conventions:u?l:null,palette:lt(a.palette),pluginVersion:e()??null}}function La(e,t){let n=L(t),r=R(n,`engine`),i=R(n,`scriptType`);if(!xa.has(r))throw I(400,`app.cli.web.reason.wrongField`,{field:`engine`});if(!Sa.has(i))throw I(400,`app.cli.web.reason.wrongField`,{field:`scriptType`});return{engine:r,scriptType:i,elementTemplates:dr(n,`elementTemplates`).map(t=>{let n=e.confine.resolve(t);return e.confine.relative(n)||`.`})}}function Ra(e){if(e.parts===void 0||e.parts===null)return;let t=V(e,`parts`);if(t.length>64)throw I(400,`app.cli.web.reason.tooMany`);return t.map(e=>{let t=L(e);return{name:R(t,`name`),filename:z(t,`filename`),contentType:z(t,`contentType`),content:R(t,`content`)}})}async function za(e,t){let n=L(e.body),r=R(n,`method`);if(!Ca.has(r))throw I(400,`app.cli.web.reason.wrongField`,{field:`method`});let i={method:r,path:R(n,`path`),body:z(n,`body`),parts:Ra(n),testRun:B(n,`testRun`)};try{Ci(i)}catch{throw I(400,`app.cli.web.reason.badEnginePath`)}return Oa(t,i,ka(n.profile),J(t,z(n,`resource`),e.resource))}async function Ba(e,t){let n=L(e.body),r=R(n,`stage`);if(r!==`preDeploy`&&r!==`postDeploy`)throw I(400,`app.cli.web.reason.wrongField`,{field:`stage`});let i=dr(n,`resources`);if(i.length>1e3)throw I(400,`app.cli.web.reason.tooMany`);let a=i.map(e=>t.confine.resolve(e)),o=ka(n.profile),s=J(t,z(n,`resource`),e.resource);if((q.get(t)??0)>=4)throw I(429,`app.cli.web.reason.tooManyHooks`);let c=t.configs.viewFor(s).values(o),l=ra(c,r);return q.set(t,(q.get(t)??0)+1),{run:t.hooks.start(async e=>{try{if(!l)return{ok:!0,lines:[]};let n=await vt(t.folder,r,l,void 0,t.env);return n.allowed?await aa(r,a,o,{root:t.folder,values:c,trusted:!0,signal:e,env:t.env}):{ok:!1,lines:n.lines}}finally{q.set(t,Math.max(0,(q.get(t)??1)-1))}})}}const Va=[{method:`GET`,path:`/api/config`,operationId:`getConfig`,run:Ia},{method:`POST`,path:`/api/config`,operationId:`saveConfig`,limit:N,run:(e,t)=>{oi(t.folder,La(t,e.body)),t.configs.invalidate()}},{method:`GET`,path:`/api/deploy/targets`,operationId:`getDeployTargets`,run:async(e,t)=>Li(await Da(t,J(t,e.query.get(`resource`),e.resource)))},{method:`GET`,path:`/api/deploy/settings`,operationId:`getDeploymentSettings`,run:async(e,t)=>Ri(await Da(t,J(t,e.resource)),ka(e.query.get(`profile`)))},{method:`POST`,path:`/api/deploy/settings`,operationId:`saveDeploymentSettings`,limit:N,run:async(e,t)=>{let n=Ma(e.body);ri(t.folder,n.profile,n),await Ki(t.secrets,n.profile,n),t.configs.invalidate()}},{method:`POST`,path:`/api/host/engine`,operationId:`askEngine`,limit:P,run:za},{method:`POST`,path:`/api/host/hook`,operationId:`runHook`,limit:N,run:Ba},{method:`GET`,path:`/api/host/hook/{run}`,operationId:`hookState`,run:(e,t)=>{let n=t.hooks.state(e.params.run);if(!n)throw I(404,`app.cli.web.reason.noSuchRun`);return n}},{method:`DELETE`,path:`/api/host/hook/{run}`,operationId:`cancelHook`,run:(e,t)=>t.hooks.cancel(e.params.run)},{method:`POST`,path:`/api/host/deployed`,operationId:`recordDeployment`,limit:N,run:(e,t)=>{let n=L(e.body);t.history.record(ka(n.profile),dr(n,`resources`))}}],Ha=67108864,Ua=16777216,Wa=/^[A-Za-z0-9-]{1,64}$/,Ga=/^[a-z0-9-]{1,120}$/;function Ka(e){return Math.floor(e.mtimeMs)}async function qa(e,t,n=async()=>void 0){if((typeof t==`string`?Buffer.byteLength(t):t.length)>16777216)throw I(413,`app.cli.web.reason.fileTooLarge`,{limit:Ua/1048576});let r=await k(e).catch(()=>null);if(r?.isDirectory())throw I(400,`app.cli.web.reason.isAFolder`);let i=v.join(v.dirname(e),`.${v.basename(e)}.${process.pid}.${Ut(4).toString(`hex`)}.tmp`);try{await $t(i,t,{mode:r?r.mode&511:420});let a=Ka(await k(i));return await n(),await D(i,e),a}catch(e){throw await O(i,{force:!0}).catch(()=>void 0),e}}async function Ja(e,t,n){let r=e.confine.resolve(t),i=await k(r);if(i.isDirectory())throw I(400,`app.cli.web.reason.isAFolder`);if(i.size>67108864)throw I(413,`app.cli.web.reason.fileTooLarge`,{limit:Ha/1048576});let a=await Xt(r);return n?{content:a.toString(`base64`),isBase64:!0}:{content:a.toString(`utf8`)}}function Ya(e,t){e.project.invalidate(),e.changed([t]).catch(()=>void 0)}async function Xa(e,t,n,r){let i=e.confine.resolve(t);e.confine.writable(i,String(t));let a=r?Buffer.from(n,`base64`):n;await T(v.dirname(i),{recursive:!0}),await qa(i,a),Ya(e,i)}async function Za(e,t,n,r){let i=e.confine.resolve(t);e.confine.writable(i,String(t)),await T(v.dirname(i),{recursive:!0});let a=await qa(i,n,async()=>{if(r===null)return;let t=await k(i).catch(()=>null);if(!t||Ka(t)!==r)throw I(409,`app.cli.web.reason.changedOnDisk`,{path:e.confine.relative(i).slice(0,200)})});return Ya(e,i),a}async function Qa(e,t){let n=await Jt(e,y.O_WRONLY|y.O_CREAT|y.O_EXCL,420);try{await n.writeFile(t,`utf8`)}finally{await n.close()}}async function $a(e,t,n){if(e.confine.resolve(t)!==e.folder)throw I(400,`app.cli.web.reason.notTheProject`,{path:String(t).slice(0,200)});if(n.length===0||n.length>500)throw I(400,`app.cli.web.reason.badFileList`);let r=[];for(let t of n){let n=L(t),i=R(n,`path`);if(/^[/\\]/.test(i)||/^[A-Za-z]:/.test(i))throw I(403,`app.cli.web.reason.outside`,{path:i.slice(0,200)});let a=e.confine.resolve(i);e.confine.writable(a,i);let o=R(n,`content`);if(Buffer.byteLength(o)>16777216)throw I(413,`app.cli.web.reason.fileTooLarge`,{limit:Ua/1048576});if(r.some(e=>e.target===a))throw I(409,`app.cli.web.reason.listedTwice`,{path:i.slice(0,200)});r.push({target:a,content:o,shown:i})}let i=[];try{for(let{target:e,content:t,shown:n}of r){await T(v.dirname(e),{recursive:!0});try{await Qa(e,t)}catch(e){throw e.code===`EEXIST`?I(409,`app.cli.web.reason.alreadyExists`,{path:n.slice(0,200)}):e}i.push(e)}}catch(e){throw await Promise.all(i.map(e=>Qt(e).catch(()=>void 0))),e}}async function eo(e,t,n,r){if(!Wa.test(t)||!Ga.test(n))throw I(400,`app.cli.web.reason.badTraceName`);let i=v.join(e.folder,`.penstock`,`runs`),a=v.join(i,t),o=e.confine.resolve(a);await T(o,{recursive:!0}),await $t(v.join(i,`.gitignore`),`*
11
+ `);let s=v.join(o,`${n}.json`);return await qa(s,r),s}const to=[{method:`POST`,path:`/api/file/read`,operationId:`readFile`,run:(e,t)=>{let n=L(e.body);return Ja(t,n.path,B(n,`asBase64`))}},{method:`POST`,path:`/api/file/save`,operationId:`saveFile`,limit:P,run:async(e,t)=>{let n=L(e.body);await Xa(t,n.path,R(n,`content`),B(n,`isBase64`))}},{method:`POST`,path:`/api/file/create-project-files`,operationId:`createProjectFiles`,limit:P,run:async(e,t)=>{let n=L(e.body);await $a(t,n.root,V(n,`files`))}},{method:`POST`,path:`/api/host/run-trace`,operationId:`saveRunTrace`,limit:P,run:async(e,t)=>{let n=L(e.body);return{path:await eo(t,R(n,`runId`),R(n,`name`),R(n,`content`))}}},{method:`GET`,path:`/api/project/files`,operationId:`getProjectFiles`,run:(e,t)=>t.project.listing()}];function no(e){return e.replace(/[\u0000-\u001f\u007f]+/g,` `).slice(0,500)}function ro(e){try{let t=new URL(e);if(t.protocol===`https:`||t.protocol===`http:`)return t.href}catch{}throw I(400,`app.cli.web.reason.notWebAddress`,{url:no(e).slice(0,120)})}const io=[{method:`POST`,path:`/api/host/notify`,operationId:`notifyUser`,limit:N,run:(e,t)=>{let n=L(e.body),r=no(R(n,`text`));B(n,`error`),t.say(r)}},{method:`POST`,path:`/api/host/open-link`,operationId:`openExternalLink`,limit:N,run:async(e,t)=>{await t.openLink(ro(R(L(e.body),`url`)))}},{method:`POST`,path:`/api/host/test-output`,operationId:`sendTestOutput`,limit:N,run:()=>void 0},{method:`POST`,path:`/api/actions`,operationId:`publishActions`,limit:N,run:()=>void 0},{method:`POST`,path:`/api/view/code-lenses`,operationId:`publishCodeLenses`,limit:N,run:()=>void 0},{method:`GET`,path:`/vscode/events`,operationId:`nextHostEvent`,held:!0,run:(e,t)=>t.events.next(e.client,e.signal)}],ao=/* @__PURE__ */ new Set([`PROCESS`,`ELEMENT`,`JOB_TYPE`,`TOPIC`,`MESSAGE`,`SIGNAL`,`DECISION`,`FORM`,`CLASS`,`BEAN`,`VARIABLE`,`ERROR`]);function oo(e){let t=L(e),n=R(t,`kind`);if(!ao.has(n))throw I(400,`app.cli.web.reason.wrongField`,{field:`kind`});return{kind:n,value:R(t,`value`)}}function so(e,t,n){return{precise:!1,results:t.flatMap(t=>{let r=n.paid?bt(e,t,e=>yt(e.file,e.line)).map(({implements:e,...t})=>({...t,implementation:e})):[],i=Je(e,t).map(e=>({path:e.file,line:e.line,offset:e.offset}));return r.length>0||i.length>0?[{kind:t.kind,value:t.value,links:r,places:i}]:[]}),...n.names?{names:bn(e).map(e=>({...e,origin:`code`}))}:{}}}const co=[{method:`POST`,path:`/api/project/code`,operationId:`findCode`,limit:N,run:async(e,t)=>{let n=L(e.body),r=V(n,`subjects`).map(oo);if(r.length>2e3)throw I(400,`app.cli.web.reason.tooMany`);let{index:i,sources:a}=await t.code.state(()=>t.project.listing()),o=so(i,r,{paid:await K(t),names:n.names===!0});if(n.facts!==!0)return o;let s=o.results.flatMap(e=>e.places.map(e=>({file:e.path,offset:e.offset})));return{...o,facts:await wt(a,s)}}},{method:`POST`,path:`/api/project/worker-variables`,operationId:`findWorkerVariables`,run:async(e,t)=>{let{values:n}=_t(t.folder),r=m(await fa(t),{env:t.env}),{workers:i}=await t.code.state(()=>t.project.listing());return Ve(i,{codeLinks:await K(t),values:n,entitled:r})}},{method:`POST`,path:`/api/project/snapshot`,operationId:`reportSnapshot`,limit:P,run:()=>void 0},{method:`POST`,path:`/api/project/findings`,operationId:`reportFindings`,limit:P,run:()=>void 0},{method:`GET`,path:`/api/debug/state`,operationId:`getDebugState`,run:()=>({positions:[]})}];function Y(e,t,n,r){return{method:e,path:t,operationId:n,run:()=>{throw I(501,`app.cli.web.unsupported.${r}`)}}}const lo=[Y(`POST`,`/api/script`,`createScript`,`script`),Y(`POST`,`/api/script/slot`,`reportScriptSlot`,`script`),Y(`GET`,`/api/preview-diff`,`getPreviewDiff`,`diff`),Y(`POST`,`/api/diff/open`,`openDiff`,`diff`),Y(`GET`,`/api/clipboard`,`getClipboard`,`clipboard`),Y(`POST`,`/api/clipboard`,`saveClipboard`,`clipboard`),Y(`POST`,`/api/clipboard/image`,`saveClipboardImage`,`clipboard`),Y(`POST`,`/api/file/choose`,`chooseFile`,`chooser`),Y(`POST`,`/api/navigate/class`,`navigateToClass`,`navigation`),Y(`POST`,`/api/view/tool-window`,`publishToolWindow`,`view`),Y(`POST`,`/api/host/reveal`,`revealElement`,`reveal`),Y(`POST`,`/api/host/open-code`,`openCode`,`navigation`),Y(`POST`,`/api/host/run-tests`,`runTestHandles`,`tests`),Y(`POST`,`/api/host/linked-rename`,`offerLinkedRename`,`rename`),Y(`POST`,`/api/host/confirm`,`confirmWithUser`,`confirm`),Y(`POST`,`/api/host/migration-preview`,`previewMigration`,`migration`),Y(`GET`,`/api/host/migration-answer`,`getMigrationAnswer`,`migration`),Y(`PUT`,`/vscode/document`,`saveDocumentText`,`document`),Y(`POST`,`/vscode/undo`,`undo`,`document`),Y(`POST`,`/vscode/redo`,`redo`,`document`)],uo={files:2e4,bytes:1073741824,depth:40};var fo=class extends Error{};const po=/* @__PURE__ */ new Set([`.DS_Store`,`Thumbs.db`]),mo=4294967295,ho=mn(nn);async function go(e,t=uo,n){let r=[],i=0,a=[{directory:e,depth:0}];for(;a.length>0;){if(n?.aborted)throw Error(`cancelled`);let{directory:o,depth:s}=a.pop(),c;try{c=await Yt(o)}catch{continue}try{for await(let n of c){let c=v.join(o,n.name);if(!n.isSymbolicLink()){if(n.isDirectory()){if(_.has(n.name)||s>=t.depth)continue;a.push({directory:c,depth:s+1})}else if(n.isFile()&&!po.has(n.name)&&!/\.tmp$/.test(n.name)){let n;try{n=await k(c)}catch{continue}if(r.length>=t.files||n.size>mo||i+n.size>t.bytes)throw new fo;i+=n.size,r.push({rel:v.relative(e,c).split(v.sep).join(`/`),absolute:c,size:n.size,modified:n.mtimeMs})}}}}finally{await c.close().catch(()=>void 0)}}return r.sort((e,t)=>e.rel<t.rel?-1:+(e.rel>t.rel))}function _o(e){let t=new Date(e),n=Math.min(2107,Math.max(1980,t.getFullYear()));return{time:t.getHours()<<11|t.getMinutes()<<5|t.getSeconds()>>1,date:n-1980<<9|t.getMonth()+1<<5|t.getDate()}}const vo=2056;function yo(e,t){let n=Buffer.alloc(30+e.length);return n.writeUInt32LE(67324752,0),n.writeUInt16LE(20,4),n.writeUInt16LE(vo,6),n.writeUInt16LE(8,8),n.writeUInt16LE(t.time,10),n.writeUInt16LE(t.date,12),n.writeUInt16LE(e.length,26),e.copy(n,30),n}function bo(e,t,n){let r=Buffer.alloc(16);return r.writeUInt32LE(134695760,0),r.writeUInt32LE(e>>>0,4),r.writeUInt32LE(t,8),r.writeUInt32LE(n,12),r}function xo(e){let t=Buffer.alloc(46+e.name.length);return t.writeUInt32LE(33639248,0),t.writeUInt16LE(788,4),t.writeUInt16LE(20,6),t.writeUInt16LE(vo,8),t.writeUInt16LE(8,10),t.writeUInt16LE(e.stamp.time,12),t.writeUInt16LE(e.stamp.date,14),t.writeUInt32LE(e.crc>>>0,16),t.writeUInt32LE(e.compressed,20),t.writeUInt32LE(e.size,24),t.writeUInt16LE(e.name.length,28),t.writeUInt32LE(33188<<16>>>0,38),t.writeUInt32LE(e.offset,42),e.name.copy(t,46),t}function So(e,t,n){let r=Buffer.alloc(22);return r.writeUInt32LE(101010256,0),r.writeUInt16LE(e,8),r.writeUInt16LE(e,10),r.writeUInt32LE(t,12),r.writeUInt32LE(n,16),r}async function*Co(e,t){let n=[],r=0,i=e=>(r+=e.length,e);for(let a of e){let e=Buffer.from(`${t}/${a.rel}`,`utf8`),o=_o(a.modified),s=r;yield i(yo(e,o));let c=0,l=0,u=0;if(a.size<=524288){let e=await Xt(a.absolute),t=await ho(e);c=en(e),l=e.length,u=t.length,yield i(t)}else{let e=jt(a.absolute),t=tn();e.on(`data`,e=>{let t=e;c=en(t,c),l+=t.length});let n=pn(e,t);n.catch(()=>void 0);for await(let e of t)u+=e.length,yield i(e);await n}if(l>mo||u>mo)throw new fo;yield i(bo(c,u,l)),n.push({name:e,stamp:o,crc:c,compressed:u,size:l,offset:s})}let a=r;for(let e of n)yield i(xo(e));yield i(So(n.length,r-a,a))}function wo(e,t){return dn.from(Co(e,t),{objectMode:!1})}function To(e){return`attachment; filename="${e.replace(/[^\x20-\x7e]|["\\;]/g,`_`)}"; filename*=UTF-8''${encodeURIComponent(e).replace(/['()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}`}const Eo=[{method:`GET`,path:`/web/project/archive`,operationId:`downloadProjectArchive`,run:async(e,t)=>{let n=e.query.get(`expect`);if(n&&n!==t.id)throw I(409,`app.cli.web.reason.projectChanged`);if(!t.confine.stands())throw I(409,`app.cli.web.reason.projectGone`);let r=v.basename(t.folder)||`project`,i;try{i=await go(t.folder,void 0,e.signal)}catch(e){throw e instanceof fo?I(413,`app.cli.web.reason.archiveTooLarge`,{files:2e4,size:1}):e}return new Or({"Content-Type":`application/zip`,"Content-Disposition":To(`${r}.zip`),"X-Content-Type-Options":`nosniff`},wo(i,r))}}],Do=/[\\/\u0000-\u001f\u007f:*?"<>|]/,Oo=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i,ko=/\.(bpmn\.xml|bpmn20\.xml|bpmn|dmn|form|json|ya?ml)$/i;function Ao(e){return e.trim()===``?`empty`:Do.test(e)?`characters`:e===`.`||e===`..`||e.endsWith(`.`)||e.endsWith(` `)||e.startsWith(` `)?`dots`:Oo.test(e)?`reserved`:Buffer.byteLength(e)>255?`long`:null}const jo={empty:`app.cli.web.reason.nameEmpty`,characters:`app.cli.web.reason.nameCharacters`,dots:`app.cli.web.reason.nameDots`,reserved:`app.cli.web.reason.nameReserved`,long:`app.cli.web.reason.nameLong`};function Mo(e){return jo[e]}function No(e,t){let n=ko.exec(e)?.[0]??``,r=e.slice(0,e.length-n.length);return t<=1?`${r} copy${n}`:`${r} copy ${t}${n}`}const Po=/* @__PURE__ */ new Set([`EPERM`,`ENOTSUP`,`EOPNOTSUPP`,`EINVAL`,`ENOSYS`,`EXDEV`,`EMLINK`]);function X(e){return e.replace(/[\u0000-\u001f\u007f]/g,`?`).slice(0,200)}function Fo(e){if(e==null)return null;if(typeof e!=`number`||!Number.isFinite(e))throw I(400,`app.cli.web.reason.wrongField`,{field:`stamp`});return e}function Io(e){let t=Ao(e);if(t)throw I(400,Mo(t),{name:X(e)})}function Lo(e,t){if(e.confine.segments(t).some(e=>_.has(e)||e.startsWith(`.`)))throw I(403,`app.cli.web.reason.notEditable`,{path:X(e.confine.relative(t))})}async function Ro(e,t,n,r){let i=e.confine.resolve(t);if(i===e.folder)throw I(400,`app.cli.web.reason.notTheRoot`);let a=await w(i).catch(()=>null);if(!a)throw I(404,`app.cli.web.reason.noSuchFile`);if(a.isSymbolicLink())throw I(400,`app.cli.web.reason.isALink`,{path:X(String(t))});if(a.isDirectory()){if(r===`file`)throw I(400,`app.cli.web.reason.isAFolder`);Lo(e,i)}else if(a.isFile()){if(e.confine.writable(i,String(t))===`penstock`)throw I(403,`app.cli.web.reason.notEditable`,{path:X(String(t))});if(n!==null&&Math.floor(a.mtimeMs)!==n)throw I(409,`app.cli.web.reason.changedOnDisk`,{path:X(e.confine.relative(i))})}else throw I(400,`app.cli.web.reason.notEditable`,{path:X(String(t))});return{target:i,info:a,shown:e.confine.relative(i)}}async function zo(e,t){let[n,r]=await Promise.all([w(e).catch(()=>null),w(t).catch(()=>null)]);return!!n&&!!r&&n.ino!==0&&n.ino===r.ino&&n.dev===r.dev}async function Bo(e,t,n){if(await w(t).catch(()=>null)){if(e.toLowerCase()===t.toLowerCase()&&await zo(e,t))return void await D(e,t);throw I(409,`app.cli.web.reason.alreadyExists`,{path:X(n)})}try{await qt(e,t)}catch(r){let i=r.code;if(i===`EEXIST`)throw I(409,`app.cli.web.reason.alreadyExists`,{path:X(n)});if(typeof i==`string`&&Po.has(i))return void await D(e,t);throw r}await Qt(e)}async function Vo(e,t,n){if(await w(t).catch(()=>null)){if(e.toLowerCase()===t.toLowerCase()&&await zo(e,t))return void await D(e,t);throw I(409,`app.cli.web.reason.alreadyExists`,{path:X(n)})}await D(e,t)}function Z(e,...t){e.project.invalidate(),e.changed(t).catch(()=>void 0)}async function Ho(e,t){let n=e.confine.resolve(t);if(n===e.folder)throw I(400,`app.cli.web.reason.notTheRoot`);let r=e.confine.segments(n);if(r.length>24)throw I(400,`app.cli.web.reason.tooDeep`);for(let e of r)if(Io(e),_.has(e)||e.startsWith(`.`))throw I(403,`app.cli.web.reason.notEditable`,{path:X(String(t))});if(await w(n).catch(()=>null))throw I(409,`app.cli.web.reason.alreadyExists`,{path:X(e.confine.relative(n))});await T(n,{recursive:!0}),Z(e,n)}async function Uo(e,t,n,r){let i=await Ro(e,t,r,`any`);Io(n);let a=v.join(v.dirname(i.target),n);if(a===i.target)return i.target;let o=e.confine.relative(a);if(i.info.isDirectory()){if(_.has(n)||n.startsWith(`.`))throw I(403,`app.cli.web.reason.notEditable`,{path:X(o)});await Vo(i.target,a,o)}else{let t=e.confine.writeKind(i.target),n=e.confine.writeKind(a);if(!n)throw I(403,`app.cli.web.reason.notEditable`,{path:X(o)});if(t!==n)throw I(400,`app.cli.web.reason.kindChange`,{path:X(o)});await Bo(i.target,a,o)}return Z(e,i.target,a),a}async function Wo(e,t,n,r){let i=await Ro(e,t,r,`any`),a=e.confine.resolve(n===``?`.`:n);if(!(await w(a).catch(()=>null))?.isDirectory())throw I(404,`app.cli.web.reason.noSuchFolder`,{folder:X(n)});a!==e.folder&&Lo(e,a);let o=v.join(a,v.basename(i.target));if(o===i.target)return o;if(i.info.isDirectory()&&or(a,i.target))throw I(400,`app.cli.web.reason.moveIntoItself`);let s=e.confine.relative(o);if(i.info.isDirectory())await Vo(i.target,o,s);else{if(!e.confine.writeKind(o))throw I(403,`app.cli.web.reason.notEditable`,{path:X(s)});await Bo(i.target,o,s)}return Z(e,i.target,o),o}async function Go(e,t){let n=await Ro(e,t,null,`file`);if(n.info.size>67108864)throw I(413,`app.cli.web.reason.fileTooLarge`,{limit:Ha/1048576});let r=v.dirname(n.target),i=v.join(r,`.${v.basename(n.target)}.${process.pid}.${Ut(4).toString(`hex`)}.tmp`);try{await Kt(n.target,i,y.COPYFILE_EXCL);for(let t=1;t<=1e3;t+=1){let a=v.join(r,No(v.basename(n.target),t));if(!await w(a).catch(()=>null)){try{await Bo(i,a,e.confine.relative(a))}catch(e){if(e.status===409)continue;throw e}return Z(e,a),a}}throw I(409,`app.cli.web.reason.exists`)}finally{await O(i,{force:!0}).catch(()=>void 0)}}async function Ko(e,t,n=0,r={seen:0}){if(n>24)return!1;let i=await E(t,{withFileTypes:!0});for(let a of i){if(r.seen+=1,r.seen>5e3)return!1;let i=v.join(t,a.name);if(a.isSymbolicLink())return!1;if(a.isDirectory()){if(!await Ko(e,i,n+1,r))return!1}else if(!a.isFile()||!e.confine.writeKind(i)||e.confine.writeKind(i)===`penstock`)return!1}return!0}async function qo(e,t,n){let r=await Ro(e,t,n,`any`);if(r.info.isDirectory()){if(!await Ko(e,r.target))throw I(409,`app.cli.web.reason.folderHoldsOthers`,{path:X(r.shown)});await O(r.target,{recursive:!0})}else await Qt(r.target);Z(e,r.target)}const Jo=[{method:`POST`,path:`/web/files/create-folder`,operationId:`createFolder`,limit:N,run:async(e,t)=>{await Ho(t,R(L(e.body),`path`))}},{method:`POST`,path:`/web/files/rename`,operationId:`renameEntry`,limit:N,run:async(e,t)=>{let n=L(e.body);return{path:await Uo(t,R(n,`path`),R(n,`name`),Fo(n.stamp))}}},{method:`POST`,path:`/web/files/move`,operationId:`moveEntry`,limit:N,run:async(e,t)=>{let n=L(e.body);return{path:await Wo(t,R(n,`path`),R(n,`folder`),Fo(n.stamp))}}},{method:`POST`,path:`/web/files/save`,operationId:`saveProjectFile`,limit:P,run:async(e,t)=>{let n=L(e.body);return{stamp:await Za(t,R(n,`path`),R(n,`content`),Fo(n.stamp))}}},{method:`POST`,path:`/web/files/duplicate`,operationId:`duplicateEntry`,limit:N,run:async(e,t)=>({path:await Go(t,R(L(e.body),`path`))})},{method:`POST`,path:`/web/files/delete`,operationId:`deleteEntry`,limit:N,run:async(e,t)=>{let n=L(e.body);await qo(t,R(n,`path`),Fo(n.stamp))}}];function Yo(e,t,n){let r=t&&b(t)?t:e,i=e??(r?ht(r):process.cwd()),a=r&&qi(v.resolve(r),v.resolve(i))&&b(r)?r:i,o=H(i)?ft(i,a):[],s=o.map(e=>({name:e,...ct(e)})),c=s.map(e=>({name:e.name,values:e.values})),l=dt(c);return{root:i,files:o,values(e){if(e===void 0)return st(c,n);let t={name:`profile`,values:{profile:e??``}};return st([...c,t],{...n,[gt]:void 0})},profiles:()=>ut(l),activeProfile:()=>mt(l,n),machineLocalEntries:e=>new Set(s.filter(e=>W.includes(v.basename(e.name))).flatMap(t=>Array.isArray(t.values[e])?t.values[e]:[]).filter(e=>typeof e==`string`&&e.trim()!==``).map(e=>e.trim())),problems:()=>s.filter(e=>e.problems.length>0).map(e=>({file:e.name,problems:e.problems}))}}var Xo=class{root;env;views=/* @__PURE__ */ new Map;builds=0;generation=0;constructor(e,t){this.root=e,this.env=t}invalidate(){this.generation+=1,this.views.clear()}viewFor(e){let t=e?v.dirname(e):this.root,n=this.views.get(t);if(n)return n;this.builds+=1;let r=Yo(this.root,e,this.env);return this.views.set(t,r),r}};const Zo={files:2e4,fileBytes:1048576,totalBytes:100663296,depth:24},Qo=/* @__PURE__ */ new Set([`JOB_TYPE`,`TOPIC`,`CLASS`,`BEAN`]);async function $o(e,t){let n=[],r=[{directory:e,depth:0}];for(;r.length>0&&n.length<t.files;){let{directory:e,depth:i}=r.pop(),a;try{a=await E(e,{withFileTypes:!0})}catch{continue}for(let o of a){if(o.isSymbolicLink()||o.name.startsWith(`.`)||_.has(o.name))continue;let a=v.join(e,o.name);o.isDirectory()?i<t.depth&&r.push({directory:a,depth:i+1}):o.isFile()&&Ie.test(o.name)&&n.length<t.files&&n.push(a)}}return n.sort()}async function es(e,t){let n;try{let r=await k(e);return!r.isFile()||r.size>t?null:(n=await Jt(e,`r`),await n.readFile(`utf8`))}catch{return null}finally{await n?.close().catch(()=>void 0)}}async function ts(e,t){let n=await $o(e,t),r=[],i=0;for(let e=0;e<n.length&&i<t.totalBytes;e+=32)(await Promise.all(n.slice(e,e+32).map(e=>es(e,t.fileBytes)))).forEach((a,o)=>{a===null||i+a.length>t.totalBytes||(i+=a.length,r.push({path:n[e+o],text:a}))});return r}async function ns(e,t){let n=[],r=[],i=0;for(let a=0;a<e.files.length;a+=32){let o=await Promise.all(e.files.slice(a,a+32).map(async({path:e})=>{let t=await es(e,33554432);if(t===null)return null;try{return{text:t,loaded:{path:e,model:await Re(e,t)}}}catch{return null}}));for(let e of o)e&&(n.push(e.loaded),i+e.text.length<=t&&(i+=e.text.length,r.push({path:e.loaded.path,text:e.text})))}return{models:n,texts:r}}var rs=class{root;limits;pending=null;builds=0;constructor(e,t=Zo){this.root=e,this.limits=t}invalidate(){this.pending=null}state(e){if(!this.pending){this.builds+=1;let t=this.build(e);this.pending=t,t.catch(()=>{this.pending===t&&(this.pending=null)})}return this.pending}async build(e){let[t,n]=await Promise.all([ts(this.root,this.limits),e().then(e=>ns(e,Math.floor(this.limits.totalBytes/2)))]),{models:r}=n,i=He(r),a=i.filter(e=>Qo.has(e.kind)&&e.elementId!==void 0).map(e=>({kind:e.kind,value:e.value,elementId:e.elementId}));return{index:await Tt(t.map(e=>({file:e.path,text:e.text}))),sources:t,models:r,diagrams:n.texts,targets:i,workers:await rt(t,a)}}};const is=[{id:`jdtls`,languages:[`java`],command:`jdtls`,args:[]},{id:`kotlin-language-server`,languages:[`kotlin`],command:`kotlin-language-server`,args:[]},{id:`typescript-language-server`,languages:[`typescript`,`javascript`],command:`typescript-language-server`,args:[`--stdio`]},{id:`vscode-json-language-server`,languages:[`json`],command:`vscode-json-language-server`,args:[`--stdio`]},{id:`vscode-json-languageserver`,languages:[`json`],command:`vscode-json-languageserver`,args:[`--stdio`]},{id:`yaml-language-server`,languages:[`yaml`],command:`yaml-language-server`,args:[`--stdio`]},{id:`lemminx`,languages:[`xml`],command:`lemminx`,args:[]},{id:`marksman`,languages:[`markdown`],command:`marksman`,args:[`server`]},{id:`pyright-langserver`,languages:[`python`],command:`pyright-langserver`,args:[`--stdio`]},{id:`gopls`,languages:[`go`],command:`gopls`,args:[]}],as=/^[\w.-]+$/;function os(e){return e.length>0&&e.length<=80&&as.test(e)}function ss(e){let t=[];try{t=(new h(e).read().languageServers??[]).map(e=>({id:e.id,languages:e.languages,command:e.command,args:e.args??[],env:e.env??{},configured:!0}))}catch{t=[]}let n=new Set(t.map(e=>e.id));return[...t,...is.filter(e=>!n.has(e.id)).map(e=>({...e,env:{},configured:!1}))]}function cs(e){try{return C(e).isFile()?(At(e,process.platform===`win32`?y.F_OK:y.X_OK),!0):!1}catch{return!1}}function ls(e,t,n=process.platform){let r=n===`win32`,i=r?[``,...(t.PATHEXT??`.COM;.EXE;.BAT;.CMD`).split(`;`).filter(Boolean)]:[``];if(v.isAbsolute(e))return i.map(t=>e+t).find(cs)??null;if(e.includes(`/`)||e.includes(`\\`))return null;let a=(t.PATH??t.Path??``).split(r?`;`:`:`).filter(Boolean);for(let t of a)for(let n of i){let r=v.join(t,e+n);if(cs(r))return r}return null}function us(e,t){return ss(e).map(e=>({...e,found:ls(e.command,{...t,...e.env})}))}const ds=Buffer.from(`\r
12
12
  \r
13
- `);var ds=class{held=Buffer.alloc(0);onMessage;onBroken;constructor(e,t){this.onMessage=e,this.onBroken=t}push(e){for(this.held=this.held.length===0?e:Buffer.concat([this.held,e]);;){let e=this.held.indexOf(us);if(e<0){this.held.length>8192&&this.broken();return}let t=/^content-length:\s*(\d+)\s*$/im.exec(this.held.subarray(0,e).toString(`latin1`)),n=t?Number(t[1]):-1;if(n<0||n>67108864)return this.broken();let r=e+us.length;if(this.held.length<r+n)return;let i=this.held.subarray(r,r+n).toString(`utf8`);this.held=this.held.subarray(r+n);try{this.onMessage(JSON.parse(i))}catch{continue}}}broken(){this.held=Buffer.alloc(0),this.onBroken()}};function fs(e){let t=Buffer.from(JSON.stringify(e),`utf8`);return Buffer.concat([Buffer.from(`Content-Length: ${t.length}\r\n\r\n`,`ascii`),t])}function ps(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return t.jsonrpc===`2.0`&&(typeof t.method==`string`||`id`in t)}var ms=class{running=/* @__PURE__ */ new Map;folder;home;env;events;closed=!1;constructor(e,t,n,r){this.folder=e,this.home=t,this.env=n,this.events=r}get count(){return this.running.size}send(e,t,n){if(this.closed)throw I(409,`app.cli.web.reason.noProject`);if(!as(t))throw I(400,`app.cli.web.reason.wrongField`,{field:`serverName`});if(!ps(n))throw I(400,`app.cli.web.reason.wrongField`,{field:`message`});let r=`${e}\u0000${t}`;(this.running.get(r)??this.start(r,e,t)).child.stdin?.write(fs(n))}forget(e){for(let[t,n]of[...this.running])t.startsWith(`${e}\u0000`)&&this.stop(t,n)}close(){this.closed=!0;for(let[e,t]of[...this.running])this.stop(e,t)}start(e,t,n){let r=os(this.home).find(e=>e.id===n);if(!r)throw I(404,`app.cli.web.reason.noLanguageServer`,{server:n});let i={...this.env,...r.env},a=cs(r.command,i);if(!a)throw I(404,`app.cli.web.reason.languageServerMissing`,{command:r.command});if(this.running.size>=6)throw I(409,`app.cli.web.reason.tooManyLanguageServers`,{limit:6});let o;try{o=ge({command:a,args:r.args})}catch{throw I(404,`app.cli.web.reason.languageServerUnsafe`,{command:r.command})}let s=Vt(o.command,o.args,{cwd:this.folder,env:i,stdio:[`pipe`,`pipe`,`pipe`],windowsVerbatimArguments:o.verbatim,windowsHide:!0}),c={child:s,spec:r};this.running.set(e,c);let l=new ds(e=>this.events.publishTo(t,{serverName:n,message:e}),()=>this.stop(e,c));return s.stdout?.on(`data`,e=>l.push(e)),s.stderr?.resume(),s.stdin?.on(`error`,()=>void 0),s.on(`error`,()=>this.drop(e,c)),s.on(`exit`,()=>this.drop(e,c)),c}drop(e,t){this.running.get(e)===t&&this.running.delete(e)}stop(e,t){this.drop(e,t);let{child:n}=t;n.exitCode!==null||n.killed||(n.stdin?.end(),n.kill(),setTimeout(()=>{n.exitCode===null&&n.kill(Ot.signals.SIGKILL)},2e3).unref())}};const hs={depth:24,visited:25e4,diagrams:2e4},gs=/\.(bpmn|bpmn\.xml|bpmn20\.xml|dmn|form)$/i,_s=[[`target`,`process-test-coverage`],[`build`,`process-test-coverage`]];async function vs(e){let t=[];for(let n=0;n<e.length;n+=64){let r=await Promise.all(e.slice(n,n+64).map(async e=>{try{let t=await k(e);return t.isFile()?{path:e,stamp:Math.floor(t.mtimeMs),size:t.size}:null}catch{return null}}));for(let e of r)e&&t.push(e)}return t.sort((e,t)=>e.path<t.path?-1:+(e.path>t.path))}function ys(e,t){let n=v.relative(e,t).split(v.sep),r=n.indexOf(`.camunda`);return r>=0&&n[r+1]===`element-templates`}async function bs(e){let t=[],n=async(e,r)=>{let i;try{i=await E(e,{withFileTypes:!0})}catch{return}for(let a of i){if(a.name.startsWith(`.`)||_.has(a.name)||a.isSymbolicLink())continue;let i=v.join(e,a.name);a.isDirectory()?r>0&&await n(i,r-1):a.name===`report.json`&&t.push(i)}};return await n(e,4),t}async function xs(e,t=hs){let n=[],r=[],i=[],a=[],o=0,s=[{directory:e,depth:0}];for(;s.length>0&&o<t.visited;){let{directory:c,depth:l}=s.pop(),u;try{u=await E(c,{withFileTypes:!0})}catch{continue}let d=v.basename(c);for(let f of u){if(o>=t.visited)break;if(o+=1,f.isSymbolicLink())continue;let u=f.name,p=v.join(c,u);if(f.isDirectory()){if(_.has(u)||u.startsWith(`.`)&&u!==`.camunda`||l>=t.depth)continue;!u.startsWith(`.`)&&a.length<2e4&&a.push(v.relative(e,p).split(v.sep).join(`/`)),s.push({directory:p,depth:l+1})}else f.isFile()&&(gs.test(u)?n.length<t.diagrams&&n.push(p):/\.json$/i.test(u)&&(d===`test-cases`?r.push(p):ys(e,p)&&i.push(p)))}}let c=(await Promise.all(_s.map(t=>bs(v.join(e,...t))))).flat(),[l,u,d,f]=await Promise.all([vs(n),vs(r),vs(i),vs(c)]),p=e=>e.map(({path:e,stamp:t})=>({path:e,stamp:t}));return a.sort(),{root:e,files:p(l),reports:p(f),testCases:p(u),templates:p(d),folders:a}}function Ss(e){return[...[e.files,e.reports,e.testCases,e.templates].map(e=>e.map(e=>`${e.path}:${e.stamp}`).join(`
13
+ `);var fs=class{held=Buffer.alloc(0);onMessage;onBroken;constructor(e,t){this.onMessage=e,this.onBroken=t}push(e){for(this.held=this.held.length===0?e:Buffer.concat([this.held,e]);;){let e=this.held.indexOf(ds);if(e<0){this.held.length>8192&&this.broken();return}let t=/^content-length:\s*(\d+)\s*$/im.exec(this.held.subarray(0,e).toString(`latin1`)),n=t?Number(t[1]):-1;if(n<0||n>67108864)return this.broken();let r=e+ds.length;if(this.held.length<r+n)return;let i=this.held.subarray(r,r+n).toString(`utf8`);this.held=this.held.subarray(r+n);try{this.onMessage(JSON.parse(i))}catch{continue}}}broken(){this.held=Buffer.alloc(0),this.onBroken()}};function ps(e){let t=Buffer.from(JSON.stringify(e),`utf8`);return Buffer.concat([Buffer.from(`Content-Length: ${t.length}\r\n\r\n`,`ascii`),t])}function ms(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return t.jsonrpc===`2.0`&&(typeof t.method==`string`||`id`in t)}var hs=class{running=/* @__PURE__ */ new Map;folder;home;env;events;closed=!1;constructor(e,t,n,r){this.folder=e,this.home=t,this.env=n,this.events=r}get count(){return this.running.size}send(e,t,n){if(this.closed)throw I(409,`app.cli.web.reason.noProject`);if(!os(t))throw I(400,`app.cli.web.reason.wrongField`,{field:`serverName`});if(!ms(n))throw I(400,`app.cli.web.reason.wrongField`,{field:`message`});let r=`${e}\u0000${t}`;(this.running.get(r)??this.start(r,e,t)).child.stdin?.write(ps(n))}forget(e){for(let[t,n]of[...this.running])t.startsWith(`${e}\u0000`)&&this.stop(t,n)}close(){this.closed=!0;for(let[e,t]of[...this.running])this.stop(e,t)}start(e,t,n){let r=ss(this.home).find(e=>e.id===n);if(!r)throw I(404,`app.cli.web.reason.noLanguageServer`,{server:n});let i={...this.env,...r.env},a=ls(r.command,i);if(!a)throw I(404,`app.cli.web.reason.languageServerMissing`,{command:r.command});if(this.running.size>=6)throw I(409,`app.cli.web.reason.tooManyLanguageServers`,{limit:6});let o;try{o=ge({command:a,args:r.args})}catch{throw I(404,`app.cli.web.reason.languageServerUnsafe`,{command:r.command})}let s=Vt(o.command,o.args,{cwd:this.folder,env:i,stdio:[`pipe`,`pipe`,`pipe`],windowsVerbatimArguments:o.verbatim,windowsHide:!0}),c={child:s,spec:r};this.running.set(e,c);let l=new fs(e=>this.events.publishTo(t,{serverName:n,message:e}),()=>this.stop(e,c));return s.stdout?.on(`data`,e=>l.push(e)),s.stderr?.resume(),s.stdin?.on(`error`,()=>void 0),s.on(`error`,()=>this.drop(e,c)),s.on(`exit`,()=>this.drop(e,c)),c}drop(e,t){this.running.get(e)===t&&this.running.delete(e)}stop(e,t){this.drop(e,t);let{child:n}=t;n.exitCode!==null||n.killed||(n.stdin?.end(),n.kill(),setTimeout(()=>{n.exitCode===null&&n.kill(Ot.signals.SIGKILL)},2e3).unref())}};const gs={depth:24,visited:25e4,diagrams:2e4},_s=/\.(bpmn|bpmn\.xml|bpmn20\.xml|dmn|form)$/i,vs=[[`target`,`process-test-coverage`],[`build`,`process-test-coverage`]];async function ys(e){let t=[];for(let n=0;n<e.length;n+=64){let r=await Promise.all(e.slice(n,n+64).map(async e=>{try{let t=await k(e);return t.isFile()?{path:e,stamp:Math.floor(t.mtimeMs),size:t.size}:null}catch{return null}}));for(let e of r)e&&t.push(e)}return t.sort((e,t)=>e.path<t.path?-1:+(e.path>t.path))}function bs(e,t){let n=v.relative(e,t).split(v.sep),r=n.indexOf(`.camunda`);return r>=0&&n[r+1]===`element-templates`}async function xs(e){let t=[],n=async(e,r)=>{let i;try{i=await E(e,{withFileTypes:!0})}catch{return}for(let a of i){if(a.name.startsWith(`.`)||_.has(a.name)||a.isSymbolicLink())continue;let i=v.join(e,a.name);a.isDirectory()?r>0&&await n(i,r-1):a.name===`report.json`&&t.push(i)}};return await n(e,4),t}async function Ss(e,t=gs){let n=[],r=[],i=[],a=[],o=0,s=[{directory:e,depth:0}];for(;s.length>0&&o<t.visited;){let{directory:c,depth:l}=s.pop(),u;try{u=await E(c,{withFileTypes:!0})}catch{continue}let d=v.basename(c);for(let f of u){if(o>=t.visited)break;if(o+=1,f.isSymbolicLink())continue;let u=f.name,p=v.join(c,u);if(f.isDirectory()){if(_.has(u)||u.startsWith(`.`)&&u!==`.camunda`||l>=t.depth)continue;!u.startsWith(`.`)&&a.length<2e4&&a.push(v.relative(e,p).split(v.sep).join(`/`)),s.push({directory:p,depth:l+1})}else f.isFile()&&(_s.test(u)?n.length<t.diagrams&&n.push(p):/\.json$/i.test(u)&&(d===`test-cases`?r.push(p):bs(e,p)&&i.push(p)))}}let c=(await Promise.all(vs.map(t=>xs(v.join(e,...t))))).flat(),[l,u,d,f]=await Promise.all([ys(n),ys(r),ys(i),ys(c)]),p=e=>e.map(({path:e,stamp:t})=>({path:e,stamp:t}));return a.sort(),{root:e,files:p(l),reports:p(f),testCases:p(u),templates:p(d),folders:a}}function Cs(e){return[...[e.files,e.reports,e.testCases,e.templates].map(e=>e.map(e=>`${e.path}:${e.stamp}`).join(`
14
14
  `)),e.folders.join(`
15
- `)].join(`\0`)}function Cs(e,t){return Ss(e)===Ss(t)}var ws=class{root;limits;cached=null;cachedGeneration=-1;generation=0;building=null;scans=0;constructor(e,t=hs){this.root=e,this.limits=t}peek(){return this.cached}invalidate(){this.generation+=1}async listing(){for(;;){if(this.cached&&this.cachedGeneration===this.generation)return this.cached;if(!this.building){let e=this.generation;this.scans+=1,this.building=xs(this.root,this.limits).then(t=>(this.cached=t,this.cachedGeneration=e,t)).finally(()=>{this.building=null})}await this.building}}},Ts=class{runs=/* @__PURE__ */ new Map;start(e){let t=Wt(),n=new AbortController,r={abort:n,status:`running`};return this.runs.set(t,r),e(n.signal).catch(e=>({ok:!1,lines:[e instanceof Error?e.message:String(e)]})).then(e=>{r.status===`running`&&(r.status=`finished`),r.result=e}),t}active(){let e=0;for(let t of this.runs.values())t.status===`running`&&(e+=1);return e}state(e){let t=this.runs.get(e);if(t)return(t.status===`finished`||t.status===`cancelled`&&t.result)&&this.runs.delete(e),{run:e,status:t.status,ok:t.status===`finished`&&(t.result?.ok??!1),lines:t.result?.lines??[]}}cancel(e){let t=this.runs.get(e);t?.status===`running`&&(t.status=`cancelled`,t.abort.abort())}};const Es=/* @__PURE__ */ new Set([`.camunda`]),Ds=/(~|\.(tmp|swp|swx|bak|lock|crdownload|part))$|^\.#|^\.DS_Store$|^4913$/i;function Os(e){let t=e.split(/[\\/]/).filter(e=>e!==``);return Ds.test(t[t.length-1]??``)?!0:t.slice(0,-1).some(e=>_.has(e)||e.startsWith(`.`)&&!Es.has(e))}var ks=class{root;onBatch;debounceMs;maxWaitMs;firstRetryMs;maxRetryMs;pollMs;open;pending=/* @__PURE__ */ new Set;watcher=null;quiet=null;deadline=null;retry=null;poll=null;retryMs;closed=!1;constructor(e,t,n={}){this.root=e,this.onBatch=t,this.debounceMs=n.debounceMs??80,this.maxWaitMs=n.maxWaitMs??600,this.firstRetryMs=n.retryMs??250,this.maxRetryMs=n.maxRetryMs??5e3,this.pollMs=n.pollMs??3e3,this.retryMs=this.firstRetryMs,this.open=n.open??((e,t)=>Rt(e,{recursive:!0,persistent:!1},t))}get active(){return this.watcher!==null||this.poll!==null}start(){this.attach(!1)}close(){this.closed=!0,this.detach();for(let e of[this.quiet,this.deadline,this.retry,this.poll])e&&clearTimeout(e);this.quiet=this.deadline=this.retry=this.poll=null,this.pending.clear()}attach(e){if(!(this.closed||this.watcher||this.poll)){if(!b(this.root))return this.later();try{this.watcher=this.open(this.root,(e,t)=>this.heard(t))}catch(e){return e?.code===`ERR_FEATURE_UNAVAILABLE_ON_PLATFORM`?this.polling():this.later()}this.watcher.on(`error`,()=>{this.detach(),this.heard(null),this.later()}),this.retryMs=this.firstRetryMs,e&&this.heard(null)}}polling(){this.poll=setInterval(()=>this.heard(null),this.pollMs),this.poll.unref()}detach(){let e=this.watcher;if(this.watcher=null,e){e.removeAllListeners(),e.on(`error`,()=>void 0);try{e.close()}catch{}}}later(){this.closed||this.retry||(this.retry=setTimeout(()=>{this.retry=null,this.attach(!0)},this.retryMs),this.retry.unref(),this.retryMs=Math.min(this.retryMs*2,this.maxRetryMs))}heard(e){if(this.closed)return;let t=e===null?`*`:e.toString();t!==`*`&&Os(t)||(this.pending.add(t===``?`*`:t),this.quiet&&clearTimeout(this.quiet),this.quiet=setTimeout(()=>this.flush(),this.debounceMs),this.quiet.unref(),this.deadline||(this.deadline=setTimeout(()=>this.flush(),this.maxWaitMs),this.deadline.unref()))}flush(){if(this.quiet&&clearTimeout(this.quiet),this.deadline&&clearTimeout(this.deadline),this.quiet=this.deadline=null,this.closed||this.pending.size===0)return;let e=[...this.pending];this.pending.clear(),this.watcher&&!b(this.root)&&(this.detach(),this.later());try{this.onBatch(e.map(e=>e===`*`?e:v.join(this.root,e)))}catch{}}};const As={password:`PENSTOCK_PASSWORD`,clientSecret:`PENSTOCK_CLIENT_SECRET`};function js(e){let t=/* @__PURE__ */ new Map,n=(e,t)=>`${e??``}\u0000${t}`;return{async get(r,i){return t.get(n(r,i))??(e[As[i]]||void 0)},async set(e,r,i){i?t.set(n(e,r),i):t.delete(n(e,r))}}}const Ms=/^penstock(\.local)?\.(ya?ml|json)$/i;function Ns(e){let t=e.env??process.env;return{env:t,home:e.home??te(t),fetch:e.fetch??fetch,openLink:e.openLink??(()=>void 0),say:e.say??(()=>void 0),events:new ur(e.events),limits:e.limits??hs,sourceLimits:e.sourceLimits,watcher:e.watcher,agent:e.agent??{}}}function Ps(e,t){let n=new cr(e),r=new ws(n.root,t.limits),i=new Yo(n.root,t.env),a=new ns(n.root,t.sourceLimits),o=t.events,s=new ms(n.root,t.home,t.env,o),c=o.onForget(e=>s.forget(e)),l=!1,u={id:Ut(6).toString(`hex`),open:!0,folder:n.root,confine:n,project:r,configs:i,code:a,servers:s,events:o,env:t.env,home:t.home,secrets:js(t.env),history:new Pi,hooks:new Ts,agent:new ve(n.root,t.agent.spawn??(e=>Fs(e,t.env)),{home:t.home,env:t.env}),fetch:t.fetch,openLink:t.openLink,say:t.say,async changed(e){if(l)return;let t=r.peek(),n=e.includes(`*`),s=n||e.some(e=>Ms.test(v.basename(e))),c=e.some(e=>e!==`*`&&Ue.test(e)),u=n||e.some(e=>/\.(bpmn|bpmn\.xml|bpmn20\.xml|dmn|form)$/i.test(e));r.invalidate(),s&&i.invalidate(),(n||c||u)&&a.invalidate();let d=await r.listing().catch(()=>null);l||(!s&&t&&d&&Cs(t,d)||o.publish({type:`projectChanged`}),c&&o.publish({type:`codeChanged`}))},close(){l=!0,u.agent.close(),c(),s.close(),d.close()}},d=new ks(n.root,e=>void u.changed(e).catch(()=>void 0),t.watcher);return d.start(),u}function Fs(t,n){let r=xe();if(!r)throw new _e(500,f(`app.agent.notFound`));return Dt({explicit:Et(n),own:r,version:e()},[`agent`,`serve`,`--project`,t]).map(({command:e,args:t,env:n})=>({command:e,args:t,env:n}))}function Q(){throw I(409,`app.cli.web.reason.noProject`)}function Is(e){return{id:`closed`,open:!1,folder:``,get confine(){return Q()},get project(){return Q()},get configs(){return Q()},get code(){return Q()},get servers(){return Q()},get secrets(){return Q()},get history(){return Q()},get hooks(){return Q()},get agent(){return Q()},events:e.events,env:e.env,home:e.home,fetch:e.fetch,openLink:e.openLink,say:e.say,async changed(){},close(){}}}function Ls(e){return e.HOME||e.USERPROFILE||kt()}function Rs(e,t){return e===`~`?t:e.startsWith(`~/`)||e.startsWith(`~\\`)?v.join(t,e.slice(2)):e}function zs(e,t){if(typeof e!=`string`||e.trim()===``||e.length>4096||e.includes(`\0`))throw I(400,`app.cli.web.reason.badFolder`,{folder:String(e).replace(/[\u0000-\u001f\u007f]/g,`?`).slice(0,200)});let n=Rs(e.trim(),t);if(!v.isAbsolute(n))throw I(400,`app.cli.web.reason.notAbsolute`,{folder:e.slice(0,200)});return v.resolve(n)}function Bs(e){return C(e,{throwIfNoEntry:!1})?.isDirectory()===!0}var Vs=class{shared;current;idle;requests=/* @__PURE__ */ new Map;deploys=0;constructor(e){this.shared=Ns(e),this.idle=Is(this.shared),this.current=this.idle,e.folder!==void 0&&(this.current=Ps(e.folder,this.shared)),this.current.open&&(this.remember(this.current.folder),this.current.project.listing().catch(()=>void 0))}get context(){return this.current}info(){let e=this.current;return e.open?{open:!0,available:e.confine.stands(),id:e.id,name:v.basename(e.folder)||e.folder,folder:e.folder}:{open:!1,available:!1,id:null,name:null,folder:null}}busy(){return this.deploys>0||this.current.open&&this.current.hooks.active()>0}beginDeploy(){this.deploys+=1;let e=!1;return()=>{e||(e=!0,--this.deploys)}}track(e,t){let n=this.requests.get(e);return n||(n=/* @__PURE__ */ new Set,this.requests.set(e,n)),n.add(t),()=>{n.delete(t),n.size===0&&this.requests.get(e)===n&&this.requests.delete(e)}}async open(e){let t=zs(e,Ls(this.shared.env)),n=C(t,{throwIfNoEntry:!1});if(!n)throw I(404,`app.cli.web.reason.noSuchFolder`,{folder:t.slice(0,200)});if(!n.isDirectory())throw I(400,`app.cli.web.reason.notAFolder`,{folder:t.slice(0,200)});try{await E(t)}catch(e){let n=e.code;throw n===`EACCES`||n===`EPERM`?I(403,`app.cli.web.reason.folderNotReadable`,{folder:t.slice(0,200)}):I(404,`app.cli.web.reason.noSuchFolder`,{folder:t.slice(0,200)})}return this.current.open&&this.current.folder===S.native(t)?this.info():this.swap(()=>Ps(t,this.shared))}async close(){return this.swap(()=>this.idle)}swap(e){if(this.busy())throw I(409,`app.cli.web.reason.switchBusy`);let t=this.current,n=e();return this.current=n,this.shared.events.drop(),this.shared.events.publish({type:`projectChanged`}),t.open&&this.retire(t),n.open&&(this.remember(n.folder),n.project.listing().catch(()=>void 0)),this.info()}retire(e){e.close(),setTimeout(()=>{let t=this.requests.get(e);if(t)for(let e of t)e.abort();this.requests.delete(e)},3e3).unref()}recent(){let e=[];try{e=new h(this.shared.home).recentProjects()}catch{}return e.map(e=>({folder:e,name:v.basename(e)||e,present:Bs(e)}))}lastProject(){return this.recent().find(e=>e.present)?.folder??null}forget(e){let t=zs(e,Ls(this.shared.env));try{new h(this.shared.home).forgetProject(t)}catch{}return this.recent()}remember(e){try{new h(this.shared.home).rememberProject(e)}catch{}}shutdown(){this.current.close();for(let e of this.requests.values())for(let t of e)t.abort();this.requests.clear(),this.shared.events.close()}};const Hs=/\.(bpmn|bpmn\.xml|bpmn20\.xml|dmn|form)$/i,Us=/^penstock\.(yaml|yml|json)$/i,Ws=new Intl.Collator(`en`,{numeric:!0,sensitivity:`base`});function Gs(e){return Us.test(e)||Hs.test(e)}async function Ks(e){let t;try{t=await Yt(e)}catch{return!1}try{for(let e=0;e<4e3;e+=1){let e=await t.read();if(!e)return!1;if(Gs(e.name))return!0}return!1}catch{return!1}finally{await t.close().catch(()=>void 0)}}async function qs(){if(process.platform!==`win32`)return[`/`];let e=Array.from({length:26},(e,t)=>String.fromCharCode(65+t)).map(async e=>{let t=`${e}:\\`;return await Promise.race([k(t).then(()=>!0,()=>!1),new Promise(e=>setTimeout(()=>e(!1),300).unref())])?t:null});return(await Promise.all(e)).filter(e=>e!==null)}function Js(e,t){let n=e.code,r=t.replace(/[\u0000-\u001f\u007f]/g,`?`).slice(0,200);throw n===`EACCES`||n===`EPERM`?I(403,`app.cli.web.reason.folderNotReadable`,{folder:r}):n===`ENOTDIR`?I(400,`app.cli.web.reason.notAFolder`,{folder:r}):n===`ENOENT`||n===`ELOOP`||n===`ENAMETOOLONG`?I(404,`app.cli.web.reason.noSuchFolder`,{folder:r}):e}async function Ys(e,t){let n=e.lastProject();if(n){let e=v.dirname(n);try{if((await k(e)).isDirectory())return e}catch{}}return t}async function Xs(e,t,n,r=2e4){let i=Ls(e.shared.env),a=t===void 0||t===``?await Ys(e,i):zs(t,i),o;try{if(o=await Zt(a),!(await k(o)).isDirectory())throw I(400,`app.cli.web.reason.notAFolder`,{folder:a.replace(/[\u0000-\u001f\u007f]/g,`?`).slice(0,200)})}catch(e){return Js(e,a)}let s;try{s=await E(o,{withFileTypes:!0})}catch(e){return Js(e,o)}let c=[],l=!1,u=0;for(let e of s){let t=e.name;if(e.isDirectory())c.push({name:t,hidden:t.startsWith(`.`),link:!1});else{if(e.isSymbolicLink()||!e.isFile()&&!e.isDirectory())try{if((await k(v.join(o,t))).isDirectory()){c.push({name:t,hidden:t.startsWith(`.`),link:e.isSymbolicLink()});continue}}catch{continue}Us.test(t)?l=!0:Hs.test(t)&&(u+=1)}}c.sort((e,t)=>Ws.compare(e.name,t.name)||(e.name<t.name?-1:+(e.name>t.name)));let d=c.length,f=d>r?c.slice(0,r):c,p=f.reduce((e,t)=>e+ +!!t.hidden,0),m=!0,ee=Date.now()+1500,te=f.filter(e=>!e.link&&(n||!e.hidden)),h=0;await Promise.all(Array.from({length:Math.min(24,te.length)},async()=>{for(;h<te.length;){if(Date.now()>ee){m=!1;return}let e=te[h];h+=1,await Ks(v.join(o,e.name))&&(e.project=!0)}}));let ne=v.dirname(o);return{path:o,parent:ne===o?null:ne,home:i,separator:v.sep,roots:await qs(),entries:f,total:d,truncated:f.length<d,hiddenCount:p,hintsComplete:m,project:l||u>0?{config:l,diagrams:u}:null}}const Zs=[{method:`POST`,path:`/web/folders`,operationId:`listFolders`,limit:N,run:e=>{let t=e.body===void 0?{}:L(e.body);return Xs(e.workspace,z(t,`path`),B(t,`hidden`))}}],Qs=[{method:`GET`,path:`/web/project`,operationId:`getCurrentProject`,run:e=>e.workspace.info()},{method:`POST`,path:`/web/project/open`,operationId:`openProject`,limit:N,run:e=>e.workspace.open(R(L(e.body),`folder`))},{method:`POST`,path:`/web/project/close`,operationId:`closeProject`,run:e=>e.workspace.close()},{method:`GET`,path:`/web/project/recent`,operationId:`listRecentProjects`,run:e=>({projects:e.workspace.recent()})},{method:`POST`,path:`/web/project/recent/forget`,operationId:`forgetRecentProject`,limit:N,run:e=>({projects:e.workspace.forget(R(L(e.body),`folder`))})}];function $s(t){let n=new h(t.home).text(`theme`);return{theme:n===`light`?`LIGHT`:n===`dark`?`DARK`:n===`dracula`?`DRACULA`:`SYSTEM`,locale:p(),engine:null,scriptType:`NONE`,bpmnLint:{configPath:null,clientBundlePath:null},elementTemplates:[],elementTemplatesContent:[],elementTemplatesFolder:``,project:``,bpmnFilePath:``,bpmnXml:``,conventions:null,pluginVersion:e()??null}}const ec=[`JOB_TYPE`,`TOPIC`,`CLASS`,`BEAN`,`MESSAGE`];function tc(e){return ec.includes(e)}function nc(e,t,n){return t===`MESSAGE`?Re(e,{kind:t,value:n}):ze(e,{kind:t,value:n})}function rc(e,t,n){let r=/* @__PURE__ */ new Map;for(let i of n)if(tc(i.kind)&&i.value!==``)for(let n of nc(t,i.kind,i.value)){if(n.file!==e)continue;let t=i.elementId??null,a=`${n.line}\u0000${i.kind}\u0000${i.value}\u0000${i.path}\u0000${t}`;if(!r.has(a)&&(r.set(a,{line:n.line,kind:i.kind,value:i.value,diagram:i.path,element:t,name:i.label,elementType:i.elementType??``}),r.size>=500))return ic(r)}return ic(r)}function ic(e){return[...e.values()].sort((e,t)=>e.line-t.line||e.diagram.localeCompare(t.diagram)||e.name.localeCompare(t.name))}function ac(e,t){let n=/* @__PURE__ */ new Map,r=(e,t,r)=>{if(t===``)return;let i=`${e}\u0000${t}`,a=n.get(i);a?a.origin!==r&&(a.origin=`both`):n.set(i,{kind:e,value:t,origin:r})};for(let e of t)tc(e.kind)&&r(e.kind,e.value,`diagram`);for(let t of e.jobTypes.keys())r(`JOB_TYPE`,t,`code`);for(let t of e.topics.keys())r(`TOPIC`,t,`code`);for(let t of e.classes.keys())r(`CLASS`,t,`code`);for(let t of e.beans.keys())r(`BEAN`,t,`code`);for(let t of e.references.keys())t.startsWith(`MESSAGE:`)&&r(`MESSAGE`,t.slice(8),`code`);return[...n.values()].sort((e,t)=>e.kind.localeCompare(t.kind)||e.value.localeCompare(t.value)).slice(0,5e3)}const $=`camunda`,oc=`zeebe`,sc=e=>{let t=e.lastIndexOf(`:`);return t<0?``:e.slice(0,t)},cc=e=>e.slice(e.lastIndexOf(`:`)+1);function lc(e,t){return e===void 0||e===`*`||e===``&&t===``||e===t}function uc(e,t,n){return e.tag!==void 0&&e.tag!==cc(t)?!1:e.attribute===void 0?lc(e.tagPrefix,sc(t)):e.attribute===cc(n)&&lc(e.attributePrefix,sc(n))}const dc=/* @__PURE__ */ new Set([`PROCESS`,`JOB_TYPE`,`TOPIC`,`MESSAGE`,`SIGNAL`,`DECISION`,`FORM`,`CLASS`,`BEAN`,`ERROR`]),fc={PROCESS:[`startProcessInstanceByKey`,`createProcessInstanceByKey`,`startProcessInstanceByKeyAndTenantId`,`processDefinitionKey`,`bpmnProcessId`],JOB_TYPE:[`jobType`],TOPIC:[`topicName`,`subscribe`],MESSAGE:[`correlateMessage`,`createMessageCorrelation`,`messageName`,`correlateMessageAsync`],SIGNAL:[`broadcastSignal`,`throwSignal`,`signalName`],DECISION:[`evaluateDecisionByKey`,`evaluateDecisionTableByKey`,`decisionKey`,`decisionId`,`decisionDefinitionKey`],FORM:[`formId`,`formKey`,`withFormKey`]},pc={JOB_TYPE:[[`JobWorker`,`type`],[`ZeebeWorker`,`type`]],TOPIC:[[`ExternalTaskSubscription`,`topicName`],[`ExternalTaskSubscription`,`value`]]},mc={PROCESS:[`process_definition_key`,`bpmn_process_id`,`start_process_instance_by_key`,`create_process_instance_by_key`,`start_process_instance_by_key_and_tenant_id`],JOB_TYPE:[`job_type`],TOPIC:[`subscribe`,`topic_name`],MESSAGE:[`correlate_message`,`create_message_correlation`,`message_name`],SIGNAL:[`broadcast_signal`,`throw_signal`,`signal_name`],DECISION:[`evaluate_decision_by_key`,`evaluate_decision_table_by_key`,`decision_id`,`decision_key`,`decision_definition_key`],FORM:[`form_id`,`form_key`],ERROR:[`handle_bpmn_error`,`error_code`]},hc=[`BpmnError`,`ZeebeBpmnError`,`CamundaBpmnError`],gc=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);function _c(e){let t=[];return(fc[e]??[]).forEach(e=>t.push({name:e})),(pc[e]??[]).forEach(([e,n])=>t.push({name:n,qualifier:e})),(mc[e]??[]).forEach(e=>t.push({name:e})),e===`ERROR`&&(hc.forEach(e=>t.push({name:e})),t.push({name:`handleBpmnError`,after:`(?:"[^"]*"|'[^']*')\\s*,\\s*`},{name:`errorCode`},{name:`bpmnError`})),t}function vc(e){let t=e.qualifier===void 0?`(?<![\\w$])${gc(e.name)}\\s*(?:\\(\\s*|=\\s*)`:`@${gc(e.qualifier)}\\s*\\(\\s*${gc(e.name)}\\s*=\\s*`;return new RegExp(t+(e.after??``),`g`)}const yc=e=>e.qualifier===void 0?e.name:`@${e.qualifier}(${e.name}`,bc=new Map([...dc].map(e=>[e,_c(e)]));new Map([...bc].map(([e,t])=>[e,new Set(t.map(e=>e.name))]));const xc={PROCESS:[{tag:`process`,attribute:`id`},{attribute:`calledElement`},{tag:`calledElement`},{tag:`CalledElement`,tagPrefix:oc,attribute:`processId`}],JOB_TYPE:[{attribute:`type`}],TOPIC:[{tag:`topic`,tagPrefix:$,attribute:`topic`},{attribute:`topic`,attributePrefix:$}],MESSAGE:[{tag:`message`,attribute:`name`}],SIGNAL:[{tag:`signal`,attribute:`name`}],DECISION:[{tag:`decision`,attribute:`id`},{tag:`decisionRef`,attribute:`decisionId`},{tag:`decisionId`},{attribute:`decisionRef`},{tag:`CalledDecision`,tagPrefix:oc,attribute:`decisionId`}],FORM:[{attribute:`formKey`,attributePrefix:`*`},{tag:`formKey`,tagPrefix:`*`},{tag:`FormDefinition`,tagPrefix:oc,attribute:`formId`},{tag:`formId`,tagPrefix:oc},{attribute:`formRef`,attributePrefix:$},{tag:`formRef`,tagPrefix:$}],CLASS:[{tag:`class`,tagPrefix:$},{attribute:`class`,attributePrefix:$}],BEAN:[{tag:`delegateExpression`,tagPrefix:$,expression:!0},{tag:`delegateExpression`,tagPrefix:$,attribute:`delegateExpression`,expression:!0},{attribute:`delegateExpression`,attributePrefix:$,expression:!0}],ERROR:[{tag:`error`,attribute:`errorCode`},{attribute:`errorCode`,attributePrefix:`*`}]},Sc=/<([A-Za-z_][\w.:-]*)((?:"[^"]*"|'[^']*'|[^>"'])*)>/g,Cc=/([A-Za-z_][\w.:-]*)\s*=\s*("[^"]*"|'[^']*')/g,wc=/"id"\s*:\s*"([^"]*)"/g,Tc=[`"`,`'`,"`"];function Ec(e,t){if(t<0||e.length===0)return null;let n=Math.min(t,e.length-1),r=e.lastIndexOf(`
16
- `,Math.max(n-1,0))+1,i=-1;for(let t=n;t>=r;--t)if(Tc.includes(e[t])){i=t;break}if(i<0)return null;let a=e[i];for(let t=i+1;t<e.length;t+=1)if(e[t]===`\\`)t+=1;else if(e[t]===a)return{first:i,last:t};else if(e[t]===`
17
- `)return null;return null}const Dc=(e,t)=>Tc.includes(e[t])?Ec(e,t):null,Oc=(e,t)=>e.slice(t.first+1,Math.max(t.last,t.first+1));function kc(e,t){let n=[];for(let r=t.indexOf("${");r>=0;r=t.indexOf("${",r+1)){let i=r+2;if(!t.startsWith(e,i)||t[i+e.length]!==`}`)continue;let a=Ec(t,r);a&&Oc(t,a).startsWith("${")&&n.push({start:i,end:i+e.length,where:`expression`})}return n}function Ac(e,t,n){if(!t)return[];if(e===`BEAN`)return kc(t,n);let r=/* @__PURE__ */ new Map;for(let i of bc.get(e)??[])for(let e of n.matchAll(vc(i))){let a=Dc(n,e.index+e[0].length);a&&Oc(n,a)===t&&(r.has(a.first+1)||r.set(a.first+1,{start:a.first+1,end:a.last,where:yc(i)}))}return[...r.values()].sort((e,t)=>e.start-t.start)}function jc(e,t,n,r,i){return r.expression?!e.startsWith("${")||!e.includes(`}`)?null:{start:t+2,end:t+e.indexOf(`}`),where:i}:e===n?{start:t,end:t+n.length,where:i}:null}function Mc(e,t,n){if(!t)return[];let r=xc[e]??[],i=/* @__PURE__ */ new Map,a=e=>{e&&!i.has(e.start)&&i.set(e.start,e)};for(let e of n.matchAll(Sc)){let i=e[1],o=e[2],s=e.index,c=s+1+i.length;for(let o of r.filter(e=>e.attribute===void 0&&uc(e,i,``))){let r=s+e[0].length,c=n.indexOf(`<`,r);c>=0&&a(jc(n.slice(r,c),r,t,o,i))}for(let e of o.matchAll(Cc)){let n=e[1],o=e[2],s=o.slice(1,-1),l=c+e.index+e[0].length-o.length+1;for(let e of r.filter(e=>e.attribute!==void 0&&uc(e,i,n)))a(jc(s,l,t,e,`${i}@${n}`))}}return[...i.values()]}function Nc(e,t,n){return e!==`FORM`||!t?[]:[...n.matchAll(wc)].filter(e=>e[1]===t).map(e=>{let n=e.index+e[0].length-1;return{start:n-t.length,end:n,where:`id`}})}function Pc(e){return e.trim()!==``&&![...e].some(e=>/[\u0000-\u001f\u007f-\u009f]/.test(e)||`"'<>&\\\``.includes(e))}const Fc=e=>dc.has(e),Ic=Pc,Lc=e=>/\.form$/i.test(e)?`form`:/\.(bpmn|bpmn\.xml|bpmn20\.xml|dmn)$/i.test(e)?`diagram`:`code`;function Rc(e,t,n,r){let i=[];for(let a of e){if(a.path===r)continue;let e=Lc(a.path);(e===`form`?Nc(t,n,a.text):e===`diagram`?Mc(t,n,a.text):Ac(t,n,a.text)).forEach(t=>i.push({file:a.path,start:t.start,end:t.end,where:e,label:t.where}))}return i}function zc(e){let t=new Set(e.map(e=>e.file)).size,n=e.filter(e=>e.where!==`code`).length;return f(`app.vscode.rename.summary`,{files:f(`app.vscode.rename.files`,{count:t}),diagrams:n,code:e.length-n})}const Bc=mn(Bt),Vc=4e3,Hc={JAVA_CLASS:[`CLASS`],BEAN:[`BEAN`],JOB_TYPE:[`JOB_TYPE`,`TOPIC`]},Uc=/* @__PURE__ */ new Set([`PROCESS`,`JOB_TYPE`,`TOPIC`,`MESSAGE`,`SIGNAL`,`DECISION`,`FORM`,`CLASS`,`BEAN`,`ERROR`]);function Wc(e){return Ht(`sha256`).update(e).digest(`hex`)}async function Gc(e,t){let n=L(e.body),r=R(n,`kind`),i=R(n,`value`),a=Hc[r];if(!a)throw I(400,`app.cli.web.reason.wrongField`,{field:`kind`});if(i.length===0||i.length>500)throw I(400,`app.cli.web.reason.wrongField`,{field:`value`});let{index:o}=await t.code.state(()=>t.project.listing()),s=/* @__PURE__ */ new Set;return{places:a.flatMap(e=>ze(o,{kind:e,value:i})).filter(e=>{let t=`${e.file}#${e.line}`;return!s.has(t)&&(s.add(t),!0)}).map(e=>({path:e.file,line:e.line,label:`${v.basename(e.file)}:${e.line}`}))}}async function Kc(e,t){let n=t.confine.resolve(R(L(e.body),`path`)),{index:r,targets:i}=await t.code.state(()=>t.project.listing());return{uses:rc(n,r,i)}}async function qc(e,t){let{index:n,targets:r}=await t.code.state(()=>t.project.listing());return{names:ac(n,r)}}async function Jc(e,t){try{return{ok:!0,out:(await Bc(`git`,t,{cwd:e,encoding:`utf8`,timeout:1e4,maxBuffer:67108864,env:{...process.env,GIT_TERMINAL_PROMPT:`0`,GIT_OPTIONAL_LOCKS:`0`}})).stdout}}catch{return{ok:!1,out:``}}}async function Yc(e,t){let n=t.confine.resolve(R(L(e.body),`path`)),r=v.dirname(n),i=await Jc(r,[`rev-parse`,`--is-inside-work-tree`]);if(!i.ok||i.out.trim()!==`true`)return{tracked:!1,before:null};let a=await Jc(r,[`show`,`HEAD:./${v.basename(n)}`]);return{tracked:!0,before:a.ok?a.out:null}}async function Xc(e){try{let t=await k(e);return!t.isFile()||t.size>33554432?null:await Xt(e,`utf8`)}catch{return null}}function Zc(e,t,n){if(e.confine.writeKind(t))return;let r=e.confine.segments(t),i=r.slice(0,-1).some(e=>e.startsWith(`.`));if(!Ue.test(r[r.length-1]??``)||i)throw I(403,`app.cli.web.reason.notEditable`,{path:n.slice(0,200)})}async function Qc(e,t){let n=await e.project.listing(),{sources:r}=await e.code.state(()=>e.project.listing()),i=/* @__PURE__ */ new Set([...n.files.map(e=>e.path),...r.map(e=>e.path)]);if(i.delete(t),i.size>Vc)throw I(400,`app.cli.web.reason.tooMany`);let a=[];for(let e of i){let t=await Xc(e);t!==null&&a.push({path:e,text:t})}return a}function $c(e){let t=L(e.body),n=R(t,`kind`);if(!Uc.has(n))throw I(400,`app.cli.web.reason.wrongField`,{field:`kind`});return{kind:n,from:R(t,`from`),to:R(t,`to`),path:R(t,`path`)}}function el(e,t){let n=1;for(let r=0;r<t&&r<e.length;r+=1)e.charCodeAt(r)===10&&(n+=1);return n}async function tl(e,t){let n=$c(e),r=t.confine.resolve(n.path),i={offered:!1,sites:[],files:[]};if(!Fc(n.kind)||!n.from.trim()||!Ic(n.to))return{...i,detail:f(`app.vscode.rename.notRenamable`)};if(!await K(t))return i;let a=await Qc(t,r),o=Rc(a,n.kind,n.from,r);if(o.length===0)return{...i,detail:f(`app.vscode.rename.nothingElse`,{name:n.from})};let s=new Map(a.map(e=>[e.path,e.text])),c=[...new Set(o.map(e=>e.file))];return{offered:!0,summary:zc(o),sites:o.map(e=>({path:e.file,where:e.where,label:e.label,line:el(s.get(e.file)??``,e.start)})),files:c.map(e=>({path:e,version:Wc(s.get(e)??``)}))}}function nl(e,t,n){let r=e;for(let e of[...t].sort((e,t)=>t.start-e.start))r=`${r.slice(0,e.start)}${n}${r.slice(e.end)}`;return r}async function rl(e,t){let n=v.join(v.dirname(e),`.${v.basename(e)}.${process.pid}.${Ut(4).toString(`hex`)}.tmp`),r=await k(e).catch(()=>null);return await $t(n,t,{mode:r?r.mode&511:420}),n}async function il(e,t){let n=$c(e),r=L(e.body);if(!Fc(n.kind)||!n.from.trim()||!Ic(n.to))throw I(400,`app.cli.web.reason.wrongField`,{field:`to`});if(!await K(t))throw I(403,`app.cli.webHost.reason.notLicensed`);let i=t.confine.resolve(n.path),a=V(r,`files`).map(e=>{let t=L(e);return{path:R(t,`path`),version:R(t,`version`)}});if(a.length===0||a.length>Vc)throw I(400,`app.cli.web.reason.badFileList`);let o=[];for(let e of a){let n=t.confine.resolve(e.path);if(Zc(t,n,e.path),n===i)throw I(400,`app.cli.web.reason.wrongField`,{field:`files`});let r=await Xc(n);if(r===null||Wc(r)!==e.version)throw I(409,`app.cli.webHost.reason.changedSince`,{file:t.confine.relative(n).slice(0,200)});o.push({path:n,text:r})}let s=Rc(o,n.kind,n.from,i),c=[];try{for(let e of o){let t=s.filter(t=>t.file===e.path);t.length!==0&&c.push({target:e.path,temporary:await rl(e.path,nl(e.text,t,n.to)),before:e.text})}for(let e of c){let n=await Xc(e.target);if(n===null||n!==e.before)throw I(409,`app.cli.webHost.reason.changedSince`,{file:t.confine.relative(e.target).slice(0,200)})}let e=[];try{for(let t of c)await D(t.temporary,t.target),e.push(t)}catch(t){for(let t of e.reverse()){let e=await rl(t.target,t.before);await D(e,t.target).catch(()=>O(e,{force:!0}))}throw t}}finally{await Promise.all(c.map(e=>O(e.temporary,{force:!0}).catch(()=>void 0)))}return{places:s.length,files:c.length}}function al(e){throw e instanceof l?I(400,`app.cli.webHost.reason.licence`,{detail:e.message}):I(502,`app.cli.webHost.reason.licenceService`,{detail:e instanceof Error?e.message:String(e)})}async function ol(e,t){let n=R(L(e.body),`key`).trim();if(n.length<8||n.length>200)throw I(400,`app.cli.webHost.reason.keyShape`);try{await i(n,{env:t.env})}catch(e){al(e)}return pa(t),ma(t)}async function sl(e,t){try{if(await o({env:t.env})===`none`)throw I(409,`app.cli.webHost.reason.nothingToRelease`)}catch(e){if(e instanceof Error&&e.name===`WebFailure`)throw e;al(e)}return pa(t),ma(t)}async function cl(e,t){let n=L(e.body),r=R(n,`tier`);if(r!==`PRO`&&r!==`TEAM`)throw I(400,`app.cli.web.reason.wrongField`,{field:`tier`});let i=typeof n.email==`string`&&n.email.trim()?n.email.trim().slice(0,200):void 0;try{return{url:(await a(r===`PRO`?`pro`:`team`,i,{env:t.env})).url}}catch(e){throw I(502,`app.cli.webHost.reason.licenceService`,{detail:e instanceof Error?e.message:String(e)})}}const ll=[{method:`POST`,path:`/web/code/locate`,operationId:`locateCode`,limit:N,run:Gc},{method:`POST`,path:`/web/code/uses`,operationId:`findCodeUses`,limit:N,run:Kc},{method:`GET`,path:`/web/code/names`,operationId:`listProjectNames`,run:qc},{method:`POST`,path:`/web/compare`,operationId:`compareWithHead`,limit:N,run:Yc},{method:`POST`,path:`/web/linked-rename/plan`,operationId:`planLinkedRename`,limit:N,run:tl},{method:`POST`,path:`/web/linked-rename/apply`,operationId:`applyLinkedRename`,limit:N,run:il},{method:`POST`,path:`/web/licence/activate`,operationId:`activateLicence`,limit:N,run:ol},{method:`POST`,path:`/web/licence/checkout`,operationId:`startLicenceCheckout`,limit:N,run:cl},{method:`POST`,path:`/web/licence/deactivate`,operationId:`deactivateLicence`,limit:N,run:sl}],ul=[{method:`GET`,path:`/web/lsp/servers`,operationId:`listLanguageServers`,run:(e,t)=>({servers:ls(t.home,t.env).map(e=>({id:e.id,label:e.command,languages:e.languages,available:e.found!==null,configured:e.configured}))})},{method:`GET`,path:`/web/lsp/messages`,operationId:`nextLspMessages`,held:!0,run:async(e,t)=>({messages:await t.events.nextMessages(e.client,e.signal)})},{method:`POST`,path:`/web/lsp/{serverName}/message`,operationId:`sendLspMessage`,limit:P,run:(e,t)=>{t.servers.send(e.client,e.params.serverName,e.body)}}],dl=/* @__PURE__ */ new Set([`JOB_TYPE`,`TOPIC`,`CLASS`,`BEAN`,`MESSAGE`,`PROCESS`,`DECISION`]),fl=/* @__PURE__ */ new Set([`execution`,`task`]);function pl(e,t){if(e.length>500)throw I(400,`app.cli.web.reason.wrongField`,{field:t});return e}function ml(e){let t=L(e),n=R(t,`kind`);if(!dl.has(n))throw I(400,`app.cli.web.reason.wrongField`,{field:`kind`});let r=t.listener;if(r!==void 0&&(typeof r!=`string`||!fl.has(r)))throw I(400,`app.cli.web.reason.wrongField`,{field:`listener`});return{kind:n,value:pl(R(t,`value`),`value`),...r?{listener:r}:{}}}function hl(e){let t=L(e),n=V(t,`elements`);if(n.length>2e4)throw I(400,`app.cli.web.reason.tooMany`);return{diagram:pl(R(t,`diagram`),`diagram`),elements:n.map(e=>{let t=L(e),n=V(t,`bindings`);if(n.length>40)throw I(400,`app.cli.web.reason.tooMany`);return{elementId:pl(R(t,`elementId`),`elementId`),elementType:pl(R(t,`elementType`),`elementType`),label:pl(R(t,`label`),`label`),bindings:n.map(ml)}})}}function gl(e,t){let n=/* @__PURE__ */ new Map;for(let r of e)r.kind===t&&!n.has(r.value)&&n.set(r.value,r.path);return n}function _l(e,t,n){return{licensed:!0,statuses:Ie({diagram:n.diagram,index:e,processes:gl(t,`PROCESS`),decisions:gl(t,`DECISION`)},n.elements).map(({reached:e,paused:t,...n})=>n)}}function vl(e,t,n){let r=e.split(/\r\n|\n|\r/);return r[r.length-1]===``&&r.pop(),r.slice(Math.max(0,t-1),Math.max(0,t-1)+n).map(e=>e.replace(/\s+$/,``).slice(0,240))}async function yl(e){let t;try{let n=await k(e);return!n.isFile()||n.size>1048576?null:(t=await Jt(e,`r`),await t.readFile(`utf8`))}catch{return null}finally{await t?.close().catch(()=>void 0)}}const bl=[{method:`POST`,path:`/web/code/status`,operationId:`findCodeStatus`,limit:P,run:async(e,t)=>{let n=hl(e.body);if(!await K(t))return{licensed:!1,statuses:[]};let{index:r,targets:i}=await t.code.state(()=>t.project.listing());return _l(r,i,n)}},{method:`POST`,path:`/web/code/snippet`,operationId:`readCodeSnippet`,limit:N,run:async(e,t)=>{let n=L(e.body),r=R(n,`path`),i=n.line;if(typeof i!=`number`||!Number.isInteger(i)||i<1||i>1e7)throw I(400,`app.cli.web.reason.wrongField`,{field:`line`});let a=n.count;if(a!==void 0&&(typeof a!=`number`||!Number.isInteger(a)||a<1))throw I(400,`app.cli.web.reason.wrongField`,{field:`count`});let o=t.confine.resolve(r);if(!Ue.test(o))throw I(400,`app.cli.web.reason.wrongField`,{field:`path`});let s=await yl(o);return{path:r,line:i,lines:s===null?[]:vl(s,i,Math.min(a??12,12))}}}],xl={workers:[],classes:[],camunda7Imports:[]};var Sl=class{signature=``;analysis={migration:null,facts:xl};async analysisOf(e,t){let n=Ht(`sha1`);e.forEach(e=>n.update(`${e.path}\n${e.text}\n`)),t.forEach(e=>n.update(`${e.file}\n${e.text}\n`));let r=n.digest(`hex`);if(r!==this.signature){let{index:n,facts:i}=await St(e,t.map(e=>({path:e.file,text:e.text}))),a=await Fe({files:e,classes:i.classes,camunda7Imports:i.camunda7Imports,index:n}).catch(()=>null);this.analysis={migration:a,facts:i},this.signature=r}return this.analysis}};function Cl(e){return e.slice(0,Math.max(e.lastIndexOf(`/`),e.lastIndexOf(`\\`),0))}async function wl(e,t){let n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map;for(let i of e){let e=Cl(i);if(!n.has(e)){let r=await t.deployTargets(i).catch(()=>null),a=r?.targets.find(e=>(e.profile??null)===(r.active??null));n.set(e,a?{profile:a.profile??null,engine:a.engine??null,url:a.url??null,ready:a.ready}:null)}let a=n.get(e);a&&r.set(i,a)}return r}async function Tl(e,t,n){let r=await t.reports().catch(()=>[]),i=await t.deployTargets().catch(()=>null),a=t.templates(),o=await n.analysisOf(e.diagrams,e.sources),[s,c]=await Promise.all([Ee(a),Be(a,o.facts.workers)]),l=new Map(c.map(e=>[e.id,e.drift]));return Ve({root:e.root,files:e.files,targets:e.targets,code:e.code,coverage:qe(e.root,r).reach,deploy:i&&{active:i.active,targets:i.targets},debug:[],preferences:{tree:e.preferences?.toolWindowTree!==!1,groupByFiles:e.preferences?.toolWindowGroupByFiles===!0},workersOnEngine:e.workersOnEngine,fileTargets:await wl(e.files.map(e=>e.path),t),codeLinks:e.licensed?`open`:`locked`,migration:o.migration,templates:[...s.values()].map(({path:e,template:t})=>({path:e,template:t,drift:l.get(t.id)??null})),contracts:o.facts.workers.map(e=>({value:e.value,file:e.file,line:e.line,handler:e.handler??null}))})}function El(e,t){return e.elementId===t.elementId&&e.owner===t.owner&&e.index===t.index}async function Dl(e){let t=await Ze(e.text),n=Ge(t).find(t=>El(t.slot,e.slot));if(!n)return null;let r=yn({definitions:t,workers:e.workers,diagramPath:e.path},n.slot.elementId,n.value);return{path:e.path,slot:n.slot,language:n.language,value:n.value,title:Te(n),variables:r}}const Ol=2e4;function kl(e,t){let n=/* @__PURE__ */ new Set,r=[];for(let{handle:i,label:a}of e){if(r.length>=500)break;let e;try{e=t(Ct(i))}catch{e=null}if(!e)continue;let o=xt(i)??1,s=`${e}#${o}`;n.has(s)||(n.add(s),r.push({path:e,line:o,label:a??`${v.basename(e)}:${o}`}))}return r}function Al(e){return{kind:`unsupported`,reason:e}}function jl(e){return e.checks.flatMap(e=>e.check.problem?[`${e.where}: ${e.check.problem}`]:[])}async function Ml(e,t){switch(e.type){case`reveal`:{let n=t.inside(e.path);return n?{kind:`reveal`,path:n,...e.elementId?{elementId:e.elementId}:{}}:Al(f(`app.cli.web.toolWindow.unsupported.outside`))}case`openCode`:return{kind:`openCode`,title:e.title,places:kl(e.handles.map(e=>({handle:e})),e=>t.inside(e))};case`findUsages`:return await t.paid()?{kind:`findUsages`,title:e.title,places:kl(await t.usages(e.subjects),e=>t.inside(e))}:{kind:`unlockCode`};case`copy`:return{kind:`copy`,text:e.text.slice(0,Ol)};case`preference`:return t.savePreference(e.key,e.value),{kind:`preference`,key:e.key,value:e.value};case`deploy`:{let n=e.paths.slice(0,1e3).map(e=>t.inside(e)).filter(e=>e!==null);return n.length===0?Al(f(`app.cli.web.toolWindow.unsupported.outside`)):{kind:`deploy`,paths:n,...e.profile?{profile:e.profile}:{},...e.confirm?{confirm:!0}:{}}}case`createExample`:return{kind:`createExample`,example:e.example};case`unlockCode`:return{kind:`unlockCode`};case`checkWorkers`:{if(!await t.paid())return{kind:`unlockCode`};let n=await t.checkWorkers(e.groups);t.workersChecked(n);let r=jl(n);return r.length>0?{kind:`notify`,text:r.join(`
18
- `).slice(0,Ol),error:!0}:{kind:`refresh`}}case`runTests`:return Al(f(`app.cli.web.toolWindow.unsupported.tests`));case`script`:{let n=await t.script(e.path,e.slot);return n?{kind:`openScript`,path:n.path,slot:n.slot,language:n.language,script:n.value,title:n.title,variables:n.variables}:{kind:`notify`,text:f(`app.cli.web.toolWindow.script.missing`)}}case`migrationConvert`:case`migrationReport`:case`migrationWorker`:return Al(f(`app.cli.web.toolWindow.unsupported.migration`));case`workerTemplate`:case`workerTemplateAt`:case`templateWorker`:return Al(f(`app.cli.web.toolWindow.unsupported.templates`))}}const Nl=/^[\w .-]{1,80}$/;function Pl(e,t){let n=t,r=!1,i=e=>{let t=[];for(let a of e){if(n<=0){r=!0;break}--n,t.push(a.children&&a.children.length>0?{...a,children:i(a.children)}:a)}return t};return{roots:i(e),truncated:r}}async function Fl(e,t){let n;try{let r=await k(e);return!r.isFile()||r.size>t?null:(n=await Jt(e,`r`),await n.readFile(`utf8`))}catch{return null}finally{await n?.close().catch(()=>void 0)}}function Il(e,t){let n=e.folder;return{root:async()=>n,list:async()=>t.templates.map(e=>v.relative(n,e.path).split(v.sep).join(`/`)),read:async t=>Fl(e.confine.resolve(v.join(n,t)),2097152),write:async(t,r)=>{let i=e.confine.resolve(v.join(n,t));e.confine.writable(i,t),await T(v.dirname(i),{recursive:!0}),await $t(i,r)}}}async function Ll(e){return(await Promise.all(e.reports.map(async e=>{let t=await Fl(e.path,16777216);return t===null?null:{path:e.path,stamp:e.stamp,text:t}}))).filter(e=>e!==null)}function Rl(e,t,n){let r=new Map(n.diagrams.map(e=>[e.path,e.text]));return{reports:()=>Ll(t),deployTargets:async t=>Li(Ta(e,t??null,t&&r.get(t)||``)),templates:()=>Il(e,t)}}function zl(e,t){let n=/* @__PURE__ */ new Map;if(t)for(let t of Oe(e.models,e.targets)){let r=bt(e.index,t,e=>yt(e.file,e.line));r.length>0&&n.set(Le(t),r)}return{precise:t,links:n}}var Bl=class{current=null;building=null;memo=new Sl;workers=null;serial=0;keyOf(e,t,n){return[e.id,e.project.scans,e.code.builds,e.configs.generation,t?`paid`:`free`,n.toolWindowTree===!1?`flat`:`tree`,n.toolWindowGroupByFiles===!0?`files`:`kinds`,this.serial].join(`.`)}async snapshot(e){let t=await e.project.listing(),n=await e.code.state(()=>e.project.listing()),r=await K(e),i=new h(e.home).read(),a=this.keyOf(e,r,i);if(this.current?.key===a)return this.current.built;if(this.building?.key===a)return this.building.promise;let o=this.build(e,t,n,r,i,a),s={key:a,promise:o};this.building=s;try{return await o}finally{this.building===s&&(this.building=null)}}async build(e,t,n,r,i,a){let o=await Tl({root:e.folder,files:n.models,targets:n.targets,code:zl(n,r),licensed:r,diagrams:n.diagrams,sources:n.sources.map(e=>({file:e.path,text:e.text})),preferences:i,workersOnEngine:this.workers},Rl(e,t,n),this.memo),{roots:s,truncated:c}=Pl(o.roots,5e4),l={revision:a,roots:s,toolbar:o.toolbar,codeLinks:r?`open`:`locked`,truncated:c,actions:o.actions};return this.current={key:a,built:l},l}async perform(e,t){let n=this.current?.built.actions.get(t);if(!n)throw I(400,`app.cli.web.reason.noSuchAction`);return Ml(n,this.hostFor(e))}revision(){return this.current?.built.revision??null}knows(e){return this.current?.built.actions.has(e)??!1}hostFor(e){return{inside:t=>{try{return e.confine.resolve(t)}catch{return null}},usages:async t=>{let{index:n}=await e.code.state(()=>e.project.listing());return t.flatMap(e=>bt(n,e,e=>yt(e.file,e.line)).map(e=>({handle:e.handle,label:e.label})))},script:async(t,n)=>{let{diagrams:r,workers:i}=await e.code.state(()=>e.project.listing()),a=r.find(e=>e.path===t);return a?Dl({path:t,text:a.text,slot:n,workers:i}):null},paid:()=>K(e),savePreference:(t,n)=>{let r=new h(e.home);r.write({...r.read(),[t]:n})},checkWorkers:t=>this.checkWorkers(e,t),workersChecked:e=>{this.workers=e,this.serial+=1}}}async checkWorkers(e,t){let n=await Promise.all(t.slice(0,50).map(async t=>{let n=t.jobTypes.slice(0,2e3);try{if(t.profile!==null&&!Nl.test(t.profile))throw new F(400,`profile`);let r=e.confine.resolve(t.resource),i=await Promise.all(He(t.engine,n,/* @__PURE__ */ new Date).map(n=>Da(e,{method:n.method,path:n.path,body:n.body,parts:n.parts},t.profile,r)));return{where:t.where,engine:t.engine,check:Pe(t.engine,n,i)}}catch(e){return{where:t.where,engine:t.engine,check:{statuses:/* @__PURE__ */ new Map,problem:e instanceof Error?e.message:String(e)}}}}));return{at:(/* @__PURE__ */ new Date()).toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`,hourCycle:`h23`}),checks:n}}};const Vl=/* @__PURE__ */ new WeakMap;function Hl(e){let t=Vl.get(e);return t||(t=new Bl,Vl.set(e,t)),t}const Ul=[{method:`GET`,path:`/web/tool-window`,operationId:`getToolWindow`,run:async(e,t)=>{let n=e.query.get(`revision`);if(n!==null&&n.length>200)throw I(400,`app.cli.web.reason.wrongField`,{field:`revision`});let{actions:r,...i}=await Hl(t).snapshot(t);return n===i.revision?{revision:i.revision,unchanged:!0}:i}},{method:`POST`,path:`/web/tool-window/perform`,operationId:`performToolWindowAction`,limit:N,run:async(e,t)=>{let n=L(e.body),r=R(n,`id`),i=R(n,`revision`);if(r.length>64||i.length>200)throw I(400,`app.cli.web.reason.wrongField`,{field:`id`});let a=Hl(t),o=a.revision();if(o===null||o!==i)throw I(409,`app.cli.web.reason.staleToolWindow`);if(!a.knows(r))throw I(400,`app.cli.web.reason.noSuchAction`);return a.perform(t,r)}}],Wl=Ba.map(e=>e.operationId===`getConfig`?{...e,run:(t,n)=>n.open?e.run(t,n):$s(n)}:e),Gl=[..._a,...eo,...so,...Wl,...ro,...Gr,...Qs,...Zs,...qo,...To,...ll,...xr,...bl,...Ul,...co,...ul],Kl=/* @__PURE__ */ new Set([`getLicense`,`requestFeature`,`showLicenceOffer`,`getTheme`,`getPreferences`,`savePreferences`,`getDialogButtonOrder`,`notifyUser`,`openExternalLink`,`nextHostEvent`,`fetchConnectorUrl`,`connectorFile`,`getCurrentProject`,`openProject`,`closeProject`,`listRecentProjects`,`forgetRecentProject`,`listFolders`]),ql=new Set(co.map(e=>e.operationId));function Jl(e){return e.operationId===`getConfig`?`checked`:Kl.has(e.operationId)||yr.has(e.operationId)||ql.has(e.operationId)?`none`:`required`}function Yl(e){let t=e.map(e=>({route:e,parts:e.path.split(`/`)}));return(e,n)=>{let r=n.split(`/`),i=[];for(let{route:n,parts:a}of t){if(a.length!==r.length)continue;let t={},o=!0;for(let e=0;e<a.length&&o;e+=1){let n=a[e];if(n.startsWith(`{`)&&n.endsWith(`}`)){if(r[e]===``){o=!1;break}try{t[n.slice(1,-1)]=decodeURIComponent(r[e])}catch{o=!1}}else n!==r[e]&&(o=!1)}if(o){if(n.method===e)return{kind:`found`,route:n,params:t};i.push(n.method)}}return i.length>0?{kind:`method`,allowed:i}:{kind:`none`}}}const Xl=Yl(Gl),Zl=/* @__PURE__ */ new Set([`0.0.0.0`,`::`]),Ql=[`127.0.0.1`,`localhost`,`[::1]`];function $l(){return Ut(32).toString(`base64url`)}function eu(e,t){return typeof e!=`string`||e.length===0||e.length>512?!1:Gt(Ht(`sha256`).update(e).digest(),Ht(`sha256`).update(t).digest())}function tu(e){let t=[],n=e[`x-penstock-token`];typeof n==`string`&&t.push(n);let r=e.cookie;if(typeof r==`string`&&r.length<=8192)for(let e of r.split(`;`)){let n=e.indexOf(`=`);n>0&&e.slice(0,n).trim()===`penstock_web`&&t.push(e.slice(n+1).trim())}return t}function nu(e,t){return tu(e).some(e=>eu(e,t))}function ru(e){let t=e[`x-penstock-resource`];if(typeof t!=`string`||t.length===0)return null;try{return decodeURIComponent(t)}catch{return t}}function iu(e){return`penstock_web=${e}; Path=/; HttpOnly; SameSite=Strict`}function au(e){return e===`::1`||e===`localhost`||e.startsWith(`127.`)}function ou(e){return e.includes(`:`)&&!e.startsWith(`[`)?`[${e}]`:e}function su(e){let t=/^(\[[0-9a-f:.]+\]):(\d{1,5})$/.exec(e);if(t)return{name:t[1],port:t[2]};let n=/^([a-z0-9.-]+):(\d{1,5})$/.exec(e);return n?{name:n[1],port:n[2]}:null}function cu(e,t){let n=Zl.has(e),r=new Set(Ql.map(e=>`${e}:${t}`));return!n&&!au(e)&&r.add(`${ou(e).toLowerCase()}:${t}`),{allowsHost:e=>{if(typeof e!=`string`||e.length===0||e.length>300)return!1;let i=e.toLowerCase();if(r.has(i))return!0;if(!n)return!1;let a=su(i);return a!==null&&Number(a.port)===t&&hn(a.name.replace(/^\[|\]$/g,``))!==0},allowsOrigin(e,t){return e===void 0||e.toLowerCase()===`http://${t.toLowerCase()}`}}}function lu(e){let t=e[`sec-fetch-site`];return t===void 0||t===`same-origin`||t===`none`}export{Dn as A,er as C,Yn as D,N as E,wn as F,Cn as I,En as M,Tn as N,M as O,Nn as P,F as S,Xn as T,wr as _,cu as a,cr as b,ru as c,Yl as d,Jl as f,Tr as g,Dr as h,nu as i,Mn as j,Bn as k,eu as l,Or as m,iu as n,au as o,Vs as p,lu as r,$l as s,ou as t,Xl as u,Cr as v,I as w,or as x,vr as y};
15
+ `)].join(`\0`)}function ws(e,t){return Cs(e)===Cs(t)}var Ts=class{root;limits;cached=null;cachedGeneration=-1;generation=0;building=null;scans=0;constructor(e,t=gs){this.root=e,this.limits=t}peek(){return this.cached}invalidate(){this.generation+=1}async listing(){for(;;){if(this.cached&&this.cachedGeneration===this.generation)return this.cached;if(!this.building){let e=this.generation;this.scans+=1,this.building=Ss(this.root,this.limits).then(t=>(this.cached=t,this.cachedGeneration=e,t)).finally(()=>{this.building=null})}await this.building}}},Es=class{runs=/* @__PURE__ */ new Map;start(e){let t=Wt(),n=new AbortController,r={abort:n,status:`running`};return this.runs.set(t,r),e(n.signal).catch(e=>({ok:!1,lines:[e instanceof Error?e.message:String(e)]})).then(e=>{r.status===`running`&&(r.status=`finished`),r.result=e}),t}active(){let e=0;for(let t of this.runs.values())t.status===`running`&&(e+=1);return e}state(e){let t=this.runs.get(e);if(t)return(t.status===`finished`||t.status===`cancelled`&&t.result)&&this.runs.delete(e),{run:e,status:t.status,ok:t.status===`finished`&&(t.result?.ok??!1),lines:t.result?.lines??[]}}cancel(e){let t=this.runs.get(e);t?.status===`running`&&(t.status=`cancelled`,t.abort.abort())}};const Ds=/* @__PURE__ */ new Set([`.camunda`]),Os=/(~|\.(tmp|swp|swx|bak|lock|crdownload|part))$|^\.#|^\.DS_Store$|^4913$/i;function ks(e){let t=e.split(/[\\/]/).filter(e=>e!==``);return Os.test(t[t.length-1]??``)?!0:t.slice(0,-1).some(e=>_.has(e)||e.startsWith(`.`)&&!Ds.has(e))}var As=class{root;onBatch;debounceMs;maxWaitMs;firstRetryMs;maxRetryMs;pollMs;open;pending=/* @__PURE__ */ new Set;watcher=null;quiet=null;deadline=null;retry=null;poll=null;retryMs;closed=!1;constructor(e,t,n={}){this.root=e,this.onBatch=t,this.debounceMs=n.debounceMs??80,this.maxWaitMs=n.maxWaitMs??600,this.firstRetryMs=n.retryMs??250,this.maxRetryMs=n.maxRetryMs??5e3,this.pollMs=n.pollMs??3e3,this.retryMs=this.firstRetryMs,this.open=n.open??((e,t)=>Rt(e,{recursive:!0,persistent:!1},t))}get active(){return this.watcher!==null||this.poll!==null}start(){this.attach(!1)}close(){this.closed=!0,this.detach();for(let e of[this.quiet,this.deadline,this.retry,this.poll])e&&clearTimeout(e);this.quiet=this.deadline=this.retry=this.poll=null,this.pending.clear()}attach(e){if(!(this.closed||this.watcher||this.poll)){if(!b(this.root))return this.later();try{this.watcher=this.open(this.root,(e,t)=>this.heard(t))}catch(e){return e?.code===`ERR_FEATURE_UNAVAILABLE_ON_PLATFORM`?this.polling():this.later()}this.watcher.on(`error`,()=>{this.detach(),this.heard(null),this.later()}),this.retryMs=this.firstRetryMs,e&&this.heard(null)}}polling(){this.poll=setInterval(()=>this.heard(null),this.pollMs),this.poll.unref()}detach(){let e=this.watcher;if(this.watcher=null,e){e.removeAllListeners(),e.on(`error`,()=>void 0);try{e.close()}catch{}}}later(){this.closed||this.retry||(this.retry=setTimeout(()=>{this.retry=null,this.attach(!0)},this.retryMs),this.retry.unref(),this.retryMs=Math.min(this.retryMs*2,this.maxRetryMs))}heard(e){if(this.closed)return;let t=e===null?`*`:e.toString();t!==`*`&&ks(t)||(this.pending.add(t===``?`*`:t),this.quiet&&clearTimeout(this.quiet),this.quiet=setTimeout(()=>this.flush(),this.debounceMs),this.quiet.unref(),this.deadline||(this.deadline=setTimeout(()=>this.flush(),this.maxWaitMs),this.deadline.unref()))}flush(){if(this.quiet&&clearTimeout(this.quiet),this.deadline&&clearTimeout(this.deadline),this.quiet=this.deadline=null,this.closed||this.pending.size===0)return;let e=[...this.pending];this.pending.clear(),this.watcher&&!b(this.root)&&(this.detach(),this.later());try{this.onBatch(e.map(e=>e===`*`?e:v.join(this.root,e)))}catch{}}};const js={password:`PENSTOCK_PASSWORD`,clientSecret:`PENSTOCK_CLIENT_SECRET`};function Ms(e){let t=/* @__PURE__ */ new Map,n=(e,t)=>`${e??``}\u0000${t}`;return{async get(r,i){return t.get(n(r,i))??(e[js[i]]||void 0)},async set(e,r,i){i?t.set(n(e,r),i):t.delete(n(e,r))}}}const Ns=/^penstock(\.local)?\.(ya?ml|json)$/i;function Ps(e){let t=e.env??process.env;return{env:t,home:e.home??te(t),fetch:e.fetch??fetch,openLink:e.openLink??(()=>void 0),say:e.say??(()=>void 0),events:new ur(e.events),limits:e.limits??gs,sourceLimits:e.sourceLimits,watcher:e.watcher,agent:e.agent??{}}}function Fs(e,t){let n=new cr(e),r=new Ts(n.root,t.limits),i=new Xo(n.root,t.env),a=new rs(n.root,t.sourceLimits),o=t.events,s=new hs(n.root,t.home,t.env,o),c=o.onForget(e=>s.forget(e)),l=!1,u={id:Ut(6).toString(`hex`),open:!0,folder:n.root,confine:n,project:r,configs:i,code:a,servers:s,events:o,env:t.env,home:t.home,secrets:Ms(t.env),history:new Pi,hooks:new Es,agent:new ve(n.root,t.agent.spawn??(e=>Is(e,t.env)),{home:t.home,env:t.env}),fetch:t.fetch,openLink:t.openLink,say:t.say,async changed(e){if(l)return;let t=r.peek(),n=e.includes(`*`),s=n||e.some(e=>Ns.test(v.basename(e))),c=e.some(e=>e!==`*`&&Ie.test(e)),u=n||e.some(e=>/\.(bpmn|bpmn\.xml|bpmn20\.xml|dmn|form)$/i.test(e));r.invalidate(),s&&i.invalidate(),(n||c||u)&&a.invalidate();let d=await r.listing().catch(()=>null);l||(!s&&t&&d&&ws(t,d)||o.publish({type:`projectChanged`}),c&&o.publish({type:`codeChanged`}))},close(){l=!0,u.agent.close(),c(),s.close(),d.close()}},d=new As(n.root,e=>void u.changed(e).catch(()=>void 0),t.watcher);return d.start(),u}function Is(t,n){let r=xe();if(!r)throw new _e(500,f(`app.agent.notFound`));return Dt({explicit:Et(n),own:r,version:e()},[`agent`,`serve`,`--project`,t]).map(({command:e,args:t,env:n})=>({command:e,args:t,env:n}))}function Q(){throw I(409,`app.cli.web.reason.noProject`)}function Ls(e){return{id:`closed`,open:!1,folder:``,get confine(){return Q()},get project(){return Q()},get configs(){return Q()},get code(){return Q()},get servers(){return Q()},get secrets(){return Q()},get history(){return Q()},get hooks(){return Q()},get agent(){return Q()},events:e.events,env:e.env,home:e.home,fetch:e.fetch,openLink:e.openLink,say:e.say,async changed(){},close(){}}}function Rs(e){return e.HOME||e.USERPROFILE||kt()}function zs(e,t){return e===`~`?t:e.startsWith(`~/`)||e.startsWith(`~\\`)?v.join(t,e.slice(2)):e}function Bs(e,t){if(typeof e!=`string`||e.trim()===``||e.length>4096||e.includes(`\0`))throw I(400,`app.cli.web.reason.badFolder`,{folder:String(e).replace(/[\u0000-\u001f\u007f]/g,`?`).slice(0,200)});let n=zs(e.trim(),t);if(!v.isAbsolute(n))throw I(400,`app.cli.web.reason.notAbsolute`,{folder:e.slice(0,200)});return v.resolve(n)}function Vs(e){return C(e,{throwIfNoEntry:!1})?.isDirectory()===!0}var Hs=class{shared;current;idle;requests=/* @__PURE__ */ new Map;deploys=0;constructor(e){this.shared=Ps(e),this.idle=Ls(this.shared),this.current=this.idle,e.folder!==void 0&&(this.current=Fs(e.folder,this.shared)),this.current.open&&(this.remember(this.current.folder),this.current.project.listing().catch(()=>void 0))}get context(){return this.current}info(){let e=this.current;return e.open?{open:!0,available:e.confine.stands(),id:e.id,name:v.basename(e.folder)||e.folder,folder:e.folder}:{open:!1,available:!1,id:null,name:null,folder:null}}busy(){return this.deploys>0||this.current.open&&this.current.hooks.active()>0}beginDeploy(){this.deploys+=1;let e=!1;return()=>{e||(e=!0,--this.deploys)}}track(e,t){let n=this.requests.get(e);return n||(n=/* @__PURE__ */ new Set,this.requests.set(e,n)),n.add(t),()=>{n.delete(t),n.size===0&&this.requests.get(e)===n&&this.requests.delete(e)}}async open(e){let t=Bs(e,Rs(this.shared.env)),n=C(t,{throwIfNoEntry:!1});if(!n)throw I(404,`app.cli.web.reason.noSuchFolder`,{folder:t.slice(0,200)});if(!n.isDirectory())throw I(400,`app.cli.web.reason.notAFolder`,{folder:t.slice(0,200)});try{await E(t)}catch(e){let n=e.code;throw n===`EACCES`||n===`EPERM`?I(403,`app.cli.web.reason.folderNotReadable`,{folder:t.slice(0,200)}):I(404,`app.cli.web.reason.noSuchFolder`,{folder:t.slice(0,200)})}return this.current.open&&this.current.folder===S.native(t)?this.info():this.swap(()=>Fs(t,this.shared))}async close(){return this.swap(()=>this.idle)}swap(e){if(this.busy())throw I(409,`app.cli.web.reason.switchBusy`);let t=this.current,n=e();return this.current=n,this.shared.events.drop(),this.shared.events.publish({type:`projectChanged`}),t.open&&this.retire(t),n.open&&(this.remember(n.folder),n.project.listing().catch(()=>void 0)),this.info()}retire(e){e.close(),setTimeout(()=>{let t=this.requests.get(e);if(t)for(let e of t)e.abort();this.requests.delete(e)},3e3).unref()}recent(){let e=[];try{e=new h(this.shared.home).recentProjects()}catch{}return e.map(e=>({folder:e,name:v.basename(e)||e,present:Vs(e)}))}lastProject(){return this.recent().find(e=>e.present)?.folder??null}forget(e){let t=Bs(e,Rs(this.shared.env));try{new h(this.shared.home).forgetProject(t)}catch{}return this.recent()}remember(e){try{new h(this.shared.home).rememberProject(e)}catch{}}shutdown(){this.current.close();for(let e of this.requests.values())for(let t of e)t.abort();this.requests.clear(),this.shared.events.close()}};const Us=/\.(bpmn|bpmn\.xml|bpmn20\.xml|dmn|form)$/i,Ws=/^penstock\.(yaml|yml|json)$/i,Gs=new Intl.Collator(`en`,{numeric:!0,sensitivity:`base`});function Ks(e){return Ws.test(e)||Us.test(e)}async function qs(e){let t;try{t=await Yt(e)}catch{return!1}try{for(let e=0;e<4e3;e+=1){let e=await t.read();if(!e)return!1;if(Ks(e.name))return!0}return!1}catch{return!1}finally{await t.close().catch(()=>void 0)}}async function Js(){if(process.platform!==`win32`)return[`/`];let e=Array.from({length:26},(e,t)=>String.fromCharCode(65+t)).map(async e=>{let t=`${e}:\\`;return await Promise.race([k(t).then(()=>!0,()=>!1),new Promise(e=>setTimeout(()=>e(!1),300).unref())])?t:null});return(await Promise.all(e)).filter(e=>e!==null)}function Ys(e,t){let n=e.code,r=t.replace(/[\u0000-\u001f\u007f]/g,`?`).slice(0,200);throw n===`EACCES`||n===`EPERM`?I(403,`app.cli.web.reason.folderNotReadable`,{folder:r}):n===`ENOTDIR`?I(400,`app.cli.web.reason.notAFolder`,{folder:r}):n===`ENOENT`||n===`ELOOP`||n===`ENAMETOOLONG`?I(404,`app.cli.web.reason.noSuchFolder`,{folder:r}):e}async function Xs(e,t){let n=e.lastProject();if(n){let e=v.dirname(n);try{if((await k(e)).isDirectory())return e}catch{}}return t}async function Zs(e,t,n,r=2e4){let i=Rs(e.shared.env),a=t===void 0||t===``?await Xs(e,i):Bs(t,i),o;try{if(o=await Zt(a),!(await k(o)).isDirectory())throw I(400,`app.cli.web.reason.notAFolder`,{folder:a.replace(/[\u0000-\u001f\u007f]/g,`?`).slice(0,200)})}catch(e){return Ys(e,a)}let s;try{s=await E(o,{withFileTypes:!0})}catch(e){return Ys(e,o)}let c=[],l=!1,u=0;for(let e of s){let t=e.name;if(e.isDirectory())c.push({name:t,hidden:t.startsWith(`.`),link:!1});else{if(e.isSymbolicLink()||!e.isFile()&&!e.isDirectory())try{if((await k(v.join(o,t))).isDirectory()){c.push({name:t,hidden:t.startsWith(`.`),link:e.isSymbolicLink()});continue}}catch{continue}Ws.test(t)?l=!0:Us.test(t)&&(u+=1)}}c.sort((e,t)=>Gs.compare(e.name,t.name)||(e.name<t.name?-1:+(e.name>t.name)));let d=c.length,f=d>r?c.slice(0,r):c,p=f.reduce((e,t)=>e+ +!!t.hidden,0),m=!0,ee=Date.now()+1500,te=f.filter(e=>!e.link&&(n||!e.hidden)),h=0;await Promise.all(Array.from({length:Math.min(24,te.length)},async()=>{for(;h<te.length;){if(Date.now()>ee){m=!1;return}let e=te[h];h+=1,await qs(v.join(o,e.name))&&(e.project=!0)}}));let ne=v.dirname(o);return{path:o,parent:ne===o?null:ne,home:i,separator:v.sep,roots:await Js(),entries:f,total:d,truncated:f.length<d,hiddenCount:p,hintsComplete:m,project:l||u>0?{config:l,diagrams:u}:null}}const Qs=[{method:`POST`,path:`/web/folders`,operationId:`listFolders`,limit:N,run:e=>{let t=e.body===void 0?{}:L(e.body);return Zs(e.workspace,z(t,`path`),B(t,`hidden`))}}],$s=[{method:`GET`,path:`/web/project`,operationId:`getCurrentProject`,run:e=>e.workspace.info()},{method:`POST`,path:`/web/project/open`,operationId:`openProject`,limit:N,run:e=>e.workspace.open(R(L(e.body),`folder`))},{method:`POST`,path:`/web/project/close`,operationId:`closeProject`,run:e=>e.workspace.close()},{method:`GET`,path:`/web/project/recent`,operationId:`listRecentProjects`,run:e=>({projects:e.workspace.recent()})},{method:`POST`,path:`/web/project/recent/forget`,operationId:`forgetRecentProject`,limit:N,run:e=>({projects:e.workspace.forget(R(L(e.body),`folder`))})}];function ec(t){let n=new h(t.home).text(`theme`);return{theme:n===`light`?`LIGHT`:n===`dark`?`DARK`:n===`dracula`?`DRACULA`:`SYSTEM`,locale:p(),engine:null,scriptType:`NONE`,bpmnLint:{configPath:null,clientBundlePath:null},elementTemplates:[],elementTemplatesContent:[],elementTemplatesFolder:``,project:``,bpmnFilePath:``,bpmnXml:``,conventions:null,pluginVersion:e()??null}}const tc=[`JOB_TYPE`,`TOPIC`,`CLASS`,`BEAN`,`MESSAGE`];function nc(e){return tc.includes(e)}function rc(e,t,n){return t===`MESSAGE`?je(e,{kind:t,value:n}):Je(e,{kind:t,value:n})}function ic(e,t,n){let r=/* @__PURE__ */ new Map;for(let i of n)if(nc(i.kind)&&i.value!==``)for(let n of rc(t,i.kind,i.value)){if(n.file!==e)continue;let t=i.elementId??null,a=`${n.line}\u0000${i.kind}\u0000${i.value}\u0000${i.path}\u0000${t}`;if(!r.has(a)&&(r.set(a,{line:n.line,kind:i.kind,value:i.value,diagram:i.path,element:t,name:i.label,elementType:i.elementType??``}),r.size>=500))return ac(r)}return ac(r)}function ac(e){return[...e.values()].sort((e,t)=>e.line-t.line||e.diagram.localeCompare(t.diagram)||e.name.localeCompare(t.name))}function oc(e,t){let n=/* @__PURE__ */ new Map,r=(e,t,r)=>{if(t===``)return;let i=`${e}\u0000${t}`,a=n.get(i);a?a.origin!==r&&(a.origin=`both`):n.set(i,{kind:e,value:t,origin:r})};for(let e of t)nc(e.kind)&&r(e.kind,e.value,`diagram`);for(let t of e.jobTypes.keys())r(`JOB_TYPE`,t,`code`);for(let t of e.topics.keys())r(`TOPIC`,t,`code`);for(let t of e.classes.keys())r(`CLASS`,t,`code`);for(let t of e.beans.keys())r(`BEAN`,t,`code`);for(let t of e.references.keys())t.startsWith(`MESSAGE:`)&&r(`MESSAGE`,t.slice(8),`code`);return[...n.values()].sort((e,t)=>e.kind.localeCompare(t.kind)||e.value.localeCompare(t.value)).slice(0,5e3)}const $=`camunda`,sc=`zeebe`,cc=e=>{let t=e.lastIndexOf(`:`);return t<0?``:e.slice(0,t)},lc=e=>e.slice(e.lastIndexOf(`:`)+1);function uc(e,t){return e===void 0||e===`*`||e===``&&t===``||e===t}function dc(e,t,n){return e.tag!==void 0&&e.tag!==lc(t)?!1:e.attribute===void 0?uc(e.tagPrefix,cc(t)):e.attribute===lc(n)&&uc(e.attributePrefix,cc(n))}const fc=/* @__PURE__ */ new Set([`PROCESS`,`JOB_TYPE`,`TOPIC`,`MESSAGE`,`SIGNAL`,`DECISION`,`FORM`,`CLASS`,`BEAN`,`ERROR`]),pc={PROCESS:[`startProcessInstanceByKey`,`createProcessInstanceByKey`,`startProcessInstanceByKeyAndTenantId`,`processDefinitionKey`,`bpmnProcessId`],JOB_TYPE:[`jobType`],TOPIC:[`topicName`,`subscribe`],MESSAGE:[`correlateMessage`,`createMessageCorrelation`,`messageName`,`correlateMessageAsync`],SIGNAL:[`broadcastSignal`,`throwSignal`,`signalName`],DECISION:[`evaluateDecisionByKey`,`evaluateDecisionTableByKey`,`decisionKey`,`decisionId`,`decisionDefinitionKey`],FORM:[`formId`,`formKey`,`withFormKey`]},mc={JOB_TYPE:[[`JobWorker`,`type`],[`ZeebeWorker`,`type`]],TOPIC:[[`ExternalTaskSubscription`,`topicName`],[`ExternalTaskSubscription`,`value`]]},hc={PROCESS:[`process_definition_key`,`bpmn_process_id`,`start_process_instance_by_key`,`create_process_instance_by_key`,`start_process_instance_by_key_and_tenant_id`],JOB_TYPE:[`job_type`],TOPIC:[`subscribe`,`topic_name`],MESSAGE:[`correlate_message`,`create_message_correlation`,`message_name`],SIGNAL:[`broadcast_signal`,`throw_signal`,`signal_name`],DECISION:[`evaluate_decision_by_key`,`evaluate_decision_table_by_key`,`decision_id`,`decision_key`,`decision_definition_key`],FORM:[`form_id`,`form_key`],ERROR:[`handle_bpmn_error`,`error_code`]},gc=[`BpmnError`,`ZeebeBpmnError`,`CamundaBpmnError`],_c=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);function vc(e){let t=[];return(pc[e]??[]).forEach(e=>t.push({name:e})),(mc[e]??[]).forEach(([e,n])=>t.push({name:n,qualifier:e})),(hc[e]??[]).forEach(e=>t.push({name:e})),e===`ERROR`&&(gc.forEach(e=>t.push({name:e})),t.push({name:`handleBpmnError`,after:`(?:"[^"]*"|'[^']*')\\s*,\\s*`},{name:`errorCode`},{name:`bpmnError`})),t}function yc(e){let t=e.qualifier===void 0?`(?<![\\w$])${_c(e.name)}\\s*(?:\\(\\s*|=\\s*)`:`@${_c(e.qualifier)}\\s*\\(\\s*${_c(e.name)}\\s*=\\s*`;return new RegExp(t+(e.after??``),`g`)}const bc=e=>e.qualifier===void 0?e.name:`@${e.qualifier}(${e.name}`,xc=new Map([...fc].map(e=>[e,vc(e)]));new Map([...xc].map(([e,t])=>[e,new Set(t.map(e=>e.name))]));const Sc={PROCESS:[{tag:`process`,attribute:`id`},{attribute:`calledElement`},{tag:`calledElement`},{tag:`CalledElement`,tagPrefix:sc,attribute:`processId`}],JOB_TYPE:[{attribute:`type`}],TOPIC:[{tag:`topic`,tagPrefix:$,attribute:`topic`},{attribute:`topic`,attributePrefix:$}],MESSAGE:[{tag:`message`,attribute:`name`}],SIGNAL:[{tag:`signal`,attribute:`name`}],DECISION:[{tag:`decision`,attribute:`id`},{tag:`decisionRef`,attribute:`decisionId`},{tag:`decisionId`},{attribute:`decisionRef`},{tag:`CalledDecision`,tagPrefix:sc,attribute:`decisionId`}],FORM:[{attribute:`formKey`,attributePrefix:`*`},{tag:`formKey`,tagPrefix:`*`},{tag:`FormDefinition`,tagPrefix:sc,attribute:`formId`},{tag:`formId`,tagPrefix:sc},{attribute:`formRef`,attributePrefix:$},{tag:`formRef`,tagPrefix:$}],CLASS:[{tag:`class`,tagPrefix:$},{attribute:`class`,attributePrefix:$}],BEAN:[{tag:`delegateExpression`,tagPrefix:$,expression:!0},{tag:`delegateExpression`,tagPrefix:$,attribute:`delegateExpression`,expression:!0},{attribute:`delegateExpression`,attributePrefix:$,expression:!0}],ERROR:[{tag:`error`,attribute:`errorCode`},{attribute:`errorCode`,attributePrefix:`*`}]},Cc=/<([A-Za-z_][\w.:-]*)((?:"[^"]*"|'[^']*'|[^>"'])*)>/g,wc=/([A-Za-z_][\w.:-]*)\s*=\s*("[^"]*"|'[^']*')/g,Tc=/"id"\s*:\s*"([^"]*)"/g,Ec=[`"`,`'`,"`"];function Dc(e,t){if(t<0||e.length===0)return null;let n=Math.min(t,e.length-1),r=e.lastIndexOf(`
16
+ `,Math.max(n-1,0))+1,i=-1;for(let t=n;t>=r;--t)if(Ec.includes(e[t])){i=t;break}if(i<0)return null;let a=e[i];for(let t=i+1;t<e.length;t+=1)if(e[t]===`\\`)t+=1;else if(e[t]===a)return{first:i,last:t};else if(e[t]===`
17
+ `)return null;return null}const Oc=(e,t)=>Ec.includes(e[t])?Dc(e,t):null,kc=(e,t)=>e.slice(t.first+1,Math.max(t.last,t.first+1));function Ac(e,t){let n=[];for(let r=t.indexOf("${");r>=0;r=t.indexOf("${",r+1)){let i=r+2;if(!t.startsWith(e,i)||t[i+e.length]!==`}`)continue;let a=Dc(t,r);a&&kc(t,a).startsWith("${")&&n.push({start:i,end:i+e.length,where:`expression`})}return n}function jc(e,t,n){if(!t)return[];if(e===`BEAN`)return Ac(t,n);let r=/* @__PURE__ */ new Map;for(let i of xc.get(e)??[])for(let e of n.matchAll(yc(i))){let a=Oc(n,e.index+e[0].length);a&&kc(n,a)===t&&(r.has(a.first+1)||r.set(a.first+1,{start:a.first+1,end:a.last,where:bc(i)}))}return[...r.values()].sort((e,t)=>e.start-t.start)}function Mc(e,t,n,r,i){return r.expression?!e.startsWith("${")||!e.includes(`}`)?null:{start:t+2,end:t+e.indexOf(`}`),where:i}:e===n?{start:t,end:t+n.length,where:i}:null}function Nc(e,t,n){if(!t)return[];let r=Sc[e]??[],i=/* @__PURE__ */ new Map,a=e=>{e&&!i.has(e.start)&&i.set(e.start,e)};for(let e of n.matchAll(Cc)){let i=e[1],o=e[2],s=e.index,c=s+1+i.length;for(let o of r.filter(e=>e.attribute===void 0&&dc(e,i,``))){let r=s+e[0].length,c=n.indexOf(`<`,r);c>=0&&a(Mc(n.slice(r,c),r,t,o,i))}for(let e of o.matchAll(wc)){let n=e[1],o=e[2],s=o.slice(1,-1),l=c+e.index+e[0].length-o.length+1;for(let e of r.filter(e=>e.attribute!==void 0&&dc(e,i,n)))a(Mc(s,l,t,e,`${i}@${n}`))}}return[...i.values()]}function Pc(e,t,n){return e!==`FORM`||!t?[]:[...n.matchAll(Tc)].filter(e=>e[1]===t).map(e=>{let n=e.index+e[0].length-1;return{start:n-t.length,end:n,where:`id`}})}function Fc(e){return e.trim()!==``&&![...e].some(e=>/[\u0000-\u001f\u007f-\u009f]/.test(e)||`"'<>&\\\``.includes(e))}const Ic=e=>fc.has(e),Lc=Fc,Rc=e=>/\.form$/i.test(e)?`form`:/\.(bpmn|bpmn\.xml|bpmn20\.xml|dmn)$/i.test(e)?`diagram`:`code`;function zc(e,t,n,r){let i=[];for(let a of e){if(a.path===r)continue;let e=Rc(a.path);(e===`form`?Pc(t,n,a.text):e===`diagram`?Nc(t,n,a.text):jc(t,n,a.text)).forEach(t=>i.push({file:a.path,start:t.start,end:t.end,where:e,label:t.where}))}return i}function Bc(e){let t=new Set(e.map(e=>e.file)).size,n=e.filter(e=>e.where!==`code`).length;return f(`app.vscode.rename.summary`,{files:f(`app.vscode.rename.files`,{count:t}),diagrams:n,code:e.length-n})}const Vc=mn(Bt),Hc=4e3,Uc={JAVA_CLASS:[`CLASS`],BEAN:[`BEAN`],JOB_TYPE:[`JOB_TYPE`,`TOPIC`]},Wc=/* @__PURE__ */ new Set([`PROCESS`,`JOB_TYPE`,`TOPIC`,`MESSAGE`,`SIGNAL`,`DECISION`,`FORM`,`CLASS`,`BEAN`,`ERROR`]);function Gc(e){return Ht(`sha256`).update(e).digest(`hex`)}async function Kc(e,t){let n=L(e.body),r=R(n,`kind`),i=R(n,`value`),a=Uc[r];if(!a)throw I(400,`app.cli.web.reason.wrongField`,{field:`kind`});if(i.length===0||i.length>500)throw I(400,`app.cli.web.reason.wrongField`,{field:`value`});let{index:o}=await t.code.state(()=>t.project.listing()),s=/* @__PURE__ */ new Set;return{places:a.flatMap(e=>Je(o,{kind:e,value:i})).filter(e=>{let t=`${e.file}#${e.line}`;return!s.has(t)&&(s.add(t),!0)}).map(e=>({path:e.file,line:e.line,label:`${v.basename(e.file)}:${e.line}`}))}}async function qc(e,t){let n=t.confine.resolve(R(L(e.body),`path`)),{index:r,targets:i}=await t.code.state(()=>t.project.listing());return{uses:ic(n,r,i)}}async function Jc(e,t){let{index:n,targets:r}=await t.code.state(()=>t.project.listing());return{names:oc(n,r)}}async function Yc(e,t){try{return{ok:!0,out:(await Vc(`git`,t,{cwd:e,encoding:`utf8`,timeout:1e4,maxBuffer:67108864,env:{...process.env,GIT_TERMINAL_PROMPT:`0`,GIT_OPTIONAL_LOCKS:`0`}})).stdout}}catch{return{ok:!1,out:``}}}async function Xc(e,t){let n=t.confine.resolve(R(L(e.body),`path`)),r=v.dirname(n),i=await Yc(r,[`rev-parse`,`--is-inside-work-tree`]);if(!i.ok||i.out.trim()!==`true`)return{tracked:!1,before:null};let a=await Yc(r,[`show`,`HEAD:./${v.basename(n)}`]);return{tracked:!0,before:a.ok?a.out:null}}async function Zc(e){try{let t=await k(e);return!t.isFile()||t.size>33554432?null:await Xt(e,`utf8`)}catch{return null}}function Qc(e,t,n){if(e.confine.writeKind(t))return;let r=e.confine.segments(t),i=r.slice(0,-1).some(e=>e.startsWith(`.`));if(!Ie.test(r[r.length-1]??``)||i)throw I(403,`app.cli.web.reason.notEditable`,{path:n.slice(0,200)})}async function $c(e,t){let n=await e.project.listing(),{sources:r}=await e.code.state(()=>e.project.listing()),i=/* @__PURE__ */ new Set([...n.files.map(e=>e.path),...r.map(e=>e.path)]);if(i.delete(t),i.size>Hc)throw I(400,`app.cli.web.reason.tooMany`);let a=[];for(let e of i){let t=await Zc(e);t!==null&&a.push({path:e,text:t})}return a}function el(e){let t=L(e.body),n=R(t,`kind`);if(!Wc.has(n))throw I(400,`app.cli.web.reason.wrongField`,{field:`kind`});return{kind:n,from:R(t,`from`),to:R(t,`to`),path:R(t,`path`)}}function tl(e,t){let n=1;for(let r=0;r<t&&r<e.length;r+=1)e.charCodeAt(r)===10&&(n+=1);return n}async function nl(e,t){let n=el(e),r=t.confine.resolve(n.path),i={offered:!1,sites:[],files:[]};if(!Ic(n.kind)||!n.from.trim()||!Lc(n.to))return{...i,detail:f(`app.vscode.rename.notRenamable`)};if(!await K(t))return i;let a=await $c(t,r),o=zc(a,n.kind,n.from,r);if(o.length===0)return{...i,detail:f(`app.vscode.rename.nothingElse`,{name:n.from})};let s=new Map(a.map(e=>[e.path,e.text])),c=[...new Set(o.map(e=>e.file))];return{offered:!0,summary:Bc(o),sites:o.map(e=>({path:e.file,where:e.where,label:e.label,line:tl(s.get(e.file)??``,e.start)})),files:c.map(e=>({path:e,version:Gc(s.get(e)??``)}))}}function rl(e,t,n){let r=e;for(let e of[...t].sort((e,t)=>t.start-e.start))r=`${r.slice(0,e.start)}${n}${r.slice(e.end)}`;return r}async function il(e,t){let n=v.join(v.dirname(e),`.${v.basename(e)}.${process.pid}.${Ut(4).toString(`hex`)}.tmp`),r=await k(e).catch(()=>null);return await $t(n,t,{mode:r?r.mode&511:420}),n}async function al(e,t){let n=el(e),r=L(e.body);if(!Ic(n.kind)||!n.from.trim()||!Lc(n.to))throw I(400,`app.cli.web.reason.wrongField`,{field:`to`});if(!await K(t))throw I(403,`app.cli.webHost.reason.notLicensed`);let i=t.confine.resolve(n.path),a=V(r,`files`).map(e=>{let t=L(e);return{path:R(t,`path`),version:R(t,`version`)}});if(a.length===0||a.length>Hc)throw I(400,`app.cli.web.reason.badFileList`);let o=[];for(let e of a){let n=t.confine.resolve(e.path);if(Qc(t,n,e.path),n===i)throw I(400,`app.cli.web.reason.wrongField`,{field:`files`});let r=await Zc(n);if(r===null||Gc(r)!==e.version)throw I(409,`app.cli.webHost.reason.changedSince`,{file:t.confine.relative(n).slice(0,200)});o.push({path:n,text:r})}let s=zc(o,n.kind,n.from,i),c=[];try{for(let e of o){let t=s.filter(t=>t.file===e.path);t.length!==0&&c.push({target:e.path,temporary:await il(e.path,rl(e.text,t,n.to)),before:e.text})}for(let e of c){let n=await Zc(e.target);if(n===null||n!==e.before)throw I(409,`app.cli.webHost.reason.changedSince`,{file:t.confine.relative(e.target).slice(0,200)})}let e=[];try{for(let t of c)await D(t.temporary,t.target),e.push(t)}catch(t){for(let t of e.reverse()){let e=await il(t.target,t.before);await D(e,t.target).catch(()=>O(e,{force:!0}))}throw t}}finally{await Promise.all(c.map(e=>O(e.temporary,{force:!0}).catch(()=>void 0)))}return{places:s.length,files:c.length}}function ol(e){throw e instanceof l?I(400,`app.cli.webHost.reason.licence`,{detail:e.message}):I(502,`app.cli.webHost.reason.licenceService`,{detail:e instanceof Error?e.message:String(e)})}async function sl(e,t){let n=R(L(e.body),`key`).trim();if(n.length<8||n.length>200)throw I(400,`app.cli.webHost.reason.keyShape`);try{await i(n,{env:t.env})}catch(e){ol(e)}return pa(t),ha(t)}async function cl(e,t){try{if(await o({env:t.env})===`none`)throw I(409,`app.cli.webHost.reason.nothingToRelease`)}catch(e){if(e instanceof Error&&e.name===`WebFailure`)throw e;ol(e)}return pa(t),ha(t)}async function ll(e,t){let n=L(e.body),r=R(n,`tier`);if(r!==`PRO`&&r!==`TEAM`)throw I(400,`app.cli.web.reason.wrongField`,{field:`tier`});let i=typeof n.email==`string`&&n.email.trim()?n.email.trim().slice(0,200):void 0;try{return{url:(await a(r===`PRO`?`pro`:`team`,i,{env:t.env})).url}}catch(e){throw I(502,`app.cli.webHost.reason.licenceService`,{detail:e instanceof Error?e.message:String(e)})}}const ul=[{method:`POST`,path:`/web/code/locate`,operationId:`locateCode`,limit:N,run:Kc},{method:`POST`,path:`/web/code/uses`,operationId:`findCodeUses`,limit:N,run:qc},{method:`GET`,path:`/web/code/names`,operationId:`listProjectNames`,run:Jc},{method:`POST`,path:`/web/compare`,operationId:`compareWithHead`,limit:N,run:Xc},{method:`POST`,path:`/web/linked-rename/plan`,operationId:`planLinkedRename`,limit:N,run:nl},{method:`POST`,path:`/web/linked-rename/apply`,operationId:`applyLinkedRename`,limit:N,run:al},{method:`POST`,path:`/web/licence/activate`,operationId:`activateLicence`,limit:N,run:sl},{method:`POST`,path:`/web/licence/checkout`,operationId:`startLicenceCheckout`,limit:N,run:ll},{method:`POST`,path:`/web/licence/deactivate`,operationId:`deactivateLicence`,limit:N,run:cl}],dl=[{method:`GET`,path:`/web/lsp/servers`,operationId:`listLanguageServers`,run:(e,t)=>({servers:us(t.home,t.env).map(e=>({id:e.id,label:e.command,languages:e.languages,available:e.found!==null,configured:e.configured}))})},{method:`GET`,path:`/web/lsp/messages`,operationId:`nextLspMessages`,held:!0,run:async(e,t)=>({messages:await t.events.nextMessages(e.client,e.signal)})},{method:`POST`,path:`/web/lsp/{serverName}/message`,operationId:`sendLspMessage`,limit:P,run:(e,t)=>{t.servers.send(e.client,e.params.serverName,e.body)}}],fl=/* @__PURE__ */ new Set([`JOB_TYPE`,`TOPIC`,`CLASS`,`BEAN`,`MESSAGE`,`PROCESS`,`DECISION`]),pl=/* @__PURE__ */ new Set([`execution`,`task`]);function ml(e,t){if(e.length>500)throw I(400,`app.cli.web.reason.wrongField`,{field:t});return e}function hl(e){let t=L(e),n=R(t,`kind`);if(!fl.has(n))throw I(400,`app.cli.web.reason.wrongField`,{field:`kind`});let r=t.listener;if(r!==void 0&&(typeof r!=`string`||!pl.has(r)))throw I(400,`app.cli.web.reason.wrongField`,{field:`listener`});return{kind:n,value:ml(R(t,`value`),`value`),...r?{listener:r}:{}}}function gl(e){let t=L(e),n=V(t,`elements`);if(n.length>2e4)throw I(400,`app.cli.web.reason.tooMany`);return{diagram:ml(R(t,`diagram`),`diagram`),elements:n.map(e=>{let t=L(e),n=V(t,`bindings`);if(n.length>40)throw I(400,`app.cli.web.reason.tooMany`);return{elementId:ml(R(t,`elementId`),`elementId`),elementType:ml(R(t,`elementType`),`elementType`),label:ml(R(t,`label`),`label`),bindings:n.map(hl)}})}}function _l(e,t){let n=/* @__PURE__ */ new Map;for(let r of e)r.kind===t&&!n.has(r.value)&&n.set(r.value,r.path);return n}function vl(e,t,n){return{licensed:!0,statuses:Pe({diagram:n.diagram,index:e,processes:_l(t,`PROCESS`),decisions:_l(t,`DECISION`)},n.elements).map(({reached:e,paused:t,...n})=>n)}}function yl(e,t,n){let r=e.split(/\r\n|\n|\r/);return r[r.length-1]===``&&r.pop(),r.slice(Math.max(0,t-1),Math.max(0,t-1)+n).map(e=>e.replace(/\s+$/,``).slice(0,240))}async function bl(e){let t;try{let n=await k(e);return!n.isFile()||n.size>1048576?null:(t=await Jt(e,`r`),await t.readFile(`utf8`))}catch{return null}finally{await t?.close().catch(()=>void 0)}}const xl=[{method:`POST`,path:`/web/code/status`,operationId:`findCodeStatus`,limit:P,run:async(e,t)=>{let n=gl(e.body);if(!await K(t))return{licensed:!1,statuses:[]};let{index:r,targets:i}=await t.code.state(()=>t.project.listing());return vl(r,i,n)}},{method:`POST`,path:`/web/code/snippet`,operationId:`readCodeSnippet`,limit:N,run:async(e,t)=>{let n=L(e.body),r=R(n,`path`),i=n.line;if(typeof i!=`number`||!Number.isInteger(i)||i<1||i>1e7)throw I(400,`app.cli.web.reason.wrongField`,{field:`line`});let a=n.count;if(a!==void 0&&(typeof a!=`number`||!Number.isInteger(a)||a<1))throw I(400,`app.cli.web.reason.wrongField`,{field:`count`});let o=t.confine.resolve(r);if(!Ie.test(o))throw I(400,`app.cli.web.reason.wrongField`,{field:`path`});let s=await bl(o);return{path:r,line:i,lines:s===null?[]:yl(s,i,Math.min(a??12,12))}}}],Sl={workers:[],classes:[],camunda7Imports:[]};var Cl=class{signature=``;analysis={migration:null,facts:Sl};async analysisOf(e,t){let n=Ht(`sha1`);e.forEach(e=>n.update(`${e.path}\n${e.text}\n`)),t.forEach(e=>n.update(`${e.file}\n${e.text}\n`));let r=n.digest(`hex`);if(r!==this.signature){let{index:n,facts:i}=await St(e,t.map(e=>({path:e.file,text:e.text}))),a=await Ne({files:e,classes:i.classes,camunda7Imports:i.camunda7Imports,index:n}).catch(()=>null);this.analysis={migration:a,facts:i},this.signature=r}return this.analysis}};function wl(e){return e.slice(0,Math.max(e.lastIndexOf(`/`),e.lastIndexOf(`\\`),0))}async function Tl(e,t){let n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map;for(let i of e){let e=wl(i);if(!n.has(e)){let r=await t.deployTargets(i).catch(()=>null),a=r?.targets.find(e=>(e.profile??null)===(r.active??null));n.set(e,a?{profile:a.profile??null,engine:a.engine??null,url:a.url??null,ready:a.ready}:null)}let a=n.get(e);a&&r.set(i,a)}return r}async function El(e,t,n){let r=await t.reports().catch(()=>[]),i=await t.deployTargets().catch(()=>null),a=t.templates(),o=await n.analysisOf(e.diagrams,e.sources),[s,c]=await Promise.all([Te(a),Ae(a,o.facts.workers)]),l=new Map(c.map(e=>[e.id,e.drift]));return Ee({root:e.root,files:e.files,targets:e.targets,code:e.code,coverage:Le(e.root,r).reach,deploy:i&&{active:i.active,targets:i.targets},debug:[],preferences:{tree:e.preferences?.toolWindowTree!==!1,groupByFiles:e.preferences?.toolWindowGroupByFiles===!0},workersOnEngine:e.workersOnEngine,fileTargets:await Tl(e.files.map(e=>e.path),t),codeLinks:e.licensed?`open`:`locked`,migration:o.migration,templates:[...s.values()].map(({path:e,template:t})=>({path:e,template:t,drift:l.get(t.id)??null})),contracts:o.facts.workers.map(e=>({value:e.value,file:e.file,line:e.line,handler:e.handler??null}))})}function Dl(e,t){return e.elementId===t.elementId&&e.owner===t.owner&&e.index===t.index}async function Ol(e){let t=await Ze(e.text),n=Ge(t).find(t=>Dl(t.slot,e.slot));if(!n)return null;let r=yn({definitions:t,workers:e.workers,diagramPath:e.path},n.slot.elementId,n.value);return{path:e.path,slot:n.slot,language:n.language,value:n.value,title:Oe(n),variables:r}}const kl=2e4;function Al(e,t){let n=/* @__PURE__ */ new Set,r=[];for(let{handle:i,label:a}of e){if(r.length>=500)break;let e;try{e=t(Ct(i))}catch{e=null}if(!e)continue;let o=xt(i)??1,s=`${e}#${o}`;n.has(s)||(n.add(s),r.push({path:e,line:o,label:a??`${v.basename(e)}:${o}`}))}return r}function jl(e){return{kind:`unsupported`,reason:e}}function Ml(e){return e.checks.flatMap(e=>e.check.problem?[`${e.where}: ${e.check.problem}`]:[])}async function Nl(e,t){switch(e.type){case`reveal`:{let n=t.inside(e.path);return n?{kind:`reveal`,path:n,...e.elementId?{elementId:e.elementId}:{}}:jl(f(`app.cli.web.toolWindow.unsupported.outside`))}case`openCode`:return{kind:`openCode`,title:e.title,places:Al(e.handles.map(e=>({handle:e})),e=>t.inside(e))};case`findUsages`:return await t.paid()?{kind:`findUsages`,title:e.title,places:Al(await t.usages(e.subjects),e=>t.inside(e))}:{kind:`unlockCode`};case`copy`:return{kind:`copy`,text:e.text.slice(0,kl)};case`preference`:return t.savePreference(e.key,e.value),{kind:`preference`,key:e.key,value:e.value};case`deploy`:{let n=e.paths.slice(0,1e3).map(e=>t.inside(e)).filter(e=>e!==null);return n.length===0?jl(f(`app.cli.web.toolWindow.unsupported.outside`)):{kind:`deploy`,paths:n,...e.profile?{profile:e.profile}:{},...e.confirm?{confirm:!0}:{}}}case`createExample`:return{kind:`createExample`,example:e.example};case`unlockCode`:return{kind:`unlockCode`};case`checkWorkers`:{if(!await t.paid())return{kind:`unlockCode`};let n=await t.checkWorkers(e.groups);t.workersChecked(n);let r=Ml(n);return r.length>0?{kind:`notify`,text:r.join(`
18
+ `).slice(0,kl),error:!0}:{kind:`refresh`}}case`runTests`:return jl(f(`app.cli.web.toolWindow.unsupported.tests`));case`script`:{let n=await t.script(e.path,e.slot);return n?{kind:`openScript`,path:n.path,slot:n.slot,language:n.language,script:n.value,title:n.title,variables:n.variables}:{kind:`notify`,text:f(`app.cli.web.toolWindow.script.missing`)}}case`migrationConvert`:case`migrationApply`:case`migrationReport`:case`migrationWorker`:return jl(f(`app.cli.web.toolWindow.unsupported.migration`));case`workerTemplate`:case`workerTemplateAt`:case`templateWorker`:return jl(f(`app.cli.web.toolWindow.unsupported.templates`))}}const Pl=/^[\w .-]{1,80}$/;function Fl(e,t){let n=t,r=!1,i=e=>{let t=[];for(let a of e){if(n<=0){r=!0;break}--n,t.push(a.children&&a.children.length>0?{...a,children:i(a.children)}:a)}return t};return{roots:i(e),truncated:r}}async function Il(e,t){let n;try{let r=await k(e);return!r.isFile()||r.size>t?null:(n=await Jt(e,`r`),await n.readFile(`utf8`))}catch{return null}finally{await n?.close().catch(()=>void 0)}}function Ll(e,t){let n=e.folder;return{root:async()=>n,list:async()=>t.templates.map(e=>v.relative(n,e.path).split(v.sep).join(`/`)),read:async t=>Il(e.confine.resolve(v.join(n,t)),2097152),write:async(t,r)=>{let i=e.confine.resolve(v.join(n,t));e.confine.writable(i,t),await T(v.dirname(i),{recursive:!0}),await $t(i,r)}}}async function Rl(e){return(await Promise.all(e.reports.map(async e=>{let t=await Il(e.path,16777216);return t===null?null:{path:e.path,stamp:e.stamp,text:t}}))).filter(e=>e!==null)}function zl(e,t,n){let r=new Map(n.diagrams.map(e=>[e.path,e.text]));return{reports:()=>Rl(t),deployTargets:async t=>Li(Ea(e,t??null,t&&r.get(t)||``)),templates:()=>Ll(e,t)}}function Bl(e,t){let n=/* @__PURE__ */ new Map;if(t)for(let t of Fe(e.models,e.targets)){let r=bt(e.index,t,e=>yt(e.file,e.line));r.length>0&&n.set(Ke(t),r)}return{precise:t,links:n}}var Vl=class{current=null;building=null;memo=new Cl;workers=null;serial=0;keyOf(e,t,n){return[e.id,e.project.scans,e.code.builds,e.configs.generation,t?`paid`:`free`,n.toolWindowTree===!1?`flat`:`tree`,n.toolWindowGroupByFiles===!0?`files`:`kinds`,this.serial].join(`.`)}async snapshot(e){let t=await e.project.listing(),n=await e.code.state(()=>e.project.listing()),r=await K(e),i=new h(e.home).read(),a=this.keyOf(e,r,i);if(this.current?.key===a)return this.current.built;if(this.building?.key===a)return this.building.promise;let o=this.build(e,t,n,r,i,a),s={key:a,promise:o};this.building=s;try{return await o}finally{this.building===s&&(this.building=null)}}async build(e,t,n,r,i,a){let o=await El({root:e.folder,files:n.models,targets:n.targets,code:Bl(n,r),licensed:r,diagrams:n.diagrams,sources:n.sources.map(e=>({file:e.path,text:e.text})),preferences:i,workersOnEngine:this.workers},zl(e,t,n),this.memo),{roots:s,truncated:c}=Fl(o.roots,5e4),l={revision:a,roots:s,toolbar:o.toolbar,codeLinks:r?`open`:`locked`,truncated:c,actions:o.actions};return this.current={key:a,built:l},l}async perform(e,t){let n=this.current?.built.actions.get(t);if(!n)throw I(400,`app.cli.web.reason.noSuchAction`);return Nl(n,this.hostFor(e))}revision(){return this.current?.built.revision??null}knows(e){return this.current?.built.actions.has(e)??!1}hostFor(e){return{inside:t=>{try{return e.confine.resolve(t)}catch{return null}},usages:async t=>{let{index:n}=await e.code.state(()=>e.project.listing());return t.flatMap(e=>bt(n,e,e=>yt(e.file,e.line)).map(e=>({handle:e.handle,label:e.label})))},script:async(t,n)=>{let{diagrams:r,workers:i}=await e.code.state(()=>e.project.listing()),a=r.find(e=>e.path===t);return a?Ol({path:t,text:a.text,slot:n,workers:i}):null},paid:()=>K(e),savePreference:(t,n)=>{let r=new h(e.home);r.write({...r.read(),[t]:n})},checkWorkers:t=>this.checkWorkers(e,t),workersChecked:e=>{this.workers=e,this.serial+=1}}}async checkWorkers(e,t){let n=await Promise.all(t.slice(0,50).map(async t=>{let n=t.jobTypes.slice(0,2e3);try{if(t.profile!==null&&!Pl.test(t.profile))throw new F(400,`profile`);let r=e.confine.resolve(t.resource),i=await Promise.all(Be(t.engine,n,/* @__PURE__ */ new Date).map(n=>Oa(e,{method:n.method,path:n.path,body:n.body,parts:n.parts},t.profile,r)));return{where:t.where,engine:t.engine,check:We(t.engine,n,i)}}catch(e){return{where:t.where,engine:t.engine,check:{statuses:/* @__PURE__ */ new Map,problem:e instanceof Error?e.message:String(e)}}}}));return{at:(/* @__PURE__ */ new Date()).toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`,hourCycle:`h23`}),checks:n}}};const Hl=/* @__PURE__ */ new WeakMap;function Ul(e){let t=Hl.get(e);return t||(t=new Vl,Hl.set(e,t)),t}const Wl=[{method:`GET`,path:`/web/tool-window`,operationId:`getToolWindow`,run:async(e,t)=>{let n=e.query.get(`revision`);if(n!==null&&n.length>200)throw I(400,`app.cli.web.reason.wrongField`,{field:`revision`});let{actions:r,...i}=await Ul(t).snapshot(t);return n===i.revision?{revision:i.revision,unchanged:!0}:i}},{method:`POST`,path:`/web/tool-window/perform`,operationId:`performToolWindowAction`,limit:N,run:async(e,t)=>{let n=L(e.body),r=R(n,`id`),i=R(n,`revision`);if(r.length>64||i.length>200)throw I(400,`app.cli.web.reason.wrongField`,{field:`id`});let a=Ul(t),o=a.revision();if(o===null||o!==i)throw I(409,`app.cli.web.reason.staleToolWindow`);if(!a.knows(r))throw I(400,`app.cli.web.reason.noSuchAction`);return a.perform(t,r)}}],Gl=Va.map(e=>e.operationId===`getConfig`?{...e,run:(t,n)=>n.open?e.run(t,n):ec(n)}:e),Kl=[...va,...to,...co,...Gl,...io,...Gr,...$s,...Qs,...Jo,...Eo,...ul,...xr,...xl,...Wl,...lo,...dl],ql=/* @__PURE__ */ new Set([`getLicense`,`requestFeature`,`showLicenceOffer`,`getTheme`,`getPreferences`,`savePreferences`,`getDialogButtonOrder`,`notifyUser`,`openExternalLink`,`nextHostEvent`,`fetchConnectorUrl`,`connectorFile`,`getCurrentProject`,`openProject`,`closeProject`,`listRecentProjects`,`forgetRecentProject`,`listFolders`]),Jl=new Set(lo.map(e=>e.operationId));function Yl(e){return e.operationId===`getConfig`?`checked`:ql.has(e.operationId)||yr.has(e.operationId)||Jl.has(e.operationId)?`none`:`required`}function Xl(e){let t=e.map(e=>({route:e,parts:e.path.split(`/`)}));return(e,n)=>{let r=n.split(`/`),i=[];for(let{route:n,parts:a}of t){if(a.length!==r.length)continue;let t={},o=!0;for(let e=0;e<a.length&&o;e+=1){let n=a[e];if(n.startsWith(`{`)&&n.endsWith(`}`)){if(r[e]===``){o=!1;break}try{t[n.slice(1,-1)]=decodeURIComponent(r[e])}catch{o=!1}}else n!==r[e]&&(o=!1)}if(o){if(n.method===e)return{kind:`found`,route:n,params:t};i.push(n.method)}}return i.length>0?{kind:`method`,allowed:i}:{kind:`none`}}}const Zl=Xl(Kl),Ql=/* @__PURE__ */ new Set([`0.0.0.0`,`::`]),$l=[`127.0.0.1`,`localhost`,`[::1]`];function eu(){return Ut(32).toString(`base64url`)}function tu(e,t){return typeof e!=`string`||e.length===0||e.length>512?!1:Gt(Ht(`sha256`).update(e).digest(),Ht(`sha256`).update(t).digest())}function nu(e){let t=[],n=e[`x-penstock-token`];typeof n==`string`&&t.push(n);let r=e.cookie;if(typeof r==`string`&&r.length<=8192)for(let e of r.split(`;`)){let n=e.indexOf(`=`);n>0&&e.slice(0,n).trim()===`penstock_web`&&t.push(e.slice(n+1).trim())}return t}function ru(e,t){return nu(e).some(e=>tu(e,t))}function iu(e){let t=e[`x-penstock-resource`];if(typeof t!=`string`||t.length===0)return null;try{return decodeURIComponent(t)}catch{return t}}function au(e){return`penstock_web=${e}; Path=/; HttpOnly; SameSite=Strict`}function ou(e){return e===`::1`||e===`localhost`||e.startsWith(`127.`)}function su(e){return e.includes(`:`)&&!e.startsWith(`[`)?`[${e}]`:e}function cu(e){let t=/^(\[[0-9a-f:.]+\]):(\d{1,5})$/.exec(e);if(t)return{name:t[1],port:t[2]};let n=/^([a-z0-9.-]+):(\d{1,5})$/.exec(e);return n?{name:n[1],port:n[2]}:null}function lu(e,t){let n=Ql.has(e),r=new Set($l.map(e=>`${e}:${t}`));return!n&&!ou(e)&&r.add(`${su(e).toLowerCase()}:${t}`),{allowsHost:e=>{if(typeof e!=`string`||e.length===0||e.length>300)return!1;let i=e.toLowerCase();if(r.has(i))return!0;if(!n)return!1;let a=cu(i);return a!==null&&Number(a.port)===t&&hn(a.name.replace(/^\[|\]$/g,``))!==0},allowsOrigin(e,t){return e===void 0||e.toLowerCase()===`http://${t.toLowerCase()}`}}}function uu(e){let t=e[`sec-fetch-site`];return t===void 0||t===`same-origin`||t===`none`}export{Dn as A,er as C,Yn as D,N as E,wn as F,Cn as I,En as M,Tn as N,M as O,Nn as P,F as S,Xn as T,wr as _,lu as a,cr as b,iu as c,Xl as d,Yl as f,Tr as g,Dr as h,ru as i,Mn as j,Bn as k,tu as l,Or as m,au as n,ou as o,Hs as p,uu as r,eu as s,su as t,Zl as u,Cr as v,I as w,or as x,vr as y};