@tom2012/cc-web 2026.5.24-c → 2026.5.24-e

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 (22) hide show
  1. package/README.md +1 -1
  2. package/backend/dist/__tests__/browser-chrome-e2e.test.js +36 -0
  3. package/backend/dist/__tests__/browser-chrome-e2e.test.js.map +1 -1
  4. package/frontend/dist/assets/{ChatOverlay-DWnJouqf.js → ChatOverlay-V7DBSoaF.js} +1 -1
  5. package/frontend/dist/assets/{GraphPreview-BhYiu0BC.js → GraphPreview-BxBsGYE9.js} +1 -1
  6. package/frontend/dist/assets/{MobilePage-CpwaYT93.js → MobilePage-BwIfpmZA.js} +3 -3
  7. package/frontend/dist/assets/{OfficePreview-AIsCrFJN.js → OfficePreview-CWiJpp9Z.js} +2 -2
  8. package/frontend/dist/assets/{PdfPreview-BOf3iH2G.js → PdfPreview-2DcKEMbR.js} +1 -1
  9. package/frontend/dist/assets/{ProjectPage-BLDngPUN.js → ProjectPage-CKm1NIEx.js} +5 -5
  10. package/frontend/dist/assets/{SettingsPage-898duvMO.js → SettingsPage-CRPl_mVj.js} +1 -1
  11. package/frontend/dist/assets/{SkillHubPage-Cf3oFMk3.js → SkillHubPage-DsF2j49l.js} +1 -1
  12. package/frontend/dist/assets/{chevron-down-CWdHpHQs.js → chevron-down-DSuYI8m-.js} +1 -1
  13. package/frontend/dist/assets/{index-DoKF15jh.js → index-CPROAFio.js} +1 -1
  14. package/frontend/dist/assets/index-DB7vdaUN.css +1 -0
  15. package/frontend/dist/assets/{index-DzV3STk-.js → index-DLIf9Yfa.js} +1 -1
  16. package/frontend/dist/assets/{index-DtlKk29C.js → index-YwIvszwO.js} +2 -2
  17. package/frontend/dist/assets/{jszip.min-BiyTb6vp.js → jszip.min-C_jYnhtJ.js} +1 -1
  18. package/frontend/dist/assets/{search-DAr7qjB5.js → search-CaBUM8S-.js} +1 -1
  19. package/frontend/dist/assets/{select-IaWIRuom.js → select-BUvVYFSc.js} +1 -1
  20. package/frontend/dist/index.html +2 -2
  21. package/package.json +1 -1
  22. package/frontend/dist/assets/index-B55CtERr.css +0 -1
@@ -1,17 +1,17 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/GraphPreview-BhYiu0BC.js","assets/index-DtlKk29C.js","assets/index-B55CtERr.css","assets/purify.es-CgRAQgUo.js","assets/ChatOverlay-DWnJouqf.js","assets/chevron-down-CWdHpHQs.js","assets/index-DzV3STk-.js","assets/ChatOverlay-wklAmtGL.css","assets/select-IaWIRuom.js","assets/search-DAr7qjB5.js","assets/OfficePreview-AIsCrFJN.js","assets/PdfPreview-BOf3iH2G.js","assets/PdfPreview-Bu5q60D-.css"])))=>i.map(i=>d[i]);
2
- var e,t,i,s,r,n,o=Object.defineProperty,a=(e,t,i)=>((e,t,i)=>t in e?o(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);import{c as l,u as c,r as h,a as d,g as u,b as f,w as p,t as m,j as _,d as g,E as v,P as y,M as x,e as b,f as w,X as S,h as C,i as k,S as E,R as N,_ as M,s as j,k as D,l as R,D as P,T as L,m as I,F as T,n as B,o as O,C as A,p as z,A as $,q as H,v as W,x as F,B as K,y as U,z as V,I as q,G as Y,H as X,J as G,K as Z,L as J,N as Q,O as ee,Q as te,U as ie,V as se,W as re,Y as ne,Z as oe,$ as ae,a0 as le,a1 as ce,a2 as he,a3 as de,a4 as ue,a5 as fe,a6 as pe,a7 as me,a8 as _e,a9 as ge,aa as ve,ab as ye,ac as xe,ad as be,ae as we,af as Se,ag as Ce,ah as ke,ai as Ee,aj as Ne,ak as Me,al as je,am as De,an as Re,ao as Pe,ap as Le,aq as Ie,ar as Te,as as Be,at as Oe,au as Ae,av as ze,aw as $e,ax as He,ay as We,az as Fe,aA as Ke,aB as Ue,aC as Ve,aD as qe,aE as Ye,aF as Xe,aG as Ge,aH as Ze,aI as Je,aJ as Qe,aK as et,aL as tt,aM as it,aN as st,aO as rt,aP as nt,aQ as ot,aR as at,aS as lt,aT as ct,aU as ht,aV as dt,aW as ut,aX as ft,aY as pt,aZ as mt,a_ as _t,a$ as gt,b0 as vt,b1 as yt,b2 as xt}from"./index-DtlKk29C.js";import{p as bt}from"./purify.es-CgRAQgUo.js";import{F as wt,M as St,r as Ct,a as kt,b as Et,c as Nt,h as Mt,o as jt,d as Dt,e as Rt,I as Pt,C as Lt,G as It,f as Tt}from"./ChatOverlay-DWnJouqf.js";import{S as Bt,U as Ot,T as At,a as zt,b as $t,c as Ht,R as Wt,A as Ft,d as Kt,e as Ut,f as Vt,I as qt,g as Yt,C as Xt,h as Gt,i as Zt,j as Jt,k as Qt,l as ei,m as ti}from"./select-IaWIRuom.js";import{C as ii}from"./chevron-down-CWdHpHQs.js";import{u as si,C as ri,a as ni}from"./index-DzV3STk-.js";import{S as oi}from"./search-DAr7qjB5.js";
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/GraphPreview-BxBsGYE9.js","assets/index-YwIvszwO.js","assets/index-DB7vdaUN.css","assets/purify.es-CgRAQgUo.js","assets/ChatOverlay-V7DBSoaF.js","assets/chevron-down-DSuYI8m-.js","assets/index-DLIf9Yfa.js","assets/ChatOverlay-wklAmtGL.css","assets/select-BUvVYFSc.js","assets/search-CaBUM8S-.js","assets/OfficePreview-CWiJpp9Z.js","assets/PdfPreview-2DcKEMbR.js","assets/PdfPreview-Bu5q60D-.css"])))=>i.map(i=>d[i]);
2
+ var e,t,i,s,r,n,o=Object.defineProperty,a=(e,t,i)=>((e,t,i)=>t in e?o(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);import{c as l,u as c,r as h,a as d,g as u,b as f,w as p,t as m,j as _,d as g,E as v,P as y,M as x,e as b,f as w,X as S,h as C,i as k,S as E,R as N,_ as M,s as j,k as D,l as R,D as P,T as L,m as T,F as I,n as B,o as O,C as A,p as z,A as $,q as H,v as W,x as F,B as K,y as U,z as V,I as q,G as Y,H as X,J as G,K as Z,L as J,N as Q,O as ee,Q as te,U as ie,V as se,W as re,Y as ne,Z as oe,$ as ae,a0 as le,a1 as ce,a2 as he,a3 as de,a4 as ue,a5 as fe,a6 as pe,a7 as me,a8 as _e,a9 as ge,aa as ve,ab as ye,ac as xe,ad as be,ae as we,af as Se,ag as Ce,ah as ke,ai as Ee,aj as Ne,ak as Me,al as je,am as De,an as Re,ao as Pe,ap as Le,aq as Te,ar as Ie,as as Be,at as Oe,au as Ae,av as ze,aw as $e,ax as He,ay as We,az as Fe,aA as Ke,aB as Ue,aC as Ve,aD as qe,aE as Ye,aF as Xe,aG as Ge,aH as Ze,aI as Je,aJ as Qe,aK as et,aL as tt,aM as it,aN as st,aO as rt,aP as nt,aQ as ot,aR as at,aS as lt,aT as ct,aU as ht,aV as dt,aW as ut,aX as ft,aY as pt,aZ as mt,a_ as _t,a$ as gt,b0 as vt,b1 as yt,b2 as xt}from"./index-YwIvszwO.js";import{p as bt}from"./purify.es-CgRAQgUo.js";import{F as wt,M as St,r as Ct,a as kt,b as Et,c as Nt,h as Mt,o as jt,d as Dt,e as Rt,I as Pt,C as Lt,G as Tt,f as It}from"./ChatOverlay-V7DBSoaF.js";import{S as Bt,U as Ot,T as At,a as zt,b as $t,c as Ht,R as Wt,A as Ft,d as Kt,e as Ut,f as Vt,I as qt,g as Yt,C as Xt,h as Gt,i as Zt,j as Jt,k as Qt,l as ei,m as ti}from"./select-BUvVYFSc.js";import{C as ii}from"./chevron-down-DSuYI8m-.js";import{u as si,C as ri,a as ni}from"./index-DLIf9Yfa.js";import{S as oi}from"./search-CaBUM8S-.js";
3
3
  /**
4
4
  * @license lucide-react v0.309.0 - ISC
5
5
  *
6
6
  * This source code is licensed under the ISC license.
7
7
  * See the LICENSE file in the root directory of this source tree.
8
- */const ai=l("AlertCircle",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]]),li=l("ArrowRight",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]]),ci=l("Bot",[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]]),hi=l("ChevronLeft",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]),di=l("ClipboardCopy",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2",key:"4jdomd"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v4",key:"3hqy98"}],["path",{d:"M21 14H11",key:"1bme5i"}],["path",{d:"m15 10-4 4 4 4",key:"5dvupr"}]]),ui=l("Code",[["polyline",{points:"16 18 22 12 16 6",key:"z7tu5w"}],["polyline",{points:"8 6 2 12 8 18",key:"1eg1df"}]]),fi=l("Copy",[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]),pi=l("Database",[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]]),mi=l("FileSpreadsheet",[["path",{d:"M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z",key:"1nnpy2"}],["polyline",{points:"14 2 14 8 20 8",key:"1ew0cm"}],["path",{d:"M8 13h2",key:"yr2amv"}],["path",{d:"M8 17h2",key:"2yhykz"}],["path",{d:"M14 13h2",key:"un5t4a"}],["path",{d:"M14 17h2",key:"10kma7"}]]),_i=l("GitBranch",[["line",{x1:"6",x2:"6",y1:"3",y2:"15",key:"17qcm7"}],["circle",{cx:"18",cy:"6",r:"3",key:"1h7g24"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["path",{d:"M18 9a9 9 0 0 1-9 9",key:"n2h4wq"}]]),gi=l("GitCommitHorizontal",[["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["line",{x1:"3",x2:"9",y1:"12",y2:"12",key:"1dyftd"}],["line",{x1:"15",x2:"21",y1:"12",y2:"12",key:"oup4p8"}]]),vi=l("Info",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]]),yi=l("ListRestart",[["path",{d:"M21 6H3",key:"1jwq7v"}],["path",{d:"M7 12H3",key:"13ou7f"}],["path",{d:"M7 18H3",key:"1sijw9"}],["path",{d:"M12 18a5 5 0 0 0 9-3 4.5 4.5 0 0 0-4.5-4.5c-1.33 0-2.54.54-3.41 1.41L11 14",key:"qth677"}],["path",{d:"M11 10v4h4",key:"172dkj"}]]),xi=l("MessageSquare",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}]]),bi=l("MoreVertical",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]]),wi=l("Network",[["rect",{x:"16",y:"16",width:"6",height:"6",rx:"1",key:"4q2zg0"}],["rect",{x:"2",y:"16",width:"6",height:"6",rx:"1",key:"8cvhb9"}],["rect",{x:"9",y:"2",width:"6",height:"6",rx:"1",key:"1egb70"}],["path",{d:"M5 16v-3a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v3",key:"1jsf9p"}],["path",{d:"M12 12V8",key:"2874zd"}]]),Si=l("PanelLeft",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]]),Ci=l("PanelRight",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]]),ki=l("Play",[["polygon",{points:"5 3 19 12 5 21 5 3",key:"191637"}]]),Ei=l("Presentation",[["path",{d:"M2 3h20",key:"91anmk"}],["path",{d:"M21 3v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V3",key:"2k9sn8"}],["path",{d:"m7 21 5-5 5 5",key:"bip4we"}]]),Ni=l("Repeat",[["path",{d:"m17 2 4 4-4 4",key:"nntrym"}],["path",{d:"M3 11v-1a4 4 0 0 1 4-4h14",key:"84bu3i"}],["path",{d:"m7 22-4-4 4-4",key:"1wqhfi"}],["path",{d:"M21 13v1a4 4 0 0 1-4 4H3",key:"1rx37r"}]]),Mi=l("RotateCw",[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8",key:"1p45f6"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}]]),ji=l("Square",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]),Di=l("TrainTrack",[["path",{d:"M2 17 17 2",key:"18b09t"}],["path",{d:"m2 14 8 8",key:"1gv9hu"}],["path",{d:"m5 11 8 8",key:"189pqp"}],["path",{d:"m8 8 8 8",key:"1imecy"}],["path",{d:"m11 5 8 8",key:"ummqn6"}],["path",{d:"m14 2 8 8",key:"1vk7dn"}],["path",{d:"M7 22 22 7",key:"15mb1i"}]]),Ri=l("Workflow",[["rect",{width:"8",height:"8",x:"3",y:"3",rx:"2",key:"by2w9f"}],["path",{d:"M7 11v4a2 2 0 0 0 2 2h4",key:"xkn7yn"}],["rect",{width:"8",height:"8",x:"13",y:"13",rx:"2",key:"1cgmvn"}]]),Pi=l("ZoomIn",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"11",x2:"11",y1:"8",y2:"14",key:"1vmskp"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]]),Li=l("ZoomOut",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]]),Ii=N.lazy(()=>M(()=>import("./GraphPreview-BhYiu0BC.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9])).then(e=>({default:e.GraphPreview}))),Ti=N.lazy(()=>M(()=>import("./OfficePreview-AIsCrFJN.js"),__vite__mapDeps([10,1,2,3])).then(e=>({default:e.OfficePreview}))),Bi=N.lazy(()=>M(()=>import("./PdfPreview-BOf3iH2G.js"),__vite__mapDeps([11,1,2,12])).then(e=>({default:e.PdfPreview}))),Oi=new Set(["docx","xlsx","xls","pptx"]),Ai=new Set(["pdf"]),zi={js:"javascript",jsx:"jsx",ts:"typescript",tsx:"tsx",py:"python",rb:"ruby",go:"go",rs:"rust",java:"java",kt:"kotlin",swift:"swift",c:"c",cpp:"cpp",h:"c",cs:"csharp",php:"php",sh:"bash",bash:"bash",zsh:"bash",yaml:"yaml",yml:"yaml",json:"json",toml:"toml",html:"html",htm:"html",xml:"xml",svg:"xml",css:"css",scss:"scss",less:"less",sql:"sql",graphql:"graphql",gql:"graphql",dockerfile:"docker",makefile:"makefile",r:"r",lua:"lua",dart:"dart",zig:"zig"};
8
+ */const ai=l("AlertCircle",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]]),li=l("ArrowRight",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]]),ci=l("Bot",[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]]),hi=l("ChevronLeft",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]),di=l("ClipboardCopy",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2",key:"4jdomd"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v4",key:"3hqy98"}],["path",{d:"M21 14H11",key:"1bme5i"}],["path",{d:"m15 10-4 4 4 4",key:"5dvupr"}]]),ui=l("Code",[["polyline",{points:"16 18 22 12 16 6",key:"z7tu5w"}],["polyline",{points:"8 6 2 12 8 18",key:"1eg1df"}]]),fi=l("Copy",[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]),pi=l("Database",[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]]),mi=l("FileSpreadsheet",[["path",{d:"M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z",key:"1nnpy2"}],["polyline",{points:"14 2 14 8 20 8",key:"1ew0cm"}],["path",{d:"M8 13h2",key:"yr2amv"}],["path",{d:"M8 17h2",key:"2yhykz"}],["path",{d:"M14 13h2",key:"un5t4a"}],["path",{d:"M14 17h2",key:"10kma7"}]]),_i=l("GitBranch",[["line",{x1:"6",x2:"6",y1:"3",y2:"15",key:"17qcm7"}],["circle",{cx:"18",cy:"6",r:"3",key:"1h7g24"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["path",{d:"M18 9a9 9 0 0 1-9 9",key:"n2h4wq"}]]),gi=l("GitCommitHorizontal",[["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["line",{x1:"3",x2:"9",y1:"12",y2:"12",key:"1dyftd"}],["line",{x1:"15",x2:"21",y1:"12",y2:"12",key:"oup4p8"}]]),vi=l("Info",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]]),yi=l("ListRestart",[["path",{d:"M21 6H3",key:"1jwq7v"}],["path",{d:"M7 12H3",key:"13ou7f"}],["path",{d:"M7 18H3",key:"1sijw9"}],["path",{d:"M12 18a5 5 0 0 0 9-3 4.5 4.5 0 0 0-4.5-4.5c-1.33 0-2.54.54-3.41 1.41L11 14",key:"qth677"}],["path",{d:"M11 10v4h4",key:"172dkj"}]]),xi=l("MessageSquare",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}]]),bi=l("MoreVertical",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]]),wi=l("Network",[["rect",{x:"16",y:"16",width:"6",height:"6",rx:"1",key:"4q2zg0"}],["rect",{x:"2",y:"16",width:"6",height:"6",rx:"1",key:"8cvhb9"}],["rect",{x:"9",y:"2",width:"6",height:"6",rx:"1",key:"1egb70"}],["path",{d:"M5 16v-3a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v3",key:"1jsf9p"}],["path",{d:"M12 12V8",key:"2874zd"}]]),Si=l("PanelLeft",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]]),Ci=l("PanelRight",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]]),ki=l("Play",[["polygon",{points:"5 3 19 12 5 21 5 3",key:"191637"}]]),Ei=l("Presentation",[["path",{d:"M2 3h20",key:"91anmk"}],["path",{d:"M21 3v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V3",key:"2k9sn8"}],["path",{d:"m7 21 5-5 5 5",key:"bip4we"}]]),Ni=l("Repeat",[["path",{d:"m17 2 4 4-4 4",key:"nntrym"}],["path",{d:"M3 11v-1a4 4 0 0 1 4-4h14",key:"84bu3i"}],["path",{d:"m7 22-4-4 4-4",key:"1wqhfi"}],["path",{d:"M21 13v1a4 4 0 0 1-4 4H3",key:"1rx37r"}]]),Mi=l("RotateCw",[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8",key:"1p45f6"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}]]),ji=l("Square",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]),Di=l("TrainTrack",[["path",{d:"M2 17 17 2",key:"18b09t"}],["path",{d:"m2 14 8 8",key:"1gv9hu"}],["path",{d:"m5 11 8 8",key:"189pqp"}],["path",{d:"m8 8 8 8",key:"1imecy"}],["path",{d:"m11 5 8 8",key:"ummqn6"}],["path",{d:"m14 2 8 8",key:"1vk7dn"}],["path",{d:"M7 22 22 7",key:"15mb1i"}]]),Ri=l("Workflow",[["rect",{width:"8",height:"8",x:"3",y:"3",rx:"2",key:"by2w9f"}],["path",{d:"M7 11v4a2 2 0 0 0 2 2h4",key:"xkn7yn"}],["rect",{width:"8",height:"8",x:"13",y:"13",rx:"2",key:"1cgmvn"}]]),Pi=l("ZoomIn",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"11",x2:"11",y1:"8",y2:"14",key:"1vmskp"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]]),Li=l("ZoomOut",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]]),Ti=N.lazy(()=>M(()=>import("./GraphPreview-BxBsGYE9.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9])).then(e=>({default:e.GraphPreview}))),Ii=N.lazy(()=>M(()=>import("./OfficePreview-CWiJpp9Z.js"),__vite__mapDeps([10,1,2,3])).then(e=>({default:e.OfficePreview}))),Bi=N.lazy(()=>M(()=>import("./PdfPreview-2DcKEMbR.js"),__vite__mapDeps([11,1,2,12])).then(e=>({default:e.PdfPreview}))),Oi=new Set(["docx","xlsx","xls","pptx"]),Ai=new Set(["pdf"]),zi={js:"javascript",jsx:"jsx",ts:"typescript",tsx:"tsx",py:"python",rb:"ruby",go:"go",rs:"rust",java:"java",kt:"kotlin",swift:"swift",c:"c",cpp:"cpp",h:"c",cs:"csharp",php:"php",sh:"bash",bash:"bash",zsh:"bash",yaml:"yaml",yml:"yaml",json:"json",toml:"toml",html:"html",htm:"html",xml:"xml",svg:"xml",css:"css",scss:"scss",less:"less",sql:"sql",graphql:"graphql",gql:"graphql",dockerfile:"docker",makefile:"makefile",r:"r",lua:"lua",dart:"dart",zig:"zig"};
9
9
  /**
10
10
  * @license lucide-react v0.309.0 - ISC
11
11
  *
12
12
  * This source code is licensed under the ISC license.
13
13
  * See the LICENSE file in the root directory of this source tree.
14
- */const $i=new Set(["png","jpg","jpeg","gif","webp","svg","bmp","ico","avif","tiff","tif"]);function Hi(e){return"md"===e?"Markdown":"html"===e||"htm"===e?"HTML":"高亮"}const Wi=[50,75,100,125,150,200,250,300],Fi=100;function Ki({filePath:e,onClose:t,onMinimize:i}){const s=c(),r=e.endsWith("/.notebook/graph.yaml"),n=r?e.replace(/\/.notebook\/graph\.yaml$/,""):"",[o,a]=h.useState(null),[l,N]=h.useState(null),[M,D]=h.useState(()=>r?"graph":"rendered"),[R,P]=h.useState(!1),[L,I]=h.useState(Fi),[T,B]=h.useState(""),[O,A]=h.useState(!1),[z,$]=h.useState(!1),H=h.useRef(null),[W,F]=h.useState(!0),{resolved:K}=d(),U=e.split("/").pop()??e,V=h.useMemo(()=>function(e){const t=e.split("/").pop()??"",i=t.toLowerCase();if("dockerfile"===i)return"dockerfile";if("makefile"===i)return"makefile";const s=t.lastIndexOf(".");return s>=0?t.slice(s+1).toLowerCase():""}(e),[e]),q=$i.has(V),Y=Oi.has(V),X=Ai.has(V),G=function(e){return"md"===e||"html"===e||"htm"===e||e in zi}(V),Z=zi[V]||V,J=h.useMemo(()=>{if(!q)return"";const t=C(e),i=u(),s=`${t}&t=${Date.now()}`;return i?`${s}&token=${encodeURIComponent(i)}`:s},[e,q]);h.useEffect(()=>{if(F(!0),a(null),N(null),I(function(e){const t=k(E.fileZoom,{},!0)[e];return Wi.includes(t)?t:Fi}(e)),$(!1),q||Y||X)return a({path:e,binary:!1,tooLarge:!1,size:0,content:null}),void D("rendered");D(e.endsWith("/.notebook/graph.yaml")?"graph":"rendered"),f(e).then(e=>{a(e),B(e.content??"")}).catch(e=>N(e instanceof Error?e.message:"Failed to load file"))},[e,q,Y,X]);const Q=h.useCallback(async()=>{A(!0);try{await p(e,T),a(e=>e?{...e,content:T,size:new Blob([T]).size}:e),$(!1)}catch(t){m.error(t instanceof Error?t.message:"保存失败")}finally{A(!1)}},[e,T]);h.useEffect(()=>{const e=e=>{(e.metaKey||e.ctrlKey)&&"s"===e.key&&"edit"===M&&(e.preventDefault(),Q())};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[M,Q]),h.useEffect(()=>{const e=async e=>{if("Escape"===e.key&&W){if(z){if(!(await s({description:"有未保存的修改,确定关闭?",confirmLabel:"放弃修改",destructive:!0})))return}t()}};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[W,t,z,s]);const ee=async()=>{if(z){if(!(await s({description:"有未保存的修改,确定退出编辑?",confirmLabel:"放弃修改",destructive:!0})))return}D(r?"graph":G?"rendered":"plain"),$(!1)},te=t=>{I(t),function(e,t){const i=k(E.fileZoom,{},!0);t===Fi?delete i[e]:i[e]=t,j(E.fileZoom,i,!0)}(e,t)},ie=(null==o?void 0:o.content)??"",se="dark"===K?jt:Dt,re=L/100*12,ne=o&&!o.binary&&!o.tooLarge&&!X,oe=h.useDeferredValue(T),ae=h.useMemo(()=>{var e,t;if(!o||o.binary||o.tooLarge)return null;if(q||Y||X)return null;const i="edit"===M?oe:ie;if(null==i)return null;return{bytes:new Blob([i]).size,words:((null==(e=i.match(/[\u4e00-\u9fff\u3400-\u4dbf]/g))?void 0:e.length)??0)+((null==(t=i.replace(/[\u4e00-\u9fff\u3400-\u4dbf]/g," ").match(/[a-zA-Z0-9]+/g))?void 0:t.length)??0),lines:""===i?0:i.split("\n").length}},[o,q,Y,M,oe,ie]);return _.jsx("div",{className:g("fixed inset-0 z-50 flex items-center justify-center transition-all duration-200",W?"bg-black/60 backdrop-blur-sm pointer-events-auto":"bg-transparent pointer-events-none"),onClick:e=>{e.target===e.currentTarget&&F(!1)},children:_.jsxs("div",{className:g("relative flex flex-col bg-background border border-border shadow-sm transition-all duration-200 pointer-events-auto",R?"w-screen h-screen rounded-none":"w-[72vw] max-w-4xl h-[80vh] rounded-xl",!W&&!R&&"opacity-50"),onClick:()=>F(!0),onFocus:e=>{e.stopPropagation(),F(!0)},children:[_.jsxs("div",{className:"flex items-center gap-2 px-4 h-10 border-b border-border flex-shrink-0",children:[_.jsx(wt,{className:"h-3.5 w-3.5 text-muted-foreground flex-shrink-0"}),_.jsxs("span",{className:"flex-1 text-sm text-foreground font-medium truncate",title:e,children:[U,z&&_.jsx("span",{className:"text-muted-foreground ml-1",children:"*"}),ae&&_.jsxs("span",{className:"text-muted-foreground font-normal ml-2 text-xs tabular-nums",children:[(le=ae.bytes,le<1024?`${le} B`:le<1048576?`${(le/1024).toFixed(1)} KB`:`${(le/1024/1024).toFixed(2)} MB`)," · ",ae.words.toLocaleString()," 词 · ",ae.lines.toLocaleString()," 行"]})]}),ne&&!q&&!Y&&_.jsxs("div",{className:"flex items-center rounded-md border border-border bg-muted/50 p-0.5",children:[G&&_.jsxs(_.Fragment,{children:[_.jsxs("button",{onClick:()=>"edit"===M?ee():D("plain"),className:g("p-1 rounded-md transition-colors flex items-center gap-1 text-xs","plain"===M?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),title:"纯文本",children:[_.jsx(ui,{className:"h-3 w-3"}),_.jsx("span",{className:"hidden sm:inline",children:"源码"})]}),_.jsxs("button",{onClick:()=>"edit"===M?ee():D("rendered"),className:g("p-1 rounded-md transition-colors flex items-center gap-1 text-xs","rendered"===M?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),title:Hi(V),children:[_.jsx(v,{className:"h-3 w-3"}),_.jsx("span",{className:"hidden sm:inline",children:Hi(V)})]})]}),r&&_.jsxs("button",{onClick:()=>"edit"===M?ee():D("graph"),className:g("p-1 rounded-md transition-colors flex items-center gap-1 text-xs","graph"===M?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),title:"图谱",children:[_.jsx(wi,{className:"h-3 w-3"}),_.jsx("span",{className:"hidden sm:inline",children:"图谱"})]}),_.jsxs("button",{onClick:()=>"edit"===M?ee():(B((null==o?void 0:o.content)??""),$(!1),D("edit"),void setTimeout(()=>{var e;return null==(e=H.current)?void 0:e.focus()},0)),className:g("p-1 rounded-md transition-colors flex items-center gap-1 text-xs","edit"===M?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),title:"编辑",children:[_.jsx(y,{className:"h-3 w-3"}),_.jsx("span",{className:"hidden sm:inline",children:"编辑"})]})]}),"edit"===M&&_.jsxs("button",{onClick:()=>{Q()},disabled:O||!z,className:g("flex items-center gap-1 text-xs px-2 py-1 rounded transition-colors",z?"bg-blue-600 hover:bg-blue-500 text-white":"bg-muted text-muted-foreground"),title:"保存 (⌘S)",children:[_.jsx(Bt,{className:"h-3 w-3"}),O?"保存中...":"保存"]}),(ne||q||X)&&"edit"!==M&&"graph"!==M&&_.jsxs("div",{className:"flex items-center rounded-md border border-border bg-muted/50 p-0.5 gap-0.5",children:[_.jsx("button",{onClick:()=>{const e=[...Wi].reverse().find(e=>e<L);e&&te(e)},disabled:L<=Wi[0],className:"p-1 rounded-md text-muted-foreground hover:text-foreground transition-colors disabled:opacity-30",title:"缩小",children:_.jsx(Li,{className:"h-3 w-3"})}),_.jsxs("button",{onClick:()=>te(Fi),className:"px-1 text-xs text-muted-foreground hover:text-foreground transition-colors min-w-[36px] text-center",title:"重置缩放",children:[L,"%"]}),_.jsx("button",{onClick:()=>{const e=Wi.find(e=>e>L);e&&te(e)},disabled:L>=Wi[Wi.length-1],className:"p-1 rounded-md text-muted-foreground hover:text-foreground transition-colors disabled:opacity-30",title:"放大",children:_.jsx(Pi,{className:"h-3 w-3"})})]}),i&&_.jsx("button",{className:"p-1 rounded text-muted-foreground hover:text-foreground transition-colors",onClick:i,title:"最小化到 dock",children:_.jsx(x,{className:"h-3.5 w-3.5"})}),_.jsx("button",{className:"p-1 rounded text-muted-foreground hover:text-foreground transition-colors",onClick:()=>P(e=>!e),title:R?"退出全屏":"全屏",children:R?_.jsx(b,{className:"h-3.5 w-3.5"}):_.jsx(w,{className:"h-3.5 w-3.5"})}),_.jsx("button",{className:"p-0.5 rounded text-muted-foreground hover:text-foreground transition-colors",onClick:async()=>{if(z){if(!(await s({description:"有未保存的修改,确定关闭?",confirmLabel:"放弃修改",destructive:!0})))return}t()},children:_.jsx(S,{className:"h-4 w-4"})})]}),_.jsxs("div",{className:g("flex-1 min-h-0","graph"===M?"overflow-hidden":"overflow-auto"),children:["graph"===M&&_.jsx(h.Suspense,{fallback:_.jsx("p",{className:"text-sm text-muted-foreground p-4",children:"Loading…"}),children:_.jsx(Ii,{folderPath:n})}),"graph"!==M&&!o&&!l&&_.jsx("p",{className:"text-sm text-muted-foreground p-4",children:"Loading…"}),"graph"!==M&&l&&_.jsx("p",{className:"text-sm text-red-400 p-4",children:l}),"graph"!==M&&q&&o&&_.jsx("div",{className:"flex items-center justify-center p-4 h-full",children:_.jsx("img",{src:J,alt:U,className:"max-w-full max-h-full object-contain rounded-md",style:{transform:`scale(${L/100})`,transformOrigin:"center center"},draggable:!1})}),"graph"!==M&&Y&&o&&_.jsx(h.Suspense,{fallback:_.jsx("p",{className:"text-sm text-muted-foreground p-4",children:"Loading…"}),children:_.jsx(Ti,{filePath:e,ext:V,zoom:L})}),"graph"!==M&&X&&o&&_.jsx(h.Suspense,{fallback:_.jsx("p",{className:"text-sm text-muted-foreground p-4",children:"Loading…"}),children:_.jsx(Bi,{filePath:e,zoom:L})}),"graph"!==M&&!q&&!Y&&!X&&o&&o.binary&&_.jsxs("div",{className:"flex flex-col items-center gap-2 py-12 text-muted-foreground p-4",children:[_.jsx(wt,{className:"h-8 w-8"}),_.jsx("p",{className:"text-sm",children:"Binary file — cannot preview"}),_.jsxs("p",{className:"text-xs text-muted-foreground",children:[(o.size/1024).toFixed(1)," KB"]})]}),"graph"!==M&&!Y&&o&&o.tooLarge&&_.jsxs("div",{className:"flex flex-col items-center gap-2 py-12 text-muted-foreground p-4",children:[_.jsx(wt,{className:"h-8 w-8"}),_.jsx("p",{className:"text-sm",children:"File too large to preview"}),_.jsxs("p",{className:"text-xs text-muted-foreground",children:[(o.size/1024/1024).toFixed(2)," MB (limit 5 MB)"]})]}),"graph"!==M&&ne&&null!==ie&&_.jsxs(_.Fragment,{children:["edit"===M&&_.jsx("textarea",{ref:H,value:T,onChange:e=>{B(e.target.value),$(!0)},className:"w-full h-full bg-transparent text-foreground font-mono outline-none resize-none p-4 leading-relaxed",style:{fontSize:`${re}px`,minHeight:"100%"},spellCheck:!1}),"edit"!==M&&_.jsxs("div",{className:"p-4",style:{fontSize:`${re}px`},children:["plain"===M&&_.jsx("pre",{className:"font-mono text-foreground whitespace-pre-wrap break-words leading-relaxed",style:{fontSize:"inherit"},children:ie}),"rendered"===M&&"md"===V&&_.jsx("div",{className:"prose dark:prose-invert max-w-none prose-pre:bg-muted prose-pre:border prose-pre:border-border prose-code:text-foreground",style:{fontSize:"inherit"},children:_.jsx(St,{remarkPlugins:[kt,Et],rehypePlugins:[Ct],urlTransform:(e,t,i)=>"src"===t&&"img"===i.tagName?e:Rt(e),components:{code({className:e,children:t,...i}){const s=/language-(\w+)/.exec(e||"");return!s&&!e?_.jsx("code",{className:e,...i,children:t}):_.jsx(Mt,{style:se,language:(null==s?void 0:s[1])||"text",PreTag:"div",customStyle:{fontSize:"inherit",borderRadius:"6px",margin:0},children:String(t).replace(/\n$/,"")})},img:({src:t,alt:i,...s})=>_.jsx("img",{...s,src:Nt(e,t,u()),alt:i??"",loading:"lazy",style:{maxWidth:"100%",height:"auto"}})},children:ie})}),"rendered"===M&&("html"===V||"htm"===V)&&_.jsx("iframe",{srcDoc:bt.sanitize(ie,{WHOLE_DOCUMENT:!0,ADD_TAGS:["style","link"]}),className:"w-full h-full border-0 rounded bg-white",sandbox:"",title:U,style:{minHeight:"60vh",transform:`scale(${L/100})`,transformOrigin:"top left",width:1e4/L+"%",height:1e4/L+"%"}}),"rendered"===M&&"md"!==V&&"html"!==V&&"htm"!==V&&Z&&_.jsx(Mt,{style:se,language:Z,showLineNumbers:!0,lineNumberStyle:{color:"dark"===K?"#555":"#aaa",fontSize:"inherit"},customStyle:{fontSize:"inherit",borderRadius:"6px",margin:0,background:"transparent"},children:ie}),"rendered"===M&&!G&&_.jsx("pre",{className:"font-mono text-foreground whitespace-pre-wrap break-words leading-relaxed",style:{fontSize:"inherit"},children:ie})]})]})]})]})});var le}async function Ui(e){var t;if("undefined"!=typeof navigator&&(null==(t=navigator.clipboard)?void 0:t.writeText))try{return await navigator.clipboard.writeText(e),!0}catch{}try{const t=document.createElement("textarea");t.value=e,t.style.position="fixed",t.style.left="-9999px",t.style.top="0",t.setAttribute("readonly",""),document.body.appendChild(t),t.select(),t.setSelectionRange(0,e.length);const i=document.execCommand("copy");return document.body.removeChild(t),i}catch{return!1}}const Vi=new Set(["png","jpg","jpeg","gif","webp","svg","bmp","ico","avif","tiff","tif"]);function qi(e){const t=e.lastIndexOf(".");return t>=0&&Vi.has(e.slice(t+1).toLowerCase())}function Yi({projectPath:e,projectId:t}){var i;const[s,r]=h.useState(new Map),[n,o]=h.useState(new Set([e])),[a,l]=h.useState(new Set),d=D(e=>e.get(t).activePreviewPath),f=D(e=>e.get(t).filePreviews),p=D(e=>e.openFilePreview),v=D(e=>e.closeFilePreview),y=D(e=>e.minimizeFilePreview),x=!!(null==(i=f.find(e=>e.path===d))?void 0:i.minimized),[b,w]=h.useState(null),[S,k]=h.useState(!1),[E,N]=h.useState(null),[M,j]=h.useState(!1),W=c(),F=h.useRef(null),K=h.useRef(null),U=h.useRef(null),V=function(e={}){const t=e.duration??500,i=e.moveTolerance??10,s=h.useRef(null),r=h.useRef(null),n=h.useRef(!1),o=h.useCallback(()=>{s.current&&(clearTimeout(s.current),s.current=null),r.current=null},[]);return{bind:h.useCallback(e=>({onTouchStart:i=>{if(1!==i.touches.length)return;const o=i.touches[0];r.current={x:o.clientX,y:o.clientY},n.current=!1,s.current&&clearTimeout(s.current),s.current=setTimeout(()=>{if(n.current=!0,"undefined"!=typeof navigator&&"vibrate"in navigator)try{navigator.vibrate(15)}catch{}e(o.clientX,o.clientY)},t)},onTouchMove:e=>{if(!r.current||!s.current)return;const t=e.touches[0],n=t.clientX-r.current.x,a=t.clientY-r.current.y;Math.hypot(n,a)>i&&o()},onTouchEnd:o,onTouchCancel:o}),[t,i,o]),wasTriggered:n}}();h.useEffect(()=>{if(!b)return;const e=()=>w(null);return window.addEventListener("click",e),window.addEventListener("scroll",e,!0),()=>{window.removeEventListener("click",e),window.removeEventListener("scroll",e,!0)}},[b]);const q=async(t,i)=>{var s;if(0===t.length)return;const r=i??e,n=t.reduce((e,t)=>e+t.size,0);k(!0),N({loaded:0,total:n});try{const i=await O(r,t,(e,t)=>{N({loaded:e,total:t})});r!==e&&o(e=>new Set(e).add(r)),X(r);const n=i.uploaded.length,a=(null==(s=i.skipped)?void 0:s.length)??0,l=i.errors.length;l>0?m.error(`上传完成:${n} 成功,${l} 失败${a?`,${a} 跳过`:""}`):a>0?m.info(`已上传 ${n} 个文件,${a} 个同名文件被跳过`):m.success(`已上传 ${n} 个文件`)}catch(a){console.error("[FileTree] Upload failed:",a),m.error(`上传失败: ${a.message}`)}finally{k(!1),N(null)}},Y=e=>e>=1073741824?(e/1073741824).toFixed(2)+" GB":e>=1048576?(e/1048576).toFixed(1)+" MB":e>=1024?(e/1024).toFixed(0)+" KB":e+" B",X=h.useCallback(async e=>{l(t=>{if(t.has(e))return t;const i=new Set(t);return i.add(e),i});try{const t=await R(e);r(i=>new Map(i).set(e,t.entries))}catch(t){console.error("[FileTree] Failed to load:",e,t),r(t=>new Map(t).set(e,[]))}finally{l(t=>{const i=new Set(t);return i.delete(e),i})}},[]);h.useEffect(()=>{r(new Map),o(new Set([e])),l(new Set),X(e)},[e,X]);const G=h.useCallback(e=>{o(t=>{const i=new Set(t);return i.has(e)?i.delete(e):(i.add(e),s.has(e)||X(e)),i})},[s,X]),Z=h.useCallback(()=>{r(new Map),o(new Set([e])),l(new Set),X(e)},[e,X]),J=(e,i)=>e.map(e=>{const r=n.has(e.path),o=a.has(e.path),l=s.get(e.path),c=e.name.startsWith(".");return _.jsxs("div",{children:[_.jsxs("div",{className:g("flex items-center gap-1 py-[3px] rounded cursor-pointer","hover:bg-muted-foreground/10",c&&"opacity-50"),style:{paddingLeft:14*i+6+"px",paddingRight:"6px",WebkitTouchCallout:"none"},onClick:i=>{if(V.wasTriggered.current)return V.wasTriggered.current=!1,void i.stopPropagation();"dir"===e.type?G(e.path):p(t,e.path)},onContextMenu:t=>{t.preventDefault(),w({x:t.clientX,y:t.clientY,filePath:e.path,fileName:e.name,type:e.type})},...V.bind((t,i)=>{w({x:t,y:i,filePath:e.path,fileName:e.name,type:e.type})}),children:[_.jsx("span",{className:"w-3 flex-shrink-0 text-muted-foreground",children:"dir"===e.type&&(o?_.jsx(I,{className:"h-2.5 w-2.5 animate-spin"}):r?_.jsx(ii,{className:"h-2.5 w-2.5"}):_.jsx(A,{className:"h-2.5 w-2.5"}))}),"dir"===e.type?r?_.jsx(T,{className:"h-3.5 w-3.5 text-blue-400 flex-shrink-0"}):_.jsx(z,{className:"h-3.5 w-3.5 text-blue-400 flex-shrink-0"}):qi(e.name)?_.jsx(Pt,{className:"h-3.5 w-3.5 text-green-400 flex-shrink-0"}):_.jsx(wt,{className:"h-3.5 w-3.5 text-muted-foreground flex-shrink-0"}),_.jsx("span",{className:g("text-xs truncate leading-none","dir"===e.type?"text-foreground":"text-muted-foreground"),title:e.path,children:e.name})]}),_.jsx($,{initial:!1,children:"dir"===e.type&&r&&_.jsxs(H.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.15,ease:"easeInOut"},className:"overflow-hidden",children:[!l&&!o&&_.jsx("div",{className:"text-xs text-muted-foreground/50 py-0.5",style:{paddingLeft:14*(i+1)+6+16+"px"},children:"—"}),0===(null==l?void 0:l.length)&&_.jsx("div",{className:"text-xs text-muted-foreground/50 py-0.5",style:{paddingLeft:14*(i+1)+6+16+"px"},children:"empty"}),l&&l.length>0&&J(l,i+1)]})})]},e.path)}),Q=s.get(e),ee=a.has(e),te=e.split("/").filter(Boolean).pop()??e;return _.jsxs(_.Fragment,{children:[d&&!x&&_.jsx(Ki,{filePath:d,onClose:()=>v(t,d),onMinimize:()=>y(t,d)},d),b&&_.jsxs("div",{ref:F,className:"fixed z-50 min-w-[140px] bg-popover border border-border rounded-md shadow-md py-1",style:{left:b.x,top:b.y},onClick:e=>e.stopPropagation(),children:[_.jsxs("button",{className:"flex items-center gap-2 w-full px-3 py-1.5 text-xs hover:bg-accent hover:text-accent-foreground text-left",onClick:()=>{Ui(b.filePath.startsWith(e+"/")?b.filePath.slice(e.length+1):b.filePath).then(e=>{e?m.success("已复制相对路径"):m.error("复制失败")}),w(null)},children:[_.jsx(fi,{className:"h-3.5 w-3.5"}),"复制相对路径"]}),_.jsxs("button",{className:"flex items-center gap-2 w-full px-3 py-1.5 text-xs hover:bg-accent hover:text-accent-foreground text-left",onClick:()=>{Ui(b.filePath).then(e=>{e?m.success("已复制绝对路径"):m.error("复制失败")}),w(null)},children:[_.jsx(di,{className:"h-3.5 w-3.5"}),"复制绝对路径"]}),"file"===b.type&&_.jsxs(_.Fragment,{children:[_.jsx("div",{className:"my-1 border-t border-border"}),_.jsxs("button",{className:"flex items-center gap-2 w-full px-3 py-1.5 text-xs hover:bg-accent hover:text-accent-foreground text-left",onClick:()=>{(async(e,t)=>{let i=C(e);const s=u();s&&(i+=`${i.includes("?")?"&":"?"}token=${encodeURIComponent(s)}`);const r=`${i}${i.includes("?")?"&":"?"}dl=1`;try{const e=await fetch(r,{method:"HEAD"});if(!e.ok)return void m.error(`下载失败 (${e.status})`)}catch{return void m.error("下载失败:网络错误")}const n=document.createElement("a");n.href=r,n.download=t,document.body.appendChild(n),n.click(),document.body.removeChild(n)})(b.filePath,b.fileName),w(null)},children:[_.jsx(P,{className:"h-3.5 w-3.5"}),"下载"]})]}),"dir"===b.type&&_.jsxs(_.Fragment,{children:[_.jsx("div",{className:"my-1 border-t border-border"}),_.jsxs("button",{className:"flex items-center gap-2 w-full px-3 py-1.5 text-xs hover:bg-accent hover:text-accent-foreground text-left",disabled:S,onClick:()=>{var e;U.current=b.filePath,w(null),null==(e=K.current)||e.click()},children:[_.jsx(Ot,{className:"h-3.5 w-3.5"}),"上传文件到此文件夹"]})]}),_.jsx("div",{className:"my-1 border-t border-border"}),_.jsxs("button",{className:"flex items-center gap-2 w-full px-3 py-1.5 text-xs hover:bg-destructive/80 hover:text-destructive-foreground text-left",onClick:()=>{(async(t,i,r)=>{const n="dir"===r?`文件夹 "${i}" 及其所有内容`:`文件 "${i}"`;if(await W({title:"确认删除",description:`确认删除${n}?此操作不可撤销。`,destructive:!0,confirmLabel:"删除"}))try{await B(t),m.success(`已删除: ${i}`);const r=t.substring(0,t.lastIndexOf("/"));r&&s.has(r)?X(r):X(e)}catch(o){m.error(`删除失败: ${o.message}`)}})(b.filePath,b.fileName,b.type),w(null)},children:[_.jsx(L,{className:"h-3.5 w-3.5"}),"删除"]})]}),_.jsxs("div",{className:"h-full flex flex-col text-foreground select-none",children:[_.jsxs("div",{className:"flex items-center justify-between px-3 h-9 border-b border-border flex-shrink-0",children:[_.jsx("span",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Files"}),_.jsxs("div",{className:"flex items-center gap-0.5",children:[_.jsx("input",{ref:K,type:"file",multiple:!0,className:"hidden",onChange:e=>{const t=Array.from(e.target.files??[]),i=U.current;U.current=null,t.length>0&&q(t,i??void 0),e.target.value=""}}),_.jsx("button",{className:"text-muted-foreground hover:text-foreground p-0.5 rounded transition-colors",onClick:()=>{var e;U.current=null,null==(e=K.current)||e.click()},disabled:S,title:"上传文件",children:_.jsx(Ot,{className:g("h-3 w-3",S&&"animate-pulse")})}),_.jsx("button",{className:"text-muted-foreground hover:text-foreground p-0.5 rounded transition-colors",onClick:Z,title:"Refresh file tree",children:_.jsx(I,{className:g("h-3 w-3",ee&&"animate-spin")})})]})]}),_.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-2 border-b border-border flex-shrink-0",children:[_.jsx(T,{className:"h-3.5 w-3.5 text-blue-400 flex-shrink-0"}),_.jsx("span",{className:"text-xs text-foreground font-medium truncate",title:e,children:te})]}),_.jsxs("div",{className:g("flex-1 overflow-y-auto py-1 min-h-0 transition-colors",M&&"bg-accent/30 ring-1 ring-inset ring-accent"),onDragOver:e=>{e.preventDefault(),j(!0)},onDragEnter:e=>{e.preventDefault(),j(!0)},onDragLeave:()=>j(!1),onDrop:e=>{e.preventDefault(),j(!1);const t=Array.from(e.dataTransfer.files);t.length>0&&q(t)},children:[S&&E&&_.jsxs("div",{className:"px-3 py-2 border-b border-border space-y-1",children:[_.jsxs("div",{className:"flex items-center justify-between text-[10px] text-muted-foreground",children:[_.jsxs("span",{children:["上传中 ",Math.floor(E.loaded/Math.max(E.total,1)*100),"%"]}),_.jsxs("span",{className:"font-mono",children:[Y(E.loaded)," / ",Y(E.total)]})]}),_.jsx("div",{className:"h-1 bg-muted rounded-full overflow-hidden",children:_.jsx("div",{className:"h-full bg-primary transition-[width] duration-150",style:{width:E.loaded/Math.max(E.total,1)*100+"%"}})})]}),M&&!S&&_.jsx("div",{className:"text-xs text-muted-foreground px-4 py-1",children:"松开以上传文件"}),ee&&!Q?_.jsx("div",{className:"text-xs text-muted-foreground px-4 py-3",children:"Loading…"}):Q&&0!==Q.length?J(Q,0):_.jsx("div",{className:"text-xs text-muted-foreground px-4 py-3",children:"Empty folder"})]})]})]})}function Xi(e){const t=new Date(e),i=Date.now()-t.getTime();return i<36e5?`${Math.floor(i/6e4)}分钟前`:i<864e5?`${Math.floor(i/36e5)}小时前`:i<6048e5?`${Math.floor(i/864e5)}天前`:t.toLocaleDateString()}function Gi({projectId:e}){const[t,i]=h.useState(null),[s,r]=h.useState(!0),[n,o]=h.useState(null),[a,l]=h.useState(null),[c,d]=h.useState(""),[u,f]=h.useState(!1),[p,v]=h.useState([]),[y,x]=h.useState(0),[b,w]=h.useState(!0),[S,C]=h.useState(!1),k=h.useCallback(async()=>{r(!0);try{i(await W(e))}catch{i(null)}finally{r(!1)}},[e]),E=h.useCallback(async(t=!1)=>{C(!0);try{const i=t?p.length:0,s=await F(e,30,i);v(e=>t?[...e,...s.commits]:s.commits),x(s.total)}catch{}finally{C(!1)}},[e,p.length]);h.useEffect(()=>{k(),E()},[e]);const N=async t=>{try{const{diff:i}=await Y(e,t);o(i||"(no diff)"),l(t??"all changes")}catch{m.error("获取 diff 失败")}},M=async t=>{try{await X(e,[t]),m.success(`已暂存 ${t}`),await k()}catch{m.error("git add 失败")}},j=async()=>{if(c.trim()){f(!0);try{await G(e,c),m.success("提交成功"),d(""),await k()}catch(t){m.error(t instanceof Error?t.message:"提交失败")}finally{f(!1)}}};if(!t&&s)return _.jsxs("div",{className:"flex flex-col items-center gap-2 py-8 text-muted-foreground/50 text-xs",children:[_.jsx(_i,{className:"h-5 w-5"}),_.jsx("p",{children:"加载中…"})]});if(!t||!t.isRepo)return _.jsxs("div",{className:"flex flex-col items-center gap-2 py-8 text-muted-foreground/50 text-xs",children:[_.jsx(_i,{className:"h-5 w-5"}),_.jsx("p",{children:t?"非 Git 仓库":"加载失败"}),_.jsx(K,{variant:"ghost",size:"sm",className:"h-6 text-xs",onClick:()=>{k()},children:"重试"})]});const D=[...t.modified??[],...t.deleted??[]],R=t.staged??[],P=t.untracked??[];return _.jsxs("div",{className:"flex flex-col h-full overflow-y-auto p-2 space-y-2 text-xs",children:[_.jsxs("div",{className:"flex items-center justify-between",children:[_.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground font-medium",children:[_.jsx(_i,{className:"h-3 w-3"}),_.jsx("span",{children:t.branch}),(t.ahead??0)>0&&_.jsxs("span",{className:"text-blue-400",children:["↑",t.ahead]}),(t.behind??0)>0&&_.jsxs("span",{className:"text-yellow-400",children:["↓",t.behind]})]}),_.jsx(K,{variant:"ghost",size:"icon",className:"h-5 w-5",onClick:()=>{k()},disabled:s,children:_.jsx(I,{className:g("h-3 w-3",s&&"animate-spin")})})]}),R.length>0&&_.jsxs("div",{children:[_.jsxs("div",{className:"text-muted-foreground mb-1 font-medium",children:["已暂存 (",R.length,")"]}),R.map(e=>_.jsxs("div",{className:"flex items-center gap-1 py-0.5 px-1 rounded hover:bg-muted-foreground/10",children:[_.jsx(U,{className:"h-2.5 w-2.5 text-green-500 flex-shrink-0"}),_.jsx("button",{className:"flex-1 text-left truncate text-green-400",onClick:()=>{N(e)},children:e})]},e))]}),D.length>0&&_.jsxs("div",{children:[_.jsxs("div",{className:"text-muted-foreground mb-1 font-medium",children:["未暂存 (",D.length,")"]}),D.map(e=>_.jsxs("div",{className:"flex items-center gap-1 py-0.5 px-1 rounded hover:bg-muted-foreground/10",children:[_.jsx("button",{className:"flex-shrink-0 h-4 w-4 flex items-center justify-center rounded hover:bg-green-500/20 text-muted-foreground hover:text-green-400",title:"git add",onClick:()=>{M(e)},children:_.jsx(V,{className:"h-2.5 w-2.5"})}),_.jsx("button",{className:"flex-1 text-left truncate text-yellow-400",onClick:()=>{N(e)},children:e})]},e))]}),P.length>0&&_.jsxs("div",{children:[_.jsxs("div",{className:"text-muted-foreground mb-1 font-medium",children:["未跟踪 (",P.length,")"]}),P.map(e=>_.jsxs("div",{className:"flex items-center gap-1 py-0.5 px-1 rounded hover:bg-muted-foreground/10",children:[_.jsx("button",{className:"flex-shrink-0 h-4 w-4 flex items-center justify-center rounded hover:bg-green-500/20 text-muted-foreground hover:text-green-400",title:"git add",onClick:()=>{M(e)},children:_.jsx(V,{className:"h-2.5 w-2.5"})}),_.jsx("span",{className:"flex-1 truncate text-muted-foreground",children:e})]},e))]}),0===D.length&&0===R.length&&0===P.length&&_.jsx("p",{className:"text-muted-foreground/50 text-center py-4",children:"工作区干净"}),R.length>0&&_.jsxs("div",{className:"space-y-1.5 pt-1 border-t border-border",children:[_.jsx(q,{placeholder:"提交消息…",value:c,onChange:e=>d(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||j()},className:"h-7 text-xs"}),_.jsx(K,{size:"sm",className:"w-full h-7 text-xs",onClick:()=>{j()},disabled:!c.trim()||u,children:u?"提交中…":`提交 (${R.length} 文件)`})]}),(null==t?void 0:t.isRepo)&&_.jsxs("div",{className:"border-t border-border pt-2",children:[_.jsxs("button",{className:"flex items-center gap-1 text-muted-foreground font-medium mb-1 w-full text-left",onClick:()=>w(e=>!e),children:[_.jsx(ii,{className:g("h-3 w-3 transition-transform",!b&&"-rotate-90")}),_.jsx(gi,{className:"h-3 w-3"}),_.jsxs("span",{children:["提交历史 (",y,")"]})]}),b&&_.jsxs("div",{className:"space-y-0.5",children:[p.map((e,t)=>{const i=e.parents.length>1;return _.jsxs("div",{className:"flex gap-1.5 items-start group",children:[_.jsxs("div",{className:"flex flex-col items-center flex-shrink-0 w-3",children:[_.jsx("div",{className:g("w-2 h-2 rounded-full flex-shrink-0 mt-1",0===t?"bg-blue-400":i?"bg-purple-400":"bg-muted-foreground/40")}),t<p.length-1&&_.jsx("div",{className:"w-px flex-1 bg-border min-h-[12px]"})]}),_.jsxs("div",{className:"flex-1 min-w-0 pb-1",children:[_.jsxs("div",{className:"flex items-baseline gap-1",children:[_.jsx("span",{className:"font-mono text-muted-foreground/60 text-[10px] flex-shrink-0",children:e.hashShort}),_.jsx("span",{className:"truncate leading-tight",children:e.message.split("\n")[0]})]}),_.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] text-muted-foreground/50 mt-0.5",children:[_.jsx("span",{children:e.author}),_.jsx("span",{children:Xi(e.date)}),e.branches.length>0&&e.branches.slice(0,2).map(e=>_.jsx("span",{className:"px-1 py-px rounded bg-blue-500/10 text-blue-400 text-[9px]",children:e.replace("remotes/origin/","↑")},e))]})]})]},e.hash)}),p.length<y&&_.jsx("button",{className:"w-full text-center text-[10px] text-muted-foreground hover:text-foreground py-1",onClick:()=>{E(!0)},disabled:S,children:S?"加载中...":`加载更多 (${p.length}/${y})`})]})]}),null!==n&&_.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",onClick:()=>o(null),children:[_.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),_.jsxs("div",{className:"relative z-10 w-[700px] max-w-[95vw] max-h-[80vh] flex flex-col bg-background border border-border rounded-xl shadow-sm",onClick:e=>e.stopPropagation(),children:[_.jsxs("div",{className:"flex items-center justify-between px-4 h-10 border-b border-border text-sm font-medium flex-shrink-0",children:[_.jsx("span",{className:"truncate text-muted-foreground",children:a}),_.jsx("button",{className:"text-muted-foreground hover:text-foreground",onClick:()=>o(null),children:"✕"})]}),_.jsx("pre",{className:"flex-1 overflow-auto p-3 text-[11px] font-mono whitespace-pre leading-relaxed",children:n.split("\n").map((e,t)=>_.jsx("span",{className:g("block",e.startsWith("+")&&!e.startsWith("+++")&&"text-green-400 bg-green-400/5",e.startsWith("-")&&!e.startsWith("---")&&"text-red-400 bg-red-400/5",e.startsWith("@@")&&"text-blue-400"),children:e},t))})]})]})]})}function Zi(e){if(!e)return"-";const t=e-Date.now(),i=Math.abs(t),s=t<0,r=Math.round(i/1e3);if(r<60)return s?`${r} 秒前`:`${r} 秒后`;const n=Math.round(r/60);if(n<60)return s?`${n} 分钟前`:`${n} 分钟后`;const o=Math.round(n/60);if(o<24)return s?`${o} 小时前`:`${o} 小时后`;const a=Math.round(o/24);return s?`${a} 天前`:`${a} 天后`}function Ji(e){if(!e)return"";return new Date(e).toLocaleString(void 0,{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"})}function Qi({projectId:e}){const[t,i]=h.useState(null),[s,r]=h.useState(!0),[n,o]=h.useState(null),[,a]=h.useState(0),l=h.useRef(!0),c=h.useRef(0),d=h.useCallback(async()=>{const t=++c.current;r(!0),o(null);try{const{tasks:s}=await Z(e);if(!l.current||t!==c.current)return;i(s)}catch(ll){if(!l.current||t!==c.current)return;o(ll.message),i([])}finally{l.current&&t===c.current&&r(!1)}},[e]);return h.useEffect(()=>{l.current=!0,d();const e=setInterval(()=>{d()},3e4),t=setInterval(()=>a(e=>e+1),1e3);return()=>{l.current=!1,clearInterval(e),clearInterval(t)}},[d]),_.jsxs("div",{className:"h-full flex flex-col bg-muted text-foreground overflow-hidden",children:[_.jsxs("div",{className:"flex-shrink-0 px-3 py-2 flex items-center justify-between border-b border-border",children:[_.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium text-muted-foreground",children:[_.jsx(Lt,{className:"size-4"}),_.jsx("span",{children:"已排程任务"})]}),_.jsx(K,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{d()},title:"刷新","aria-label":"刷新",children:_.jsx(I,{className:g("size-3.5",s&&"animate-spin")})})]}),_.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-2 space-y-1.5",children:[_.jsxs("div",{className:"rounded-md bg-muted-foreground/5 px-2 py-1.5 text-[11px] text-muted-foreground flex items-start gap-1.5",children:[_.jsx(vi,{className:"size-3 mt-0.5 shrink-0"}),_.jsxs("span",{className:"leading-snug",children:["best-effort 重建:从 session JSONL 反推「Claude 创建过的 schedule」,",_.jsx("strong",{className:"text-foreground/80",children:"不是"}),"权威活动列表。已触发 / 已删除 无法直接观测。"]})]}),n&&_.jsx("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 text-destructive p-2 text-xs",children:n}),!n&&t&&0===t.length&&!s&&_.jsxs("div",{className:"px-2 py-6 text-center text-xs text-muted-foreground",children:[_.jsx("p",{children:"本项目最近 7 天没有创建过 schedule。"}),_.jsx("p",{className:"mt-2 leading-relaxed",children:"一次性 ScheduleWakeup 触发时间过了的会被隐藏(认为已触发); CronCreate 仅显示 7 天内创建的(与 Claude 自动过期窗口对齐)。"})]}),t&&t.map(e=>{const t=e.nextFireAt?Date.parse(e.nextFireAt):null,i="CronCreate"===e.type&&(e.recurring||/[,*\/-]/.test(e.cron??"")),s="ScheduleWakeup"===e.type&&null!==e.delaySeconds?function(e){if(e<60)return`${e} 秒后`;const t=Math.round(e/60);return t<60?`${t} 分钟后`:Math.round(t/60*10)/10+" 小时后"}(e.delaySeconds):e.cron??"?";return _.jsx("div",{className:"rounded-md border border-border bg-background px-2.5 py-2 text-xs",children:_.jsxs("div",{className:"flex items-start gap-2",children:[_.jsx("div",{className:"shrink-0 mt-0.5 text-muted-foreground",children:i?_.jsx(Ni,{className:"size-3.5"}):_.jsx(J,{className:"size-3.5"})}),_.jsxs("div",{className:"flex-1 min-w-0",children:[_.jsxs("div",{className:"flex flex-wrap items-center gap-1 mb-1",children:[_.jsx("span",{className:"text-[10px] font-mono px-1.5 rounded bg-muted-foreground/10 text-muted-foreground",children:"ScheduleWakeup"===e.type?"SW":"CC"}),e.durable&&_.jsx("span",{className:"text-[10px] px-1.5 rounded bg-primary/10 text-primary",children:"durable"}),_.jsx("code",{className:"text-[10px] bg-muted-foreground/10 px-1 rounded font-mono",children:s})]}),_.jsx("div",{className:"font-medium text-foreground line-clamp-2 leading-snug",children:e.prompt.trim()||"(无 prompt)"}),e.reason&&_.jsxs("div",{className:"mt-0.5 text-muted-foreground line-clamp-1 italic text-[11px]",children:["reason: ",e.reason]}),_.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-x-3 gap-y-0.5 text-[11px] text-muted-foreground",children:[null!==t&&_.jsxs("span",{title:Ji(t),children:["下次: ",_.jsx("span",{className:"text-foreground/90",children:Zi(t)})]}),_.jsxs("span",{title:Ji(e.createdAt),children:["创建: ",Zi(e.createdAt)]}),_.jsx("span",{className:"font-mono text-muted-foreground/70",children:e.sessionId.slice(0,8)})]})]})]})},`${e.sessionId}:${e.id}`)}),s&&!t&&_.jsx("div",{className:"space-y-1.5",children:[0,1].map(e=>_.jsx("div",{className:"rounded-md border border-border bg-background px-2.5 py-2 h-16 animate-pulse"},e))})]})]})}function es(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:e<1073741824?`${(e/1024/1024).toFixed(1)} MB`:`${(e/1024/1024/1024).toFixed(2)} GB`}function ts(e){if(!e)return"-";const t=e-Date.now(),i=Math.abs(t),s=t<0,r=Math.round(i/1e3);if(r<60)return s?`${r} 秒前`:`${r} 秒后`;const n=Math.round(r/60);if(n<60)return s?`${n} 分钟前`:`${n} 分钟后`;const o=Math.round(n/60);if(o<24)return s?`${o} 小时前`:`${o} 小时后`;const a=Math.round(o/24);return s?`${a} 天前`:`${a} 天后`}function is(e){return new Date(e).toLocaleString(void 0,{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"})}function ss({projectId:e}){const[t,i]=h.useState(null),[s,r]=h.useState(!0),[n,o]=h.useState(!1),[a,l]=h.useState(null),[,c]=h.useState(0),d=h.useRef(!0),u=h.useCallback(async()=>{l(null);try{const t=await Q(e);if(!d.current)return;i(t)}catch(ll){if(!d.current)return;l(ll.message)}finally{d.current&&r(!1)}},[e]),f=h.useCallback(async()=>{o(!0);try{const t=await ee(e);if(!d.current)return;const i=[];t.copied>0&&i.push(`新增/更新 ${t.copied}`),t.deleted>0&&i.push(`删除 ${t.deleted}`),t.skipped>0&&i.push(`跳过 ${t.skipped}`),m.success(`同步完成:${i.join("·")||"无变化"}`),await u()}catch(ll){m.error(`同步失败:${ll.message}`)}finally{d.current&&o(!1)}},[e,u]);h.useEffect(()=>{d.current=!0,u();const e=setInterval(()=>{u()},3e4),t=setInterval(()=>c(e=>e+1),5e3);return()=>{d.current=!1,clearInterval(e),clearInterval(t)}},[u]);const p=(null==t?void 0:t.files.reduce((e,t)=>e+t.bytes,0))??0;return _.jsxs("div",{className:"h-full flex flex-col bg-muted text-foreground overflow-hidden",children:[_.jsxs("div",{className:"flex-shrink-0 px-3 py-2 flex items-center justify-between border-b border-border",children:[_.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium text-muted-foreground",children:[_.jsx(te,{className:"size-4"}),_.jsx("span",{children:"聊天记录备份"})]}),_.jsx(K,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{u()},title:"刷新","aria-label":"刷新",disabled:s,children:_.jsx(I,{className:g("size-3.5",s&&"animate-spin")})})]}),_.jsx("div",{className:"flex-shrink-0 px-3 py-2 border-b border-border bg-background/40",children:_.jsxs("div",{className:"flex items-center justify-between gap-2",children:[_.jsxs("div",{className:"text-[11px] text-muted-foreground min-w-0",children:[_.jsxs("div",{children:["最后同步:"," ",_.jsx("span",{className:"text-foreground/90",title:(null==t?void 0:t.meta)?is(t.meta.lastBackupAt):void 0,children:(null==t?void 0:t.meta)?ts(t.meta.lastBackupAt):"从未同步"})]}),t&&_.jsxs("div",{className:"mt-0.5 text-muted-foreground/80",children:[t.files.length," 个文件 · ",es(p)]})]}),_.jsx(K,{size:"sm",className:"h-7 px-2.5 text-xs",onClick:()=>{f()},disabled:n||!(null==t?void 0:t.supported),children:n?"同步中…":"立即同步"})]})}),_.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-2 space-y-1",children:[a&&_.jsxs("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 text-destructive p-2 text-xs flex items-start gap-2",children:[_.jsx(ai,{className:"size-3.5 shrink-0 mt-0.5"}),_.jsx("span",{children:a})]}),t&&!t.supported&&_.jsx("div",{className:"px-2 py-6 text-center text-xs text-muted-foreground",children:_.jsxs("p",{children:["此项目使用 ",_.jsx("code",{className:"text-[10px] bg-muted-foreground/10 px-1 rounded",children:"terminal"})," 模式,无聊天记录需备份。"]})}),(null==t?void 0:t.supported)&&0===t.files.length&&!s&&!a&&_.jsxs("div",{className:"px-2 py-6 text-center text-xs text-muted-foreground",children:[_.jsx("p",{children:"暂无已备份的聊天记录"}),_.jsx("p",{className:"mt-2 leading-relaxed text-muted-foreground/80",children:'定时每 5 分钟同步一次,也可点击右上方"立即同步"手动触发。'}),_.jsxs("p",{className:"mt-1 text-muted-foreground/70",children:["备份路径: ",_.jsx("code",{className:"text-[10px] bg-muted-foreground/10 px-1 rounded break-all",children:t.backupDir})]})]}),null==t?void 0:t.files.map(e=>_.jsxs("div",{className:"rounded-md border border-border bg-background px-2.5 py-1.5 text-xs flex items-center gap-2 hover:bg-accent/50 transition-colors",children:[_.jsx(wt,{className:"size-3.5 shrink-0 text-muted-foreground"}),_.jsxs("div",{className:"flex-1 min-w-0",children:[_.jsx("div",{className:"font-mono text-[11px] text-foreground truncate",title:e.name,children:e.name}),_.jsxs("div",{className:"text-muted-foreground/80 text-[10px] flex items-center gap-2",children:[_.jsx("span",{title:is(e.mtime),children:ts(e.mtime)}),_.jsx("span",{className:"text-muted-foreground/40",children:"·"}),_.jsx("span",{children:es(e.bytes)})]})]})]},e.name)),s&&!t&&_.jsx("div",{className:"space-y-1",children:[0,1].map(e=>_.jsx("div",{className:"rounded-md border border-border bg-background h-10 animate-pulse"},e))})]})]})}async function rs(e,t,i){const s={"Content-Type":"application/json"},r=u();r&&(s.Authorization=`Bearer ${r}`);const n=await fetch(t,{method:e,headers:s,body:void 0!==i?JSON.stringify(i):void 0});if(!n.ok){let e,t=`HTTP ${n.status}`;try{e=await n.json();const i=e;(null==i?void 0:i.error)&&(t=i.error)}catch{}const i=new Error(t);throw i.status=n.status,i.detail=e,i}return n.json()}function ns(e,t){return rs("GET",`/api/projects/${e}/track-flows/file/${encodeURIComponent(t)}`)}function os(e,t,i,s,r){const n={flow:i};return void 0!==s&&(n.trainJson=s),(null==r?void 0:r.createOnly)&&(n.createOnly=!0),rs("PUT",`/api/projects/${e}/track-flows/file/${encodeURIComponent(t)}`,n)}function as(e,t,i){return rs("POST",`/api/projects/${e}/track-flows/file/${encodeURIComponent(t)}/cancel`,i?{runId:i}:{})}function ls(e,t){return rs("GET",`/api/projects/${e}/track-flows/runs/${encodeURIComponent(t)}/state`)}function cs(e){return`${e}_${"undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID().replace(/-/g,"").slice(0,6):Math.random().toString(36).slice(2,8)}`}function hs(e,t="claude-code"){return{version:3,trackName:e,adapter:t,variables:[],nodes:[],edges:[]}}function ds(e){if(!e||"object"!=typeof e)return{ok:!1,reason:"not an object"};const t=e;return 3!==t.version?{ok:!1,reason:`unsupported version: ${t.version}`}:"string"!=typeof t.trackName?{ok:!1,reason:"trackName missing"}:"string"!=typeof t.adapter?{ok:!1,reason:"adapter missing"}:Array.isArray(t.variables)&&Array.isArray(t.nodes)&&Array.isArray(t.edges)?{ok:!0,flow:t}:{ok:!1,reason:"variables/nodes/edges must be arrays"}}function us(e){const t={};for(const i of e)t[i.key]=i.initialValue??null;return t}const fs=28;function ps({flow:e,nodeStates:t,currentNodeId:i,status:s,onClose:r,embedded:n}){if(0===e.nodes.length)return null;const o=n?240:320,a=n?320:240,l=e.nodes.map(e=>e.position.x),c=e.nodes.map(e=>e.position.y),h=Math.min(...l),d=Math.max(...l),u=Math.min(...c),f=Math.max(...c),p=Math.max(1,d-h)+240,m=Math.max(1,f-u)+100,g=Math.min((o-24-80)/p,(a-24-fs)/m);function v(e){return 12+(e-h)*g}function y(e){return 12+(e-u)*g}function x(e){return{x:v(e.position.x)+40,y:y(e.position.y)+14}}const b=n?"w-full overflow-hidden rounded-md border border-border bg-card text-muted-foreground":"fixed bottom-4 right-4 z-40 rounded-lg shadow-lg border border-border backdrop-blur-md bg-card/70 text-muted-foreground";return _.jsxs("div",{className:b,style:n?void 0:{width:o},children:[_.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 border-b border-border",children:[_.jsxs("div",{className:"flex items-center gap-2 text-xs min-w-0",children:[_.jsx("span",{className:_s(s)}),_.jsx("span",{className:"font-medium text-foreground truncate",children:e.trackName}),_.jsx("span",{className:"text-muted-foreground shrink-0",children:(w=s,"running"===w?"运行中":"waiting_user_input"===w?"等待输入":"completed"===w?"已完成":"failed"===w?"失败":"已取消")})]}),_.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[("running"===s||"waiting_user_input"===s)&&_.jsx(K,{type:"button",variant:"destructive",size:"icon",onClick:()=>window.dispatchEvent(new CustomEvent("ccweb:flow-cancel-request")),title:"取消运行",className:"h-5 w-5",children:_.jsx(ji,{className:"h-2.5 w-2.5 fill-current"})}),r&&!n&&_.jsx(K,{type:"button",variant:"ghost",size:"icon",onClick:r,title:"关闭",className:"h-5 w-5",children:_.jsx(S,{className:"h-3 w-3"})})]})]}),_.jsxs("svg",{viewBox:`0 0 ${o} ${a}`,width:n?"100%":o,height:n?void 0:a,preserveAspectRatio:"xMinYMin meet",className:"block",children:[_.jsx("defs",{children:_.jsx("marker",{id:"mm-arrow",viewBox:"0 0 10 10",refX:"8",refY:"5",markerWidth:"6",markerHeight:"6",orient:"auto",children:_.jsx("path",{d:"M 0 0 L 10 5 L 0 10 z",fill:"currentColor"})})}),e.edges.map(t=>{const i=e.nodes.find(e=>e.id===t.source),s=t.target?e.nodes.find(e=>e.id===t.target):null;if(!i)return null;const r=x(i),n=s?x(s):{x:r.x,y:r.y+30},o="true"===t.sourceHandle?"stroke-emerald-500 dark:stroke-emerald-400":"false"===t.sourceHandle?"stroke-red-500 dark:stroke-red-400":"stroke-muted-foreground/60";return _.jsx("line",{x1:r.x,y1:r.y+14,x2:n.x,y2:s?n.y-14:n.y,className:o,strokeWidth:1.5,strokeDasharray:s?void 0:"3 3",markerEnd:"url(#mm-arrow)"},t.id)}),e.nodes.map(e=>{var s;const r=v(e.position.x),n=y(e.position.y),o=t.get(e.id)??null,a=i===e.id,{fillClass:l,strokeClass:c,textClass:h}=function(e,t,i){if("active"===t||i)return{fillClass:"fill-amber-100 dark:fill-amber-900/50",strokeClass:"stroke-amber-500",textClass:"fill-amber-900 dark:fill-amber-100"};if("completed"===t)return{fillClass:"fill-emerald-100 dark:fill-emerald-900/50",strokeClass:"stroke-emerald-500",textClass:"fill-emerald-900 dark:fill-emerald-100"};if("failed"===t)return{fillClass:"fill-red-100 dark:fill-red-900/50",strokeClass:"stroke-red-500",textClass:"fill-red-900 dark:fill-red-100"};if("skipped"===t)return{fillClass:"fill-muted dark:fill-muted",strokeClass:"stroke-muted-foreground/60",textClass:"fill-muted-foreground"};return"user_input"===e?{fillClass:"fill-pink-100 dark:fill-pink-900/40",strokeClass:"stroke-pink-400 dark:stroke-pink-700",textClass:"fill-foreground/80"}:"llm"===e?{fillClass:"fill-orange-100 dark:fill-orange-900/40",strokeClass:"stroke-orange-400 dark:stroke-orange-700",textClass:"fill-foreground/80"}:{fillClass:"fill-sky-100 dark:fill-sky-900/40",strokeClass:"stroke-sky-400 dark:stroke-sky-700",textClass:"fill-foreground/80"}}(e.type,o,a),d=(null==(s=e.label)?void 0:s.trim())||("user_input"===(u=e.type)?"用户输入":"llm"===u?"LLM":"判断");var u;return _.jsxs("g",{children:[_.jsx("rect",{x:r,y:n,width:80,height:fs,rx:6,ry:6,className:`${l} ${c}`,strokeWidth:a?2:1,style:a?{animationDuration:"1.5s"}:void 0,children:a&&_.jsx("animate",{attributeName:"opacity",values:"1;0.55;1",dur:"1.5s",repeatCount:"indefinite"})}),_.jsx("text",{x:r+40,y:n+14+1,textAnchor:"middle",dominantBaseline:"middle",className:`text-[10px] font-mono select-none ${h}`,children:ms(d,10)})]},e.id)})]})]});var w}function ms(e,t){return e.length>t?e.slice(0,t-1)+"…":e}function _s(e){const t="inline-block w-2 h-2 rounded-full shrink-0";return"running"===e?`${t} bg-amber-500 animate-pulse`:"waiting_user_input"===e?`${t} bg-sky-500`:"completed"===e?`${t} bg-emerald-500`:"failed"===e?`${t} bg-destructive`:`${t} bg-muted-foreground`}const gs=/^[a-zA-Z0-9_一-鿿぀-ヿㇰ-ㇿ-]+$/;function vs({projectId:e,onOpenEditor:t}){const i=c(),[s,r]=h.useState([]),[n,o]=h.useState(!1),[a,l]=h.useState(null),[d,u]=h.useState(!1),[f,p]=h.useState(null),[g,v]=h.useState(!1),[y,x]=h.useState(""),[b,w]=h.useState(null),C=h.useCallback(async()=>{o(!0),l(null);try{const t=await function(e){return rs("GET",`/api/projects/${e}/track-flows`)}(e);r(t.files)}catch(ll){l(ll.message)}finally{o(!1)}},[e]);h.useEffect(()=>{C()},[C]),h.useEffect(()=>{const e=()=>{C()};return window.addEventListener("ccweb:track-editor-closed",e),()=>window.removeEventListener("ccweb:track-editor-closed",e)},[C]),h.useEffect(()=>{let t=null,i=null;const s=()=>{i&&(clearTimeout(i),i=null)},r=r=>{const n=r.detail;if((null==n?void 0:n.type)&&(!n.type.startsWith("flow_")||n.runId)){if("flow_started"===n.type&&n.basename&&n.runId){s(),t=n.runId;const i=n.runId,r=n.basename;return p({flow:null,runId:i,basename:r,currentNodeId:null,nodeStates:new Map,status:"running"}),void(async()=>{try{const[s,n]=await Promise.all([ns(e,`${r}.flow`),ls(e,i)]);if(t!==i)return;const o=ds(s.flow);if(!o.ok||!o.flow)return;p(e=>{if(!e||e.runId!==i)return e;const t=new Map(Object.entries(n.nodeStates));for(const[i,s]of e.nodeStates)t.set(i,s);return{...e,flow:o.flow,currentNodeId:e.currentNodeId??n.currentNodeId,nodeStates:t}})}catch{}})()}if(p(e=>{if(!e)return e;if(n.runId!==e.runId)return e;if("flow_node_active"===n.type&&n.nodeId){const t=new Map(e.nodeStates);return t.set(n.nodeId,"active"),{...e,nodeStates:t,currentNodeId:n.nodeId,status:"running"}}if("flow_node_completed"===n.type&&n.nodeId){const t=new Map(e.nodeStates);return t.set(n.nodeId,"completed"),{...e,nodeStates:t}}if("flow_node_failed"===n.type&&n.nodeId){const t=new Map(e.nodeStates);return t.set(n.nodeId,"failed"),{...e,nodeStates:t,status:"failed",currentNodeId:null}}return"flow_user_input_required"===n.type?{...e,status:"waiting_user_input"}:"flow_done"===n.type?{...e,status:"completed",currentNodeId:null}:"flow_cancelled"===n.type?{...e,status:"cancelled",currentNodeId:null}:e}),"flow_done"===n.type||"flow_cancelled"===n.type||"flow_error"===n.type||"flow_node_failed"===n.type){const e=n.runId;s(),i=setTimeout(()=>{p(t=>t&&t.runId===e?null:t),i=null},3e3)}}};return window.addEventListener("ccweb:flow-msg",r),()=>{window.removeEventListener("ccweb:flow-msg",r),s()}},[e]);const k=async()=>{var i;const r=y.trim();if(r)if(gs.test(r))if(s.some(e=>e.filename===`${r}.flow`))w(`工作轨 "${r}" 已存在,请用不同名字`);else{u(!0),w(null);try{const i=hs(r),s=us(i.variables);await os(e,`${r}.flow`,i,s,{createOnly:!0}),await C(),v(!1),x(""),t(`${r}.flow`)}catch(ll){const t=ll;"FLOW_FILE_EXISTS"===(null==(i=t.detail)?void 0:i.code)?w(`工作轨 "${r}" 已存在(backend 二道闸拦截)`):w(t.message)}finally{u(!1)}}else w("名字只允许字母/数字/下划线/中文/连字符");else w("工作轨名不能为空")},E=async(t,s)=>{var r;s.stopPropagation();if(await i({description:`删除 ${t}?`,confirmLabel:"删除",destructive:!0}))try{await function(e,t){return rs("DELETE",`/api/projects/${e}/track-flows/file/${encodeURIComponent(t)}`)}(e,t),await C()}catch(n){const e=n;"FLOW_RUN_ACTIVE"===(null==(r=e.detail)?void 0:r.code)?m.error(`${t} 正在运行,请先取消运行再删除`):m.error(e.message)}};return f&&f.flow?_.jsxs("div",{className:"h-full flex flex-col p-2 gap-2 overflow-y-auto bg-background",children:[_.jsxs("div",{className:"text-xs text-muted-foreground px-1 flex items-center gap-1",children:[_.jsx(Di,{className:"h-3 w-3"}),"运行中"]}),_.jsx(ps,{flow:f.flow,nodeStates:f.nodeStates,currentNodeId:f.currentNodeId,status:f.status,embedded:!0}),_.jsx(K,{type:"button",variant:"link",size:"sm",onClick:()=>t(`${f.basename}.flow`),className:"h-7 justify-start px-1 text-xs",children:"打开编辑页查看详情 →"})]}):_.jsxs("div",{className:"h-full flex flex-col overflow-hidden bg-background",children:[_.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5 border-b border-border",children:[_.jsx(Di,{className:"h-3.5 w-3.5 text-muted-foreground"}),_.jsx("div",{className:"text-xs font-medium flex-1 text-foreground",children:"工作轨"}),_.jsx(K,{type:"button",size:"sm",onClick:()=>{x(""),w(null),v(!0)},disabled:d,className:"h-6 px-2 text-xs",children:d?_.jsx(ie,{className:"h-3 w-3 animate-spin"}):_.jsxs(_.Fragment,{children:[_.jsx(V,{className:"h-3 w-3 mr-0.5"}),"新建"]})})]}),_.jsxs("div",{className:"flex-1 overflow-y-auto p-1",children:[n&&_.jsx("div",{className:"text-xs text-muted-foreground p-2",children:"加载中…"}),a&&_.jsxs("div",{className:"text-xs text-destructive p-2",children:["错误:",a]}),!n&&!a&&0===s.length&&_.jsx("div",{className:"text-xs text-muted-foreground p-2 text-center",children:"暂无工作轨。"}),s.map(e=>_.jsxs("div",{className:"flex items-center gap-1 px-1.5 py-1 rounded-md hover:bg-accent cursor-pointer text-xs group",onClick:()=>t(e.filename),title:`${(e.size/1024).toFixed(1)} KB · ${new Date(e.mtimeMs).toLocaleString()}`,children:[_.jsx(Ri,{className:"h-3 w-3 text-muted-foreground shrink-0"}),_.jsx("span",{className:"flex-1 font-mono truncate text-foreground",children:e.filename.replace(/\.flow$/,"")}),_.jsx(K,{type:"button",size:"icon",onClick:t=>{t.stopPropagation(),window.dispatchEvent(new CustomEvent("ccweb:flow-run-request",{detail:{filename:e.filename}}))},title:"直接运行(不打开编辑器)",className:"h-5 w-5 bg-emerald-600 text-white hover:bg-emerald-700 dark:bg-emerald-600 dark:hover:bg-emerald-500",children:_.jsx(ki,{className:"h-2.5 w-2.5 fill-current"})}),_.jsx(K,{type:"button",variant:"ghost",size:"icon",onClick:t=>{E(e.filename,t)},title:"删除",className:"h-5 w-5 text-muted-foreground hover:text-destructive",children:_.jsx(S,{className:"h-3 w-3"})})]},e.filename))]}),_.jsx(se,{open:g,onOpenChange:e=>{e||v(!1)},children:_.jsxs(re,{className:"max-w-sm",children:[_.jsxs(ne,{children:[_.jsx(oe,{children:"新建工作轨"}),_.jsx(ae,{children:"工作轨文件名(不含 .flow 后缀),只允许字母/数字/下划线/中文/连字符。"})]}),_.jsxs("div",{className:"space-y-2",children:[_.jsx(le,{htmlFor:"new-flow-name",className:"text-xs text-muted-foreground",children:"文件名"}),_.jsx(q,{id:"new-flow-name",autoFocus:!0,value:y,onChange:e=>{x(e.target.value),w(null)},onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),k())},placeholder:"例:search-and-summarize",className:"font-mono"}),b&&_.jsx("div",{className:"text-xs text-destructive",children:b})]}),_.jsxs(ce,{children:[_.jsx(K,{variant:"outline",size:"sm",onClick:()=>v(!1),disabled:d,children:"取消"}),_.jsx(K,{size:"sm",onClick:()=>{k()},disabled:d,children:d?"创建中…":"创建"})]})]})})]})}function ys({projectPath:e,projectId:t,cliTool:i,onOpenTrackEditor:s}){const[r,n]=he(E.leftPanelTab,"files"),o="claude"===i,a="terminal"!==i,l="terminal"!==i;let c;return c="git"===r?"git":"tracks"===r&&l?"tracks":"scheduled"===r&&o?"scheduled":"backup"===r&&a?"backup":"files",_.jsxs(At,{value:c,onValueChange:e=>n(e),orientation:"vertical",className:"h-full flex bg-muted text-foreground overflow-hidden",children:[_.jsxs(zt,{className:g("flex flex-col items-center justify-start shrink-0","h-full w-9 border-r border-border rounded-none p-1 gap-1"),children:[_.jsx($t,{value:"files",title:"Files","aria-label":"Files",className:g("h-7 w-7 p-0 rounded-md flex items-center justify-center"),children:_.jsx(T,{className:"h-3.5 w-3.5"})}),_.jsx($t,{value:"git",title:"Git","aria-label":"Git",className:g("h-7 w-7 p-0 rounded-md flex items-center justify-center"),children:_.jsx(_i,{className:"h-3.5 w-3.5"})}),l&&_.jsx($t,{value:"tracks",title:"工作轨","aria-label":"Tracks",className:g("h-7 w-7 p-0 rounded-md flex items-center justify-center"),children:_.jsx(Di,{className:"h-3.5 w-3.5"})}),o&&_.jsx($t,{value:"scheduled",title:"已排程任务","aria-label":"Scheduled tasks",className:g("h-7 w-7 p-0 rounded-md flex items-center justify-center"),children:_.jsx(Lt,{className:"h-3.5 w-3.5"})}),a&&_.jsx($t,{value:"backup",title:"聊天记录备份","aria-label":"Sessions backup",className:g("h-7 w-7 p-0 rounded-md flex items-center justify-center"),children:_.jsx(te,{className:"h-3.5 w-3.5"})})]}),_.jsxs("div",{className:"flex-1 min-w-0 flex flex-col border-l border-border",children:[_.jsx(Ht,{value:"files",className:"flex-1 min-h-0 mt-0 data-[state=inactive]:hidden",children:_.jsx(Yi,{projectPath:e,projectId:t})}),_.jsx(Ht,{value:"git",className:"flex-1 min-h-0 mt-0 data-[state=inactive]:hidden",children:_.jsx(Gi,{projectId:t})}),l&&_.jsx(Ht,{value:"tracks",className:"flex-1 min-h-0 mt-0 data-[state=inactive]:hidden",children:_.jsx(vs,{projectId:t,onOpenEditor:e=>null==s?void 0:s(e)})}),o&&_.jsx(Ht,{value:"scheduled",className:"flex-1 min-h-0 mt-0 data-[state=inactive]:hidden",children:_.jsx(Qi,{projectId:t})}),a&&_.jsx(Ht,{value:"backup",className:"flex-1 min-h-0 mt-0 data-[state=inactive]:hidden",children:_.jsx(ss,{projectId:t})})]})]})}function xs(e){const t=bs(e),i=h.forwardRef((e,i)=>{const{children:s,...r}=e,n=h.Children.toArray(s),o=n.find(Ss);if(o){const e=o.props.children,s=n.map(t=>t===o?h.Children.count(e)>1?h.Children.only(null):h.isValidElement(e)?e.props.children:null:t);return _.jsx(t,{...r,ref:i,children:h.isValidElement(e)?h.cloneElement(e,void 0,s):null})}return _.jsx(t,{...r,ref:i,children:s})});return i.displayName=`${e}.Slot`,i}function bs(e){const t=h.forwardRef((e,t)=>{const{children:i,...s}=e;if(h.isValidElement(i)){const e=function(e){var t,i;let s=null==(t=Object.getOwnPropertyDescriptor(e.props,"ref"))?void 0:t.get,r=s&&"isReactWarning"in s&&s.isReactWarning;if(r)return e.ref;if(s=null==(i=Object.getOwnPropertyDescriptor(e,"ref"))?void 0:i.get,r=s&&"isReactWarning"in s&&s.isReactWarning,r)return e.props.ref;return e.props.ref||e.ref}(i),r=function(e,t){const i={...t};for(const s in t){const r=e[s],n=t[s];/^on[A-Z]/.test(s)?r&&n?i[s]=(...e)=>{const t=n(...e);return r(...e),t}:r&&(i[s]=r):"style"===s?i[s]={...r,...n}:"className"===s&&(i[s]=[r,n].filter(Boolean).join(" "))}return{...e,...i}}(s,i.props);return i.type!==h.Fragment&&(r.ref=t?de(t,e):e),h.cloneElement(i,r)}return h.Children.count(i)>1?h.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var ws=Symbol("radix.slottable");function Ss(e){return h.isValidElement(e)&&"function"==typeof e.type&&"__radixId"in e.type&&e.type.__radixId===ws}var Cs=["Enter"," "],ks=["ArrowUp","PageDown","End"],Es=["ArrowDown","PageUp","Home",...ks],Ns={ltr:[...Cs,"ArrowRight"],rtl:[...Cs,"ArrowLeft"]},Ms={ltr:["ArrowLeft"],rtl:["ArrowRight"]},js="Menu",[Ds,Rs,Ps]=Vt(js),[Ls,Is]=fe(js,[Ps,Kt,Ut]),Ts=Kt(),Bs=Ut(),[Os,As]=Ls(js),[zs,$s]=Ls(js),Hs=e=>{const{__scopeMenu:t,open:i=!1,children:s,dir:r,onOpenChange:n,modal:o=!0}=e,a=Ts(t),[l,c]=h.useState(null),d=h.useRef(!1),u=ue(n),f=si(r);return h.useEffect(()=>{const e=()=>{d.current=!0,document.addEventListener("pointerdown",t,{capture:!0,once:!0}),document.addEventListener("pointermove",t,{capture:!0,once:!0})},t=()=>d.current=!1;return document.addEventListener("keydown",e,{capture:!0}),()=>{document.removeEventListener("keydown",e,{capture:!0}),document.removeEventListener("pointerdown",t,{capture:!0}),document.removeEventListener("pointermove",t,{capture:!0})}},[]),_.jsx(Wt,{...a,children:_.jsx(Os,{scope:t,open:i,onOpenChange:u,content:l,onContentChange:c,children:_.jsx(zs,{scope:t,onClose:h.useCallback(()=>u(!1),[u]),isUsingKeyboardRef:d,dir:f,modal:o,children:s})})})};Hs.displayName=js;var Ws=h.forwardRef((e,t)=>{const{__scopeMenu:i,...s}=e,r=Ts(i);return _.jsx(Ft,{...r,...s,ref:t})});Ws.displayName="MenuAnchor";var Fs="MenuPortal",[Ks,Us]=Ls(Fs,{forceMount:void 0}),Vs=e=>{const{__scopeMenu:t,forceMount:i,children:s,container:r}=e,n=As(Fs,t);return _.jsx(Ks,{scope:t,forceMount:i,children:_.jsx(pe,{present:i||n.open,children:_.jsx(me,{asChild:!0,container:r,children:s})})})};Vs.displayName=Fs;var qs="MenuContent",[Ys,Xs]=Ls(qs),Gs=h.forwardRef((e,t)=>{const i=Us(qs,e.__scopeMenu),{forceMount:s=i.forceMount,...r}=e,n=As(qs,e.__scopeMenu),o=$s(qs,e.__scopeMenu);return _.jsx(Ds.Provider,{scope:e.__scopeMenu,children:_.jsx(pe,{present:s||n.open,children:_.jsx(Ds.Slot,{scope:e.__scopeMenu,children:o.modal?_.jsx(Zs,{...r,ref:t}):_.jsx(Js,{...r,ref:t})})})})}),Zs=h.forwardRef((e,t)=>{const i=As(qs,e.__scopeMenu),s=h.useRef(null),r=_e(t,s);return h.useEffect(()=>{const e=s.current;if(e)return ye(e)},[]),_.jsx(er,{...e,ref:r,trapFocus:i.open,disableOutsidePointerEvents:i.open,disableOutsideScroll:!0,onFocusOutside:ge(e.onFocusOutside,e=>e.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>i.onOpenChange(!1)})}),Js=h.forwardRef((e,t)=>{const i=As(qs,e.__scopeMenu);return _.jsx(er,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>i.onOpenChange(!1)})}),Qs=xs("MenuContent.ScrollLock"),er=h.forwardRef((e,t)=>{const{__scopeMenu:i,loop:s=!1,trapFocus:r,onOpenAutoFocus:n,onCloseAutoFocus:o,disableOutsidePointerEvents:a,onEntryFocus:l,onEscapeKeyDown:c,onPointerDownOutside:d,onFocusOutside:u,onInteractOutside:f,onDismiss:p,disableOutsideScroll:m,...g}=e,v=As(qs,i),y=$s(qs,i),x=Ts(i),b=Bs(i),w=Rs(i),[S,C]=h.useState(null),k=h.useRef(null),E=_e(t,k,v.onContentChange),N=h.useRef(0),M=h.useRef(""),j=h.useRef(0),D=h.useRef(null),R=h.useRef("right"),P=h.useRef(0),L=m?we:h.Fragment,I=m?{as:Qs,allowPinchZoom:!0}:void 0,T=e=>{var t,i;const s=M.current+e,r=w().filter(e=>!e.disabled),n=document.activeElement,o=null==(t=r.find(e=>e.ref.current===n))?void 0:t.textValue,a=function(e,t,i){const s=t.length>1&&Array.from(t).every(e=>e===t[0]),r=s?t[0]:t,n=i?e.indexOf(i):-1;let o=(a=e,l=Math.max(n,0),a.map((e,t)=>a[(l+t)%a.length]));var a,l;1===r.length&&(o=o.filter(e=>e!==i));const c=o.find(e=>e.toLowerCase().startsWith(r.toLowerCase()));return c!==i?c:void 0}(r.map(e=>e.textValue),s,o),l=null==(i=r.find(e=>e.textValue===a))?void 0:i.ref.current;!function e(t){M.current=t,window.clearTimeout(N.current),""!==t&&(N.current=window.setTimeout(()=>e(""),1e3))}(s),l&&setTimeout(()=>l.focus())};h.useEffect(()=>()=>window.clearTimeout(N.current),[]),be();const B=h.useCallback(e=>{var t,i;return R.current===(null==(t=D.current)?void 0:t.side)&&function(e,t){if(!t)return!1;const i={x:e.clientX,y:e.clientY};return function(e,t){const{x:i,y:s}=e;let r=!1;for(let n=0,o=t.length-1;n<t.length;o=n++){const e=t[n],a=t[o],l=e.x,c=e.y,h=a.x,d=a.y;c>s!=d>s&&i<(h-l)*(s-c)/(d-c)+l&&(r=!r)}return r}(i,t)}(e,null==(i=D.current)?void 0:i.area)},[]);return _.jsx(Ys,{scope:i,searchRef:M,onItemEnter:h.useCallback(e=>{B(e)&&e.preventDefault()},[B]),onItemLeave:h.useCallback(e=>{var t;B(e)||(null==(t=k.current)||t.focus(),C(null))},[B]),onTriggerLeave:h.useCallback(e=>{B(e)&&e.preventDefault()},[B]),pointerGraceTimerRef:j,onPointerGraceIntentChange:h.useCallback(e=>{D.current=e},[]),children:_.jsx(L,{...I,children:_.jsx(Se,{asChild:!0,trapped:r,onMountAutoFocus:ge(n,e=>{var t;e.preventDefault(),null==(t=k.current)||t.focus({preventScroll:!0})}),onUnmountAutoFocus:o,children:_.jsx(Ce,{asChild:!0,disableOutsidePointerEvents:a,onEscapeKeyDown:c,onPointerDownOutside:d,onFocusOutside:u,onInteractOutside:f,onDismiss:p,children:_.jsx(Yt,{asChild:!0,...b,dir:y.dir,orientation:"vertical",loop:s,currentTabStopId:S,onCurrentTabStopIdChange:C,onEntryFocus:ge(l,e=>{y.isUsingKeyboardRef.current||e.preventDefault()}),preventScrollOnEntryFocus:!0,children:_.jsx(Xt,{role:"menu","aria-orientation":"vertical","data-state":Er(v.open),"data-radix-menu-content":"",dir:y.dir,...x,...g,ref:E,style:{outline:"none",...g.style},onKeyDown:ge(g.onKeyDown,e=>{const t=e.target.closest("[data-radix-menu-content]")===e.currentTarget,i=e.ctrlKey||e.altKey||e.metaKey,s=1===e.key.length;t&&("Tab"===e.key&&e.preventDefault(),!i&&s&&T(e.key));const r=k.current;if(e.target!==r)return;if(!Es.includes(e.key))return;e.preventDefault();const n=w().filter(e=>!e.disabled).map(e=>e.ref.current);ks.includes(e.key)&&n.reverse(),function(e){const t=document.activeElement;for(const i of e){if(i===t)return;if(i.focus(),document.activeElement!==t)return}}(n)}),onBlur:ge(e.onBlur,e=>{e.currentTarget.contains(e.target)||(window.clearTimeout(N.current),M.current="")}),onPointerMove:ge(e.onPointerMove,jr(e=>{const t=e.target,i=P.current!==e.clientX;if(e.currentTarget.contains(t)&&i){const t=e.clientX>P.current?"right":"left";R.current=t,P.current=e.clientX}}))})})})})})})});Gs.displayName=qs;var tr=h.forwardRef((e,t)=>{const{__scopeMenu:i,...s}=e;return _.jsx(ve.div,{role:"group",...s,ref:t})});tr.displayName="MenuGroup";var ir=h.forwardRef((e,t)=>{const{__scopeMenu:i,...s}=e;return _.jsx(ve.div,{...s,ref:t})});ir.displayName="MenuLabel";var sr="MenuItem",rr="menu.itemSelect",nr=h.forwardRef((e,t)=>{const{disabled:i=!1,onSelect:s,...r}=e,n=h.useRef(null),o=$s(sr,e.__scopeMenu),a=Xs(sr,e.__scopeMenu),l=_e(t,n),c=h.useRef(!1);return _.jsx(or,{...r,ref:l,disabled:i,onClick:ge(e.onClick,()=>{const e=n.current;if(!i&&e){const t=new CustomEvent(rr,{bubbles:!0,cancelable:!0});e.addEventListener(rr,e=>null==s?void 0:s(e),{once:!0}),xe(e,t),t.defaultPrevented?c.current=!1:o.onClose()}}),onPointerDown:t=>{var i;null==(i=e.onPointerDown)||i.call(e,t),c.current=!0},onPointerUp:ge(e.onPointerUp,e=>{var t;c.current||null==(t=e.currentTarget)||t.click()}),onKeyDown:ge(e.onKeyDown,e=>{const t=""!==a.searchRef.current;i||t&&" "===e.key||Cs.includes(e.key)&&(e.currentTarget.click(),e.preventDefault())})})});nr.displayName=sr;var or=h.forwardRef((e,t)=>{const{__scopeMenu:i,disabled:s=!1,textValue:r,...n}=e,o=Xs(sr,i),a=Bs(i),l=h.useRef(null),c=_e(t,l),[d,u]=h.useState(!1),[f,p]=h.useState("");return h.useEffect(()=>{const e=l.current;e&&p((e.textContent??"").trim())},[n.children]),_.jsx(Ds.ItemSlot,{scope:i,disabled:s,textValue:r??f,children:_.jsx(qt,{asChild:!0,...a,focusable:!s,children:_.jsx(ve.div,{role:"menuitem","data-highlighted":d?"":void 0,"aria-disabled":s||void 0,"data-disabled":s?"":void 0,...n,ref:c,onPointerMove:ge(e.onPointerMove,jr(e=>{if(s)o.onItemLeave(e);else if(o.onItemEnter(e),!e.defaultPrevented){e.currentTarget.focus({preventScroll:!0})}})),onPointerLeave:ge(e.onPointerLeave,jr(e=>o.onItemLeave(e))),onFocus:ge(e.onFocus,()=>u(!0)),onBlur:ge(e.onBlur,()=>u(!1))})})})}),ar=h.forwardRef((e,t)=>{const{checked:i=!1,onCheckedChange:s,...r}=e;return _.jsx(mr,{scope:e.__scopeMenu,checked:i,children:_.jsx(nr,{role:"menuitemcheckbox","aria-checked":Nr(i)?"mixed":i,...r,ref:t,"data-state":Mr(i),onSelect:ge(r.onSelect,()=>null==s?void 0:s(!!Nr(i)||!i),{checkForDefaultPrevented:!1})})})});ar.displayName="MenuCheckboxItem";var lr="MenuRadioGroup",[cr,hr]=Ls(lr,{value:void 0,onValueChange:()=>{}}),dr=h.forwardRef((e,t)=>{const{value:i,onValueChange:s,...r}=e,n=ue(s);return _.jsx(cr,{scope:e.__scopeMenu,value:i,onValueChange:n,children:_.jsx(tr,{...r,ref:t})})});dr.displayName=lr;var ur="MenuRadioItem",fr=h.forwardRef((e,t)=>{const{value:i,...s}=e,r=hr(ur,e.__scopeMenu),n=i===r.value;return _.jsx(mr,{scope:e.__scopeMenu,checked:n,children:_.jsx(nr,{role:"menuitemradio","aria-checked":n,...s,ref:t,"data-state":Mr(n),onSelect:ge(s.onSelect,()=>{var e;return null==(e=r.onValueChange)?void 0:e.call(r,i)},{checkForDefaultPrevented:!1})})})});fr.displayName=ur;var pr="MenuItemIndicator",[mr,_r]=Ls(pr,{checked:!1}),gr=h.forwardRef((e,t)=>{const{__scopeMenu:i,forceMount:s,...r}=e,n=_r(pr,i);return _.jsx(pe,{present:s||Nr(n.checked)||!0===n.checked,children:_.jsx(ve.span,{...r,ref:t,"data-state":Mr(n.checked)})})});gr.displayName=pr;var vr=h.forwardRef((e,t)=>{const{__scopeMenu:i,...s}=e;return _.jsx(ve.div,{role:"separator","aria-orientation":"horizontal",...s,ref:t})});vr.displayName="MenuSeparator";var yr=h.forwardRef((e,t)=>{const{__scopeMenu:i,...s}=e,r=Ts(i);return _.jsx(Gt,{...r,...s,ref:t})});yr.displayName="MenuArrow";var[xr,br]=Ls("MenuSub"),wr="MenuSubTrigger",Sr=h.forwardRef((e,t)=>{const i=As(wr,e.__scopeMenu),s=$s(wr,e.__scopeMenu),r=br(wr,e.__scopeMenu),n=Xs(wr,e.__scopeMenu),o=h.useRef(null),{pointerGraceTimerRef:a,onPointerGraceIntentChange:l}=n,c={__scopeMenu:e.__scopeMenu},d=h.useCallback(()=>{o.current&&window.clearTimeout(o.current),o.current=null},[]);return h.useEffect(()=>d,[d]),h.useEffect(()=>{const e=a.current;return()=>{window.clearTimeout(e),l(null)}},[a,l]),_.jsx(Ws,{asChild:!0,...c,children:_.jsx(or,{id:r.triggerId,"aria-haspopup":"menu","aria-expanded":i.open,"aria-controls":r.contentId,"data-state":Er(i.open),...e,ref:de(t,r.onTriggerChange),onClick:t=>{var s;null==(s=e.onClick)||s.call(e,t),e.disabled||t.defaultPrevented||(t.currentTarget.focus(),i.open||i.onOpenChange(!0))},onPointerMove:ge(e.onPointerMove,jr(t=>{n.onItemEnter(t),t.defaultPrevented||e.disabled||i.open||o.current||(n.onPointerGraceIntentChange(null),o.current=window.setTimeout(()=>{i.onOpenChange(!0),d()},100))})),onPointerLeave:ge(e.onPointerLeave,jr(e=>{var t,s;d();const r=null==(t=i.content)?void 0:t.getBoundingClientRect();if(r){const t=null==(s=i.content)?void 0:s.dataset.side,o="right"===t,l=o?-5:5,c=r[o?"left":"right"],h=r[o?"right":"left"];n.onPointerGraceIntentChange({area:[{x:e.clientX+l,y:e.clientY},{x:c,y:r.top},{x:h,y:r.top},{x:h,y:r.bottom},{x:c,y:r.bottom}],side:t}),window.clearTimeout(a.current),a.current=window.setTimeout(()=>n.onPointerGraceIntentChange(null),300)}else{if(n.onTriggerLeave(e),e.defaultPrevented)return;n.onPointerGraceIntentChange(null)}})),onKeyDown:ge(e.onKeyDown,t=>{var r;const o=""!==n.searchRef.current;e.disabled||o&&" "===t.key||Ns[s.dir].includes(t.key)&&(i.onOpenChange(!0),null==(r=i.content)||r.focus(),t.preventDefault())})})})});Sr.displayName=wr;var Cr="MenuSubContent",kr=h.forwardRef((e,t)=>{const i=Us(qs,e.__scopeMenu),{forceMount:s=i.forceMount,...r}=e,n=As(qs,e.__scopeMenu),o=$s(qs,e.__scopeMenu),a=br(Cr,e.__scopeMenu),l=h.useRef(null),c=_e(t,l);return _.jsx(Ds.Provider,{scope:e.__scopeMenu,children:_.jsx(pe,{present:s||n.open,children:_.jsx(Ds.Slot,{scope:e.__scopeMenu,children:_.jsx(er,{id:a.contentId,"aria-labelledby":a.triggerId,...r,ref:c,align:"start",side:"rtl"===o.dir?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:e=>{var t;o.isUsingKeyboardRef.current&&(null==(t=l.current)||t.focus()),e.preventDefault()},onCloseAutoFocus:e=>e.preventDefault(),onFocusOutside:ge(e.onFocusOutside,e=>{e.target!==a.trigger&&n.onOpenChange(!1)}),onEscapeKeyDown:ge(e.onEscapeKeyDown,e=>{o.onClose(),e.preventDefault()}),onKeyDown:ge(e.onKeyDown,e=>{var t;const i=e.currentTarget.contains(e.target),s=Ms[o.dir].includes(e.key);i&&s&&(n.onOpenChange(!1),null==(t=a.trigger)||t.focus(),e.preventDefault())})})})})})});function Er(e){return e?"open":"closed"}function Nr(e){return"indeterminate"===e}function Mr(e){return Nr(e)?"indeterminate":e?"checked":"unchecked"}function jr(e){return t=>"mouse"===t.pointerType?e(t):void 0}kr.displayName=Cr;var Dr=Hs,Rr=Ws,Pr=Vs,Lr=Gs,Ir=tr,Tr=ir,Br=nr,Or=ar,Ar=dr,zr=fr,$r=gr,Hr=vr,Wr=yr,Fr=Sr,Kr=kr,Ur="ContextMenu",[Vr]=fe(Ur,[Is]),qr=Is(),[Yr,Xr]=Vr(Ur),Gr=e=>{const{__scopeContextMenu:t,children:i,onOpenChange:s,dir:r,modal:n=!0}=e,[o,a]=h.useState(!1),l=qr(t),c=ue(s),d=h.useCallback(e=>{a(e),c(e)},[c]);return _.jsx(Yr,{scope:t,open:o,onOpenChange:d,modal:n,children:_.jsx(Dr,{...l,dir:r,open:o,onOpenChange:d,modal:n,children:i})})};Gr.displayName=Ur;var Zr="ContextMenuTrigger",Jr=h.forwardRef((e,t)=>{const{__scopeContextMenu:i,disabled:s=!1,...r}=e,n=Xr(Zr,i),o=qr(i),a=h.useRef({x:0,y:0}),l=h.useRef({getBoundingClientRect:()=>DOMRect.fromRect({width:0,height:0,...a.current})}),c=h.useRef(0),d=h.useCallback(()=>window.clearTimeout(c.current),[]),u=e=>{a.current={x:e.clientX,y:e.clientY},n.onOpenChange(!0)};return h.useEffect(()=>d,[d]),h.useEffect(()=>{s&&d()},[s,d]),_.jsxs(_.Fragment,{children:[_.jsx(Rr,{...o,virtualRef:l}),_.jsx(ve.span,{"data-state":n.open?"open":"closed","data-disabled":s?"":void 0,...r,ref:t,style:{WebkitTouchCallout:"none",...e.style},onContextMenu:s?e.onContextMenu:ge(e.onContextMenu,e=>{d(),u(e),e.preventDefault()}),onPointerDown:s?e.onPointerDown:ge(e.onPointerDown,nn(e=>{d(),c.current=window.setTimeout(()=>u(e),700)})),onPointerMove:s?e.onPointerMove:ge(e.onPointerMove,nn(d)),onPointerCancel:s?e.onPointerCancel:ge(e.onPointerCancel,nn(d)),onPointerUp:s?e.onPointerUp:ge(e.onPointerUp,nn(d))})]})});Jr.displayName=Zr;var Qr=e=>{const{__scopeContextMenu:t,...i}=e,s=qr(t);return _.jsx(Pr,{...s,...i})};Qr.displayName="ContextMenuPortal";var en="ContextMenuContent",tn=h.forwardRef((e,t)=>{const{__scopeContextMenu:i,...s}=e,r=Xr(en,i),n=qr(i),o=h.useRef(!1);return _.jsx(Lr,{...n,...s,ref:t,side:"right",sideOffset:2,align:"start",onCloseAutoFocus:t=>{var i;null==(i=e.onCloseAutoFocus)||i.call(e,t),!t.defaultPrevented&&o.current&&t.preventDefault(),o.current=!1},onInteractOutside:t=>{var i;null==(i=e.onInteractOutside)||i.call(e,t),t.defaultPrevented||r.modal||(o.current=!0)},style:{...e.style,"--radix-context-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-context-menu-content-available-width":"var(--radix-popper-available-width)","--radix-context-menu-content-available-height":"var(--radix-popper-available-height)","--radix-context-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-context-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});tn.displayName=en;h.forwardRef((e,t)=>{const{__scopeContextMenu:i,...s}=e,r=qr(i);return _.jsx(Ir,{...r,...s,ref:t})}).displayName="ContextMenuGroup";h.forwardRef((e,t)=>{const{__scopeContextMenu:i,...s}=e,r=qr(i);return _.jsx(Tr,{...r,...s,ref:t})}).displayName="ContextMenuLabel";var sn=h.forwardRef((e,t)=>{const{__scopeContextMenu:i,...s}=e,r=qr(i);return _.jsx(Br,{...r,...s,ref:t})});sn.displayName="ContextMenuItem";h.forwardRef((e,t)=>{const{__scopeContextMenu:i,...s}=e,r=qr(i);return _.jsx(Or,{...r,...s,ref:t})}).displayName="ContextMenuCheckboxItem";h.forwardRef((e,t)=>{const{__scopeContextMenu:i,...s}=e,r=qr(i);return _.jsx(Ar,{...r,...s,ref:t})}).displayName="ContextMenuRadioGroup";h.forwardRef((e,t)=>{const{__scopeContextMenu:i,...s}=e,r=qr(i);return _.jsx(zr,{...r,...s,ref:t})}).displayName="ContextMenuRadioItem";h.forwardRef((e,t)=>{const{__scopeContextMenu:i,...s}=e,r=qr(i);return _.jsx($r,{...r,...s,ref:t})}).displayName="ContextMenuItemIndicator";var rn=h.forwardRef((e,t)=>{const{__scopeContextMenu:i,...s}=e,r=qr(i);return _.jsx(Hr,{...r,...s,ref:t})});rn.displayName="ContextMenuSeparator";h.forwardRef((e,t)=>{const{__scopeContextMenu:i,...s}=e,r=qr(i);return _.jsx(Wr,{...r,...s,ref:t})}).displayName="ContextMenuArrow";h.forwardRef((e,t)=>{const{__scopeContextMenu:i,...s}=e,r=qr(i);return _.jsx(Fr,{...r,...s,ref:t})}).displayName="ContextMenuSubTrigger";function nn(e){return t=>"mouse"!==t.pointerType?e(t):void 0}h.forwardRef((e,t)=>{const{__scopeContextMenu:i,...s}=e,r=qr(i);return _.jsx(Kr,{...r,...s,ref:t,style:{...e.style,"--radix-context-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-context-menu-content-available-width":"var(--radix-popper-available-width)","--radix-context-menu-content-available-height":"var(--radix-popper-available-height)","--radix-context-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-context-menu-trigger-height":"var(--radix-popper-anchor-height)"}})}).displayName="ContextMenuSubContent";var on=Qr,an=tn,ln=sn,cn=rn;const hn=Gr,dn=Jr,un=h.forwardRef(({className:e,...t},i)=>_.jsx(on,{children:_.jsx(an,{ref:i,className:g("z-50 min-w-[10rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md","data-[state=open]:animate-in data-[state=closed]:animate-out","data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0","data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95",e),...t})}));un.displayName=an.displayName;const fn=h.forwardRef(({className:e,destructive:t,...i},s)=>_.jsx(ln,{ref:s,className:g("relative flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none","focus:bg-accent focus:text-accent-foreground","data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"text-red-500 focus:text-red-500 focus:bg-red-500/10",e),...i}));fn.displayName=ln.displayName;const pn=h.forwardRef(({className:e,...t},i)=>_.jsx(cn,{ref:i,className:g("-mx-1 my-1 h-px bg-border",e),...t}));function mn({kind:e,label:t,preview:i,inserted:s,unclicked:r,onLeftClick:n,onEdit:o,onDelete:a,onShare:l,onRefresh:c,footer:d,readOnly:u,noContextMenu:f,cornerHint:p,instructionsFile:m="CLAUDE.md"}){const v=h.useRef(null),x=g("agent-prompt"===e?s?"border-green-500/50 bg-green-500/10 hover:bg-green-500/15":"border-dashed border-border hover:border-border/80 hover:bg-muted-foreground/10 dark:hover:bg-muted-foreground/20":r?"border-blue-500/30 bg-blue-500/15 hover:bg-blue-500/20 dark:bg-blue-500/15 dark:hover:bg-blue-500/25":"border-transparent bg-background dark:bg-muted-foreground/10 hover:bg-muted-foreground/10 dark:hover:bg-muted-foreground/20 hover:border-muted-foreground/30"),b="agent-prompt"===e,w=!f||c?" · 右键更多":"",S="quick-prompt"===e?`点击发送${w}`:(s?`点击从 ${m} 移除`:`点击插入 ${m}`)+w,C=_.jsxs("div",{ref:v,className:g("group relative rounded-md border text-xs transition-colors cursor-pointer select-none",x),onClick:n,title:S,children:[b&&_.jsx("span",{"aria-hidden":!0,className:g("absolute top-1.5 left-1.5 h-2 w-2 rounded-full transition-colors",s?"bg-green-500 ring-1 ring-green-500/40":"border border-muted-foreground/40 bg-transparent")}),_.jsxs("div",{className:g("py-1.5",f&&p?"pr-10":f?"pr-2":"pr-7",b?"pl-5":"pl-3"),children:[_.jsx("div",{className:"font-medium truncate",children:t}),i&&i!==t&&_.jsx("div",{className:"mt-0.5 text-muted-foreground/80 truncate font-mono",children:i}),d]}),f&&p&&_.jsx("span",{"aria-hidden":!0,className:"absolute top-1.5 right-2 text-[10px] leading-none font-mono tabular-nums text-muted-foreground/60 pointer-events-none",children:p}),!f&&_.jsx("button",{onClick:e=>{e.stopPropagation(),e.preventDefault();const t=v.current;if(!t)return;const i=t.getBoundingClientRect(),s=new MouseEvent("contextmenu",{bubbles:!0,cancelable:!0,clientX:i.right-8,clientY:i.top+i.height/2,button:2});t.dispatchEvent(s)},className:g("absolute top-1 right-1 p-0.5 rounded transition-opacity","md:opacity-0 md:group-hover:opacity-100 md:focus-visible:opacity-100","hover:bg-muted-foreground/10 focus-visible:bg-muted-foreground/10","text-muted-foreground hover:text-foreground"),title:"更多","aria-label":"更多操作",children:_.jsx(bi,{className:"h-3.5 w-3.5"})})]});return!(!c&&(f||!o&&!a&&!l))?_.jsxs(hn,{children:[_.jsx(dn,{asChild:!0,children:C}),_.jsxs(un,{children:[c&&_.jsxs(fn,{onSelect:c,children:[_.jsx(I,{className:"h-3.5 w-3.5"}),"更新"]}),!f&&!u&&o&&a&&_.jsxs(_.Fragment,{children:[c&&_.jsx(pn,{}),_.jsxs(fn,{onSelect:o,children:[_.jsx(y,{className:"h-3.5 w-3.5"}),"编辑"]}),_.jsxs(fn,{destructive:!0,onSelect:a,children:[_.jsx(L,{className:"h-3.5 w-3.5"}),"删除"]}),l&&_.jsx(pn,{})]}),!f&&l&&_.jsxs(fn,{onSelect:l,children:[_.jsx(ke,{className:"h-3.5 w-3.5"}),"共享到 ccweb-hub"]})]})]}):_.jsx("div",{onContextMenu:e=>e.preventDefault(),children:C})}function _n({open:e,onOpenChange:t,initialLabel:i,initialCommand:s,title:r,onSave:n}){const[o,a]=h.useState(i),[l,c]=h.useState(s),[d,u]=h.useState(!0);h.useEffect(()=>{e&&u(!0)},[e]),h.useEffect(()=>{e&&(a(i),c(s))},[e,i,s]);const f=()=>{const e=l.trim();e&&(n(o.trim()||e,e),t(!1))};return _.jsx(se,{open:e,onOpenChange:t,modal:!1,children:_.jsxs(re,{noOverlay:!0,className:g("sm:max-w-2xl max-h-[85vh] flex flex-col transition-opacity",!d&&"opacity-50"),onInteractOutside:e=>{e.preventDefault(),u(!1)},onClick:()=>u(!0),children:[_.jsxs(ne,{children:[_.jsx(oe,{children:r}),_.jsx(ae,{children:"左键点击卡片会把此命令发送到 CLI。"})]}),_.jsxs("div",{className:"space-y-4 flex-1 min-h-0 flex flex-col",children:[_.jsxs("div",{className:"space-y-2",children:[_.jsx(le,{htmlFor:"qp-label",children:"标签"}),_.jsx(q,{id:"qp-label",placeholder:"显示名(可选,默认用命令文本)",value:o,onChange:e=>a(e.target.value),className:"text-base",autoFocus:!0})]}),_.jsxs("div",{className:"space-y-2 flex-1 flex flex-col min-h-0",children:[_.jsx(le,{htmlFor:"qp-command",children:"命令"}),_.jsx("textarea",{id:"qp-command",placeholder:"输入要发送的命令...",value:l,onChange:e=>c(e.target.value),className:g("flex-1 min-h-[200px] w-full rounded-md border border-input bg-background px-4 py-3","text-base leading-relaxed font-mono","ring-offset-background placeholder:text-muted-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2","resize-none"),onKeyDown:e=>{"Enter"===e.key&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),f())}})]})]}),_.jsxs(ce,{className:"flex items-center justify-between sm:justify-between",children:[_.jsx("span",{className:"text-xs text-muted-foreground",children:"⌘↩ 保存"}),_.jsxs("div",{className:"flex gap-2",children:[_.jsx(K,{variant:"outline",onClick:()=>t(!1),children:"取消"}),_.jsx(K,{onClick:f,disabled:!l.trim(),children:"保存"})]})]})]})})}function gn({title:e,count:t,onAdd:i,children:s}){return _.jsxs("div",{className:"px-2 py-2",children:[_.jsxs("div",{className:"flex items-center justify-between mb-1.5 px-1",children:[_.jsxs("div",{className:"flex items-center gap-1.5 text-xs font-medium text-muted-foreground",children:[_.jsx("span",{children:e}),_.jsxs("span",{className:"text-muted-foreground/60",children:["(",t,")"]})]}),_.jsx("button",{onClick:i,className:"p-0.5 rounded text-muted-foreground hover:text-foreground hover:bg-muted-foreground/10 transition-colors",title:"新建","aria-label":"新建",children:_.jsx(V,{className:"h-3 w-3"})})]}),s]})}function vn({projectId:e,onSend:t}){const i=c(),[s,r]=h.useState([]),[n,o]=h.useState([]),a=D(),l=a.get(e),[d,u]=h.useState({open:!1}),[f,p]=h.useState(l.shareHubOpen),[m,g]=h.useState(l.shareHubLabel),[v,y]=h.useState(l.shareHubCommand),x=h.useCallback(t=>{r(e=>{const i=e.findIndex(e=>e.id===t);if(i<0||e[i].used)return e;const s=[...e];return s[i]={...s[i],used:!0},s}),Ee(e,t,!0).catch(e=>{console.error("Failed to mark shortcut used:",e)})},[e]);h.useEffect(()=>{Ne(e).then(r).catch(()=>r([]))},[e]),h.useEffect(()=>{Me().then(o).catch(()=>o([]))},[]);const b=h.useCallback(e=>{const t=[],i=new Set;let s=e;const r=[];for(;s&&!i.has(s.id);)i.add(s.id),r.unshift(s),s=s.parentId?n.find(e=>e.id===s.parentId):void 0;for(const n of r)t.push(n.command);return t},[n]),w=h.useCallback(async e=>{const i=b(e);for(const s of i)try{await Promise.resolve(t(s+"\r"))}catch{return}},[b,t]),S=e=>u({open:!0,mode:"create",scope:e}),C=(t,i)=>{g(t),y(i),p(!0),a.setShareHub(e,!0,t,i)};return _.jsxs("div",{className:"h-full flex flex-col text-foreground overflow-hidden",children:[_.jsxs("div",{className:"px-3 pt-2.5 pb-2 border-b border-border/50 shrink-0",children:[_.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Quick Prompts"}),_.jsx("p",{className:"mt-1 text-[11px] text-muted-foreground/70 leading-snug",children:"点击卡片发送命令到 CLI;新建的命令在首次点击前以浅蓝色标识"})]}),_.jsxs("div",{className:"flex-1 overflow-y-auto min-h-0",children:[_.jsx(gn,{title:"项目",count:s.length,onAdd:()=>S("project"),children:0===s.length?_.jsx("div",{className:"px-1 py-3 text-xs text-muted-foreground/60",children:"暂无项目命令"}):_.jsx("div",{className:"space-y-1.5",children:s.map(s=>_.jsx(mn,{kind:"quick-prompt",label:s.label,preview:s.label!==s.command?s.command:"",unclicked:!s.used,onLeftClick:()=>(e=>{t(e.command+"\r"),x(e.id)})(s),onEdit:()=>(e=>u({open:!0,mode:"edit",scope:"project",id:e.id,label:e.label,command:e.command}))(s),onDelete:()=>{(async t=>{if(await i({title:"删除项目快捷 Prompt",description:`确认删除「${t.label}」?此操作不可撤销。`,destructive:!0,confirmLabel:"删除"}))try{await Re(e,t.id),r(e=>e.filter(e=>e.id!==t.id))}catch(s){console.error("Failed to delete shortcut:",s)}})(s)},onShare:()=>C(s.label,s.command)},s.id))})}),_.jsx("div",{className:"h-px bg-border mx-2"}),_.jsx(gn,{title:"全局",count:n.length,onAdd:()=>S("global"),children:0===n.length?_.jsx("div",{className:"px-1 py-3 text-xs text-muted-foreground/60",children:"暂无全局命令"}):_.jsx("div",{className:"space-y-1.5",children:n.map(e=>{var t;const s=e.parentId?null==(t=n.find(t=>t.id===e.parentId))?void 0:t.label:void 0;return _.jsx(mn,{kind:"quick-prompt",label:e.label,preview:s?"":e.label!==e.command?e.command:"",onLeftClick:()=>w(e),onEdit:()=>(e=>u({open:!0,mode:"edit",scope:"global",id:e.id,label:e.label,command:e.command}))(e),onDelete:()=>{(async e=>{const t=n.filter(t=>t.parentId===e.id);if(await i({title:"删除全局快捷 Prompt",description:t.length>0?`「${e.label}」被 ${t.length} 个其他全局命令继承。删除后这些命令的继承会断链。确认删除?`:`确认删除「${e.label}」?此操作不可撤销。`,destructive:!0,confirmLabel:"删除"}))try{await Pe(e.id),o(t=>t.filter(t=>t.id!==e.id))}catch(s){console.error("Failed to delete global shortcut:",s)}})(e)},onShare:()=>C(e.label,e.command),footer:s?_.jsxs("div",{className:"flex items-center gap-1 mt-0.5",children:[_.jsx(je,{className:"h-2.5 w-2.5 text-muted-foreground"}),_.jsxs("span",{className:"text-muted-foreground truncate",children:["继承: ",s,"(继承链仅可在 Dashboard 编辑)"]})]}):null},e.id)})})})]}),_.jsx(_n,{open:d.open,onOpenChange:e=>{e||u({open:!1})},initialLabel:d.open&&"edit"===d.mode?d.label:"",initialCommand:d.open&&"edit"===d.mode?d.command:"",title:d.open?"create"===d.mode?`新建${"global"===d.scope?"全局":"项目"}命令`:"编辑命令":"",onSave:(t,i)=>{(async(t,i)=>{if(d.open)try{if("create"===d.mode)if("global"===d.scope){const e=await Le({label:t,command:i});o(t=>[...t,e])}else{const s=await Ie(e,{label:t,command:i});r(e=>[...e,s])}else if("global"===d.scope){const e=n.find(e=>e.id===d.id),s=await Te(d.id,{label:t,command:i,parentId:(null==e?void 0:e.parentId)??null});o(e=>e.map(e=>e.id===s.id?s:e))}else{const s=await Be(e,d.id,{label:t,command:i});r(e=>e.map(e=>e.id===s.id?s:e))}}catch(s){console.error("Failed to save shortcut:",s)}})(t,i)}}),_.jsx(De,{open:f,onOpenChange:t=>{p(t),t||a.setShareHub(e,!1)},kind:"quick-prompt",label:m,content:v})]})}pn.displayName=cn.displayName;function yn({open:e,onOpenChange:t,title:i,initialLabel:s,initialCommand:r,onSave:n,instructionsFile:o="CLAUDE.md"}){const[a,l]=h.useState(s),[c,d]=h.useState(r),[u,f]=h.useState(!0);h.useEffect(()=>{e&&(l(s),d(r),f(!0))},[e,s,r]);const p=a.trim(),m=c.trim(),v=p.length>100,y=m.length>8e3,x=m.length>0&&p.length>0&&!v&&!y,b=()=>{x&&(n(p,c),t(!1))};return _.jsx(se,{open:e,onOpenChange:t,modal:!1,children:_.jsxs(re,{noOverlay:!0,className:g("sm:max-w-2xl max-h-[85vh] flex flex-col transition-opacity",!u&&"opacity-50"),onInteractOutside:e=>{e.preventDefault(),f(!1)},onClick:()=>f(!0),children:[_.jsxs(ne,{children:[_.jsx(oe,{children:i}),_.jsxs(ae,{children:["This prompt can be clicked once in the sidebar to insert into ",o,", and clicked again to remove (by exact text match)."]})]}),_.jsxs("div",{className:"space-y-4 flex-1 min-h-0 flex flex-col",children:[_.jsxs("div",{className:"space-y-2",children:[_.jsxs("div",{className:"flex items-center justify-between",children:[_.jsx(le,{htmlFor:"prompt-label",children:"Label"}),_.jsxs("span",{className:g("text-xs text-muted-foreground",v&&"text-red-500"),children:[p.length," / ",100]})]}),_.jsx(q,{id:"prompt-label",placeholder:"A short name for this prompt",value:a,onChange:e=>l(e.target.value),className:"text-base",autoFocus:!0})]}),_.jsxs("div",{className:"space-y-2 flex-1 flex flex-col min-h-0",children:[_.jsxs("div",{className:"flex items-center justify-between",children:[_.jsx(le,{htmlFor:"prompt-command",children:"Prompt"}),_.jsxs("span",{className:g("text-xs text-muted-foreground",y&&"text-red-500"),children:[m.length," / ",8e3]})]}),_.jsx("textarea",{id:"prompt-command",placeholder:`The exact text that will be appended to ${o}...`,value:c,onChange:e=>d(e.target.value),className:g("flex-1 min-h-[200px] w-full rounded-md border border-input bg-background px-4 py-3","text-sm leading-relaxed font-mono","ring-offset-background placeholder:text-muted-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2","resize-none"),onKeyDown:e=>{"Enter"===e.key&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),b())}})]})]}),_.jsxs(ce,{className:"flex items-center justify-between sm:justify-between",children:[_.jsx("span",{className:"text-xs text-muted-foreground",children:"⌘↩ to save"}),_.jsxs("div",{className:"flex gap-2",children:[_.jsx(K,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),_.jsx(K,{onClick:b,disabled:!x,children:"Save"})]})]})]})})}function xn({projectId:e}){const t=c(),[i,s]=h.useState([]),[r,n]=h.useState([]),[o,a]=h.useState("CLAUDE.md"),[l,d]=h.useState(!0),[u,f]=h.useState({open:!1}),[p,g]=h.useState({open:!1,label:"",content:""}),v=h.useCallback(async()=>{try{const t=await Oe(e);s(t.global),n(t.project),t.instructionsFilename&&a(t.instructionsFilename)}catch(t){m.error(`加载提示词失败: ${t.message}`)}finally{d(!1)}},[e]);h.useEffect(()=>{d(!0),v()},[v]);const y=h.useRef(new Set),x=h.useCallback(async(t,i)=>{if(y.current.has(i.id))return;y.current.add(i.id);const r=i.inserted?"remove":"insert",a=e=>e.map(e=>e.id===i.id?{...e,inserted:!e.inserted}:e);"global"===t?s(a):n(a);try{const t=await Ae(e,i.command,r);if("remove"===r&&!1===t.changed)return"not-found"===t.reason?m.error(`${o} 中找不到该提示词的精确文本,请自行编辑 ${o} 移除。`):m.warning(`该提示词当前不在 ${o} 中(可能被手动编辑过),已重新同步状态。`),void v();v()}catch(l){m.error(`操作失败: ${l.message}`),"global"===t?s(a):n(a)}finally{y.current.delete(i.id)}},[e,v,o]),b=h.useCallback(async(t,i,s,r,n)=>{try{if("create"===t)"global"===i?await ze({label:r,command:n}):await $e(e,{label:r,command:n}),m.success("已添加");else{if(!s)return;"global"===i?await He(s,{label:r,command:n}):await We(e,s,{label:r,command:n}),m.success("已更新")}v()}catch(o){m.error(`保存失败: ${o.message}`)}},[e,v]),w=h.useCallback(async(i,s)=>{const r=s.inserted?`此提示词目前已插入当前项目的 ${o}。\n\n删除后它会在 ${o} 中成为"孤儿文本"——仅删除提示词记录,不会自动从 ${o} 移除。\n\n确认删除?`:"确认删除此提示词?此操作不可撤销。";if(await t({title:"删除提示词",description:r,destructive:!0,confirmLabel:"删除"}))try{"global"===i?await Fe(s.id):await Ke(e,s.id),m.success("已删除"),v()}catch(n){m.error(`删除失败: ${n.message}`)}},[e,v,t,o]),S=h.useCallback(e=>{g({open:!0,label:e.label,content:e.command})},[]);return _.jsxs("div",{className:"flex flex-col h-full overflow-y-auto",children:[_.jsxs("div",{className:"px-3 pt-2.5 pb-2 border-b border-border/50 shrink-0",children:[_.jsx("span",{className:"text-xs font-medium uppercase tracking-wider text-muted-foreground",children:"Agent Prompts"}),_.jsxs("p",{className:"mt-1 text-[11px] text-muted-foreground/70 leading-snug",children:["点击卡片插入 / 移出当前项目的 ",o,";左上角绿点表示已插入"]})]}),_.jsx(bn,{title:"项目",count:r.length,loading:l,prompts:r,emptyText:"暂无项目提示词",instructionsFile:o,onAdd:()=>f({open:!0,mode:"create",scope:"project"}),onToggle:e=>{x("project",e)},onEdit:e=>f({open:!0,mode:"edit",scope:"project",id:e.id,label:e.label,command:e.command}),onDelete:e=>{w("project",e)},onShare:S}),_.jsx("div",{className:"h-px bg-border mx-2"}),_.jsx(bn,{title:"全局",count:i.length,loading:l,prompts:i,emptyText:"暂无全局提示词",instructionsFile:o,onAdd:()=>f({open:!0,mode:"create",scope:"global"}),onToggle:e=>{x("global",e)},onEdit:e=>f({open:!0,mode:"edit",scope:"global",id:e.id,label:e.label,command:e.command}),onDelete:e=>{w("global",e)},onShare:S}),_.jsx(yn,{open:u.open,onOpenChange:e=>{e||f({open:!1})},title:!1===u.open?"":"create"===u.mode?`新建${"global"===u.scope?"全局":"项目"}提示词`:`编辑${"global"===u.scope?"全局":"项目"}提示词`,initialLabel:u.open&&"edit"===u.mode?u.label:"",initialCommand:u.open&&"edit"===u.mode?u.command:"",instructionsFile:o,onSave:(e,t)=>{if(!u.open)return;const i="edit"===u.mode?u.id:null;b(u.mode,u.scope,i,e,t)}}),_.jsx(De,{open:p.open,onOpenChange:e=>g(t=>({...t,open:e})),kind:"agent-prompt",label:p.label,content:p.content})]})}function bn({title:e,count:t,loading:i,prompts:s,emptyText:r,onAdd:n,onToggle:o,onEdit:a,onDelete:l,onShare:c,instructionsFile:h}){return _.jsxs("div",{className:"px-2 py-2",children:[_.jsxs("div",{className:"flex items-center justify-between mb-1.5 px-1",children:[_.jsxs("div",{className:"flex items-center gap-1.5 text-xs font-medium text-muted-foreground uppercase tracking-wider",children:[_.jsx("span",{children:e}),_.jsxs("span",{className:"text-muted-foreground/60 normal-case tracking-normal",children:["(",t,")"]})]}),_.jsx("button",{onClick:n,className:"p-0.5 rounded text-muted-foreground hover:text-foreground hover:bg-muted-foreground/10 transition-colors",title:"新建","aria-label":"新建",children:_.jsx(V,{className:"h-3 w-3"})})]}),i?_.jsx("div",{className:"px-1 py-3 text-xs text-muted-foreground/60",children:"加载中…"}):0===s.length?_.jsx("div",{className:"px-1 py-3 text-xs text-muted-foreground/60",children:r}):_.jsx("div",{className:"space-y-1.5",children:s.map(e=>{const t=e.command.split("\n").find(e=>e.trim())??e.command.trim();return _.jsx(mn,{kind:"agent-prompt",label:e.label,preview:t,inserted:e.inserted,instructionsFile:h,onLeftClick:()=>o(e),onEdit:()=>a(e),onDelete:()=>l(e),onShare:()=>c(e)},e.id)})})]})}function wn({projectId:e}){const[t,i]=h.useState([]),[s,r]=h.useState(null),[n,o]=h.useState("CLAUDE.md"),[a,l]=h.useState(!0),[c,d]=h.useState(!1),u=h.useRef(new Set),f=h.useCallback(async()=>{l(!0);try{const t=await Ue(e);i(t.items),r(t.claudeMdLineCount),t.instructionsFilename&&o(t.instructionsFilename)}catch(t){m.error(`加载失败: ${t.message}`)}finally{l(!1)}},[e]);h.useEffect(()=>{f()},[f]);const p=h.useCallback(async t=>{if(u.current.has(t.filename))return;u.current.add(t.filename),i(e=>e.map(e=>e.filename===t.filename?{...e,inserted:!e.inserted}:e));const s=t.inserted?"remove":"insert";try{const n=await Ve(e,t.filename,s);if(!n.ok)return m.error("操作失败"+(n.reason?`(${n.reason})`:"")),void f();i(e=>e.map(e=>e.filename===t.filename?{...e,inserted:n.inserted}:e)),"number"==typeof n.claudeMdLineCount&&r(n.claudeMdLineCount),"insert"===s&&"refreshed"===n.reason&&m.info(`${t.name} 已更新(文件内容有变化)`)}catch(n){m.error(`操作失败: ${n.message}`),i(e=>e.map(e=>e.filename===t.filename?{...e,inserted:t.inserted}:e))}finally{u.current.delete(t.filename)}},[e,f]),v=h.useCallback(async()=>{if(c)return;const s=t.filter(e=>e.inserted);if(0===s.length)return void m.info("没有已插入的 memory 卡片");d(!0);let n=0,o=0;for(const t of s)if(u.current.has(t.filename))o++;else{u.current.add(t.filename);try{const s=await Ve(e,t.filename,"insert");s.ok?(i(e=>e.map(e=>e.filename===t.filename?{...e,inserted:s.inserted}:e)),"number"==typeof s.claudeMdLineCount&&r(s.claudeMdLineCount),n++):o++}catch{o++}finally{u.current.delete(t.filename)}}d(!1),0===o?m.success(`已从磁盘更新 ${n} 个 memory 卡片`):m.error(`${n} 个更新成功,${o} 个失败`)},[e,t,c]),y=h.useCallback(async t=>{if(!u.current.has(t.filename))if(t.inserted){u.current.add(t.filename);try{const s=await Ve(e,t.filename,"insert");if(!s.ok)return m.error("更新失败"+(s.reason?`(${s.reason})`:"")),void f();i(e=>e.map(e=>e.filename===t.filename?{...e,inserted:s.inserted}:e)),"number"==typeof s.claudeMdLineCount&&r(s.claudeMdLineCount),m.success(`${t.name} 已从磁盘重新加载`)}catch(s){m.error(`更新失败: ${s.message}`)}finally{u.current.delete(t.filename)}}else m.info("卡片未插入,无需更新")},[e,f]);return _.jsxs("div",{className:"flex flex-col h-full overflow-y-auto",children:[_.jsxs("div",{className:"px-3 pt-2.5 pb-2 border-b border-border/50 shrink-0",children:[_.jsxs("div",{className:"flex items-center justify-between",children:[_.jsx("span",{className:"text-xs font-medium uppercase tracking-wider text-muted-foreground",children:"Memory Prompts"}),_.jsxs("div",{className:"flex items-center gap-0.5",children:[_.jsx("button",{onClick:()=>{v()},disabled:c||!t.some(e=>e.inserted),className:g("p-0.5 rounded text-muted-foreground transition-colors","hover:text-foreground hover:bg-muted-foreground/10","disabled:opacity-30 disabled:cursor-not-allowed disabled:hover:bg-transparent disabled:hover:text-muted-foreground"),title:`把所有已插入卡片的内容从磁盘重新加载到 ${n}`,children:_.jsx(yi,{className:g("h-3.5 w-3.5",c&&"animate-spin")})}),_.jsx("button",{onClick:()=>{f()},className:"p-0.5 rounded text-muted-foreground hover:text-foreground hover:bg-muted-foreground/10 transition-colors",title:"刷新(重新扫描 .ccweb/memory/)",children:_.jsx(I,{className:g("h-3.5 w-3.5",a&&"animate-spin")})})]})]}),_.jsxs("p",{className:"mt-1 text-[11px] text-muted-foreground/70 leading-snug",children:["来自 ",_.jsx("code",{className:"text-[11px]",children:".ccweb/memory/*.md"})," 的文件,点击插入 / 移除 ",n,"(以",_.jsx("code",{className:"text-[11px]",children:" START 名 / END 名 "}),"包裹)"]}),null!==s&&_.jsxs("p",{className:"mt-0.5 text-[11px] text-muted-foreground/60 font-mono tabular-nums",children:[n,": ",s," 行"]})]}),_.jsx("div",{className:"px-2 py-2 flex-1 min-h-0",children:a&&0===t.length?_.jsx("div",{className:"px-1 py-6 text-xs text-muted-foreground/60 text-center",children:"加载中…"}):0===t.length?_.jsxs("div",{className:"px-1 py-8 text-xs text-muted-foreground/60 flex flex-col items-center gap-2",children:[_.jsx(pi,{className:"h-5 w-5"}),_.jsxs("div",{className:"text-center leading-relaxed",children:["暂无 memory 文件",_.jsx("br",{}),"新建 ",_.jsx("code",{className:"text-[11px]",children:".ccweb/memory/*.md"})," 文件后点刷新"]})]}):_.jsx("div",{className:"space-y-1.5",children:t.map(e=>_.jsx(mn,{kind:"agent-prompt",noContextMenu:!0,label:e.name,preview:e.preview,inserted:e.inserted,instructionsFile:n,cornerHint:`${e.lineCount} 行`,onLeftClick:()=>{p(e)},onRefresh:e.inserted?()=>{y(e)}:void 0},e.filename))})})]})}function Sn(){const[e,t]=h.useState(null),[i,s]=h.useState(null),[r,n]=h.useState(()=>k(E.browserLastUrl,"http://127.0.0.1")),[o,a]=h.useState(r),[l,c]=h.useState(!1),[d,f]=h.useState([r]),[p,v]=h.useState(0),y=h.useRef(null),x=h.useRef(null),b=h.useRef(null),w=h.useRef(null);h.useEffect(()=>{let e=!1;return(async()=>{try{const i=u(),r=await fetch("/api/browser-chrome/_session",{method:"POST",headers:i?{Authorization:`Bearer ${i}`}:{}});if(e)return;if(403===r.status)return void s("Browser 仅限 admin 用户");if(!r.ok){const e=await r.json().catch(()=>({}));return void s((null==e?void 0:e.error)||`会话创建失败 (HTTP ${r.status})`)}const o=await r.json();t(o),o.url&&"about:blank"!==o.url&&(n(o.url),a(o.url))}catch(i){e||s("无法连接 daemon")}})(),()=>{e=!0}},[]),h.useEffect(()=>{if(!e)return;const t=new WebSocket(`${"https:"===location.protocol?"wss:":"ws:"}//${location.host}/ws/browser-chrome/${e.sid}?token=${encodeURIComponent(e.token)}`);return b.current=t,t.onmessage=e=>{let t;try{t=JSON.parse(e.data)}catch{return}if("frame"===t.type&&t.data&&y.current){const e=w.current||new Image;w.current=e,e.onload=()=>{const t=y.current;if(!t)return;t.width!==e.width&&(t.width=e.width),t.height!==e.height&&(t.height=e.height);const i=t.getContext("2d");i&&i.drawImage(e,0,0)},e.src=`data:image/${t.format||"jpeg"};base64,${t.data}`}},t.onerror=()=>{},t.onclose=e=>{1e3!==e.code&&1001!==e.code&&m.error(`Browser 连接断开 (${e.code})`)},()=>{t.close(1e3),b.current=null}},[e]),h.useEffect(()=>{j(E.browserLastUrl,r)},[r]);const S=h.useCallback(async t=>{if(!e)return;const i=function(e){const t=e.trim();return t?/^https?:\/\//i.test(t)?t:`http://${t}`:""}(t);if(!i)return;const s=u();c(!0);try{const t=await fetch(`/api/browser-chrome/${e.sid}/nav`,{method:"POST",headers:{"Content-Type":"application/json",...s?{Authorization:`Bearer ${s}`}:{}},body:JSON.stringify({url:i})});if(!t.ok){const e=await t.json().catch(()=>({}));return void m.error((null==e?void 0:e.error)||`导航失败 (${t.status})`)}const r=await t.json();n(r.url),a(r.url),f(e=>{const t=e.slice(0,p+1);return t.push(r.url),t.slice(-20)}),v(e=>Math.min(e+1,19))}catch{m.error("导航网络错误")}finally{c(!1)}},[e,p]),C=h.useCallback(e=>{e.preventDefault(),S(o)},[o,S]),N=h.useCallback(()=>{if(p>0){const e=p-1;v(e),S(d[e])}},[p,d,S]),M=h.useCallback(()=>{if(p<d.length-1){const e=p+1;v(e),S(d[e])}},[p,d,S]),D=h.useCallback(()=>S(r),[r,S]),R=h.useCallback(e=>{const t=b.current;t&&t.readyState===WebSocket.OPEN&&t.send(JSON.stringify(e))},[]),P=h.useCallback(t=>{const i=y.current;if(!i||!e)return{x:0,y:0};const s=i.getBoundingClientRect(),r=e.viewport.w/s.width,n=e.viewport.h/s.height;return{x:(t.clientX-s.left)*r,y:(t.clientY-s.top)*n}},[e]),L=h.useCallback(e=>{const{x:t,y:i}=P(e),s=[];e.shiftKey&&s.push("Shift"),e.ctrlKey&&s.push("Control"),e.altKey&&s.push("Alt"),e.metaKey&&s.push("Meta"),R({type:"click",x:t,y:i,button:2===e.button?"right":1===e.button?"middle":"left",modifiers:s})},[P,R]),I=h.useCallback(e=>{const{x:t,y:i}=P(e);R({type:"scroll",x:t,y:i,deltaX:e.deltaX,deltaY:e.deltaY})},[P,R]),T=p>0,B=p<d.length-1;return _.jsxs("div",{className:"h-full flex flex-col bg-background min-h-0",children:[_.jsxs("div",{className:"shrink-0 flex items-center gap-1 px-2 py-1.5 border-b border-border bg-muted/40",children:[_.jsx(K,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:N,disabled:!T||!e,title:"后退","aria-label":"后退",children:_.jsx(qe,{className:"h-3.5 w-3.5"})}),_.jsx(K,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:M,disabled:!B||!e,title:"前进","aria-label":"前进",children:_.jsx(li,{className:"h-3.5 w-3.5"})}),_.jsx(K,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:D,disabled:!e||l,title:"刷新","aria-label":"刷新",children:l?_.jsx(ie,{className:"h-3.5 w-3.5 animate-spin"}):_.jsx(Mi,{className:"h-3.5 w-3.5"})}),_.jsx("form",{className:"flex-1 min-w-0",onSubmit:C,children:_.jsx(q,{value:o,onChange:e=>a(e.target.value),placeholder:"http://127.0.0.1:8080",className:"h-7 text-xs font-mono",spellCheck:!1,autoComplete:"off",disabled:!e})})]}),_.jsx("div",{ref:x,className:"flex-1 min-h-0 bg-white relative overflow-hidden",children:i?_.jsxs("div",{className:g("h-full flex flex-col items-center justify-center gap-2 text-destructive text-xs px-4 text-center"),children:[_.jsx(It,{className:"h-8 w-8 opacity-40"}),_.jsx("div",{children:i})]}):e?_.jsx("canvas",{ref:y,onClick:L,onWheel:I,onContextMenu:e=>e.preventDefault(),className:"w-full h-full block cursor-pointer",style:{imageRendering:"pixelated"}}):_.jsxs("div",{className:g("h-full flex flex-col items-center justify-center gap-2 text-muted-foreground text-xs"),children:[_.jsx(ie,{className:"h-8 w-8 opacity-40 animate-spin"}),_.jsx("div",{children:"启动浏览器…"})]})}),_.jsx("div",{className:"shrink-0 px-2 py-1 text-[10px] text-muted-foreground border-t border-border bg-muted/20",children:"v0 仅支持鼠标点击/滚动 + 仅 RFC1918/loopback。键盘 / 上传下载 Phase 2 跟进。"})]})}function Cn({projectId:e,onSend:t}){const[i,s]=he(E.rightPanelTab,"shortcuts"),r="prompts"===i?"prompts":"memory"===i?"memory":"browser"===i?"browser":"shortcuts";return _.jsxs(At,{value:r,onValueChange:e=>s(e),orientation:"vertical",className:"h-full flex bg-muted text-foreground overflow-hidden",children:[_.jsxs("div",{className:"flex-1 min-w-0 flex flex-col border-r border-border",children:[_.jsx(Ht,{value:"shortcuts",className:"flex-1 min-h-0 mt-0 data-[state=inactive]:hidden",children:_.jsx(vn,{projectId:e,onSend:t})}),_.jsx(Ht,{value:"prompts",className:"flex-1 min-h-0 mt-0 data-[state=inactive]:hidden",children:_.jsx(xn,{projectId:e})}),_.jsx(Ht,{value:"memory",className:"flex-1 min-h-0 mt-0 data-[state=inactive]:hidden",children:_.jsx(wn,{projectId:e})}),_.jsx(Ht,{value:"browser",className:"flex-1 min-h-0 mt-0 data-[state=inactive]:hidden",children:_.jsx(Sn,{})})]}),_.jsxs(zt,{className:g("flex flex-col items-center justify-start shrink-0","h-full w-9 border-l border-border rounded-none p-1 gap-1"),children:[_.jsx($t,{value:"shortcuts",title:"Quick Prompts (快捷 Prompts)","aria-label":"Quick Prompts",className:g("h-7 w-7 p-0 rounded-md flex items-center justify-center"),children:_.jsx(Ye,{className:"h-3.5 w-3.5"})}),_.jsx($t,{value:"prompts",title:"Agent Prompts","aria-label":"Agent Prompts",className:g("h-7 w-7 p-0 rounded-md flex items-center justify-center"),children:_.jsx(Xe,{className:"h-3.5 w-3.5"})}),_.jsx($t,{value:"memory",title:"Memory Prompts (.ccweb/memory/*.md)","aria-label":"Memory Prompts",className:g("h-7 w-7 p-0 rounded-md flex items-center justify-center"),children:_.jsx(pi,{className:"h-3.5 w-3.5"})}),_.jsx($t,{value:"browser",title:"Browser (访问 daemon 所在机器的本地 / 局域网网页)","aria-label":"Browser",className:g("h-7 w-7 p-0 rounded-md flex items-center justify-center"),children:_.jsx(It,{className:"h-3.5 w-3.5"})})]})]})}function kn({projectId:e,state:t,running:i,onRefresh:s}){if(!t)return null;let r=_.jsx(ie,{className:"h-3 w-3 animate-spin"}),n="text-blue-600 dark:text-blue-400",o="运行中";switch(t.status){case"running":r=_.jsx(ie,{className:"h-3 w-3 animate-spin"}),n="text-blue-600 dark:text-blue-400",o="运行中";break;case"paused":r=_.jsx(ie,{className:"h-3 w-3"}),n="text-amber-600 dark:text-amber-400",o="等待输入";break;case"completed":r=_.jsx(ri,{className:"h-3 w-3"}),n="text-emerald-600 dark:text-emerald-400",o="已完成";break;case"failed":r=_.jsx(ai,{className:"h-3 w-3"}),n="text-red-600 dark:text-red-400",o="失败";break;case"cancelled":r=_.jsx(ai,{className:"h-3 w-3"}),n="text-muted-foreground",o="已取消";break;default:r=_.jsx(ie,{className:"h-3 w-3"})}return _.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[_.jsxs("span",{className:`flex items-center gap-1 ${n}`,children:[r,_.jsx("span",{className:"font-medium",children:o})]}),_.jsx("span",{className:"text-muted-foreground font-mono truncate max-w-[200px]",children:t.trackFilename}),void 0!==t.currentTaskIndex&&_.jsxs("span",{className:"text-muted-foreground",children:["#",t.currentTaskIndex]}),i&&_.jsx(K,{size:"sm",variant:"ghost",onClick:async()=>{try{await Promise.reject(new Error("track run API not available in v3 M0")),m.success("已请求中止"),s()}catch(e){m.error(e instanceof Error?e.message:"中止失败")}},title:"中止",className:"h-6 w-6 p-0",children:_.jsx(S,{className:"h-3 w-3"})}),"failed"===t.status&&t.error&&_.jsxs("span",{className:"text-red-600 dark:text-red-400 truncate max-w-[300px] font-mono",title:`${t.error.errorType}${t.error.code?` [${t.error.code}]`:""}: ${t.error.message}`,children:[t.error.code?`[${t.error.code}] `:"",t.error.message]})]})}function En({projectId:e,open:t,request:i,onSubmitted:s}){const r=c(),[n,o]=h.useState(()=>{var e;const t={};for(const s of i.fields)switch(s.type){case"bool":t[s.key]=!1;break;case"number":t[s.key]=0;break;case"enum":t[s.key]=(null==(e=s.variants)?void 0:e[0])??"";break;default:t[s.key]=""}return t}),[a,l]=h.useState(!1),d=(e,t)=>{o(i=>({...i,[e]:t}))};return _.jsx(se,{open:t,onOpenChange:()=>{},children:_.jsxs(re,{className:"max-w-lg",onPointerDownOutside:e=>e.preventDefault(),onEscapeKeyDown:e=>e.preventDefault(),children:[_.jsx(ne,{children:_.jsx(oe,{children:"工作轨需要输入"})}),_.jsx("div",{className:"space-y-3",children:i.fields.map(e=>_.jsxs("div",{className:"space-y-1.5",children:[_.jsxs(le,{className:"text-xs text-muted-foreground",children:[e.label," ",_.jsxs("span",{className:"opacity-60 font-mono",children:["(",e.key,")"]})]}),"text"===e.type&&_.jsx(q,{value:n[e.key]??"",placeholder:e.placeholder,onChange:t=>d(e.key,t.target.value)}),"number"===e.type&&_.jsx(q,{type:"number",value:String(n[e.key]??""),placeholder:e.placeholder,onChange:t=>{const i=Number(t.target.value);d(e.key,Number.isNaN(i)?"":i)}}),"bool"===e.type&&_.jsxs("div",{className:"flex items-center gap-2",children:[_.jsx("input",{type:"checkbox",checked:!!n[e.key],onChange:t=>d(e.key,t.target.checked),className:"h-4 w-4"}),_.jsx("span",{className:"text-sm",children:n[e.key]?"是":"否"})]}),"enum"===e.type&&_.jsxs(Zt,{value:n[e.key]??"",onValueChange:t=>d(e.key,t),children:[_.jsx(Jt,{children:_.jsx(Qt,{placeholder:"选择..."})}),_.jsx(ei,{children:(e.variants??[]).map(e=>_.jsx(ti,{value:e,children:e},e))})]})]},e.key))}),_.jsxs("div",{className:"flex justify-between items-center gap-2 pt-2",children:[_.jsx(K,{onClick:async()=>{if(await r({description:"中止整个工作轨运行?正在等待的 LLM 调用会被取消。",confirmLabel:"中止",destructive:!0}))try{await Promise.reject(new Error("track run API not available in v3 M0")),m.success("已请求中止"),s()}catch(e){m.error(e instanceof Error?e.message:"中止失败")}},variant:"ghost",size:"sm",disabled:a,className:"text-muted-foreground hover:text-destructive",children:"中止运行"}),_.jsx(K,{onClick:async()=>{l(!0);try{await(i.requestId,Promise.reject(new Error("track run API not available in v3 M0"))),s()}catch(e){m.error(e instanceof Error?e.message:"提交失败")}finally{l(!1)}},disabled:a,size:"sm",children:a?"提交中…":"提交"})]})]})})}function Nn(e){const[t,i]=h.useState(null),[s,r]=h.useState(!1),[n,o]=h.useState(null),a=h.useRef(e);a.current=e;const l=h.useCallback(async()=>{const e=a.current;if(e)try{const t=await Promise.resolve({running:!1,state:null,pendingAskUser:null});if(e!==a.current)return;i(t.state),r(t.running),o(t.pendingAskUser)}catch{}},[]),c=h.useRef(5e3),d=!!t||s||!!n;return h.useEffect(()=>{if(!e)return;const t=e=>{const t=e.detail;if(t&&t.type)switch(t.type){case"track_status_change":{const e=t;if(i(e.state),r("running"===e.state.status||"paused"===e.state.status),"failed"===e.state.status&&e.state.error){const t=e.state.error.code?`[${e.state.error.code}] `:"";m.error(`工作轨失败: ${t}${e.state.error.message}`)}else"cancelled"===e.state.status&&m.info("工作轨已取消");break}case"track_ask_user":{const e=t;o({runId:e.runId,requestId:e.requestId,fields:e.fields});break}case"track_run_complete":t.ok||o(null);break}};return window.addEventListener("ccweb:track-msg",t),()=>window.removeEventListener("ccweb:track-msg",t)},[e]),h.useEffect(()=>{if(!e)return i(null),r(!1),void o(null);let t=null;const s=d?5e3:3e4;c.current=s;const n=()=>{l(),t=setInterval(()=>{l()},s)},a=()=>{null!==t&&(clearInterval(t),t=null)},h=()=>{document.hidden?a():t||n()};return document.hidden||n(),document.addEventListener("visibilitychange",h),()=>{a(),document.removeEventListener("visibilitychange",h)}},[e,l,d]),{state:t,running:s,pendingAskUser:n,refresh:l}}var Mn=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"].reduce((e,t)=>{const i=Ge(`Primitive.${t}`),s=h.forwardRef((e,s)=>{const{asChild:r,...n}=e,o=r?i:t;return"undefined"!=typeof window&&(window[Symbol.for("radix-ui")]=!0),_.jsx(o,{...n,ref:s})});return s.displayName=`Primitive.${t}`,{...e,[t]:s}},{}),jn="horizontal",Dn=["horizontal","vertical"],Rn=h.forwardRef((e,t)=>{const{decorative:i,orientation:s=jn,...r}=e,n=function(e){return Dn.includes(e)}(s)?s:jn,o=i?{role:"none"}:{"aria-orientation":"vertical"===n?n:void 0,role:"separator"};return _.jsx(Mn.div,{"data-orientation":n,...o,...r,ref:t})});Rn.displayName="Separator";var Pn=Rn;const Ln=h.forwardRef(({className:e,orientation:t="horizontal",decorative:i=!0,...s},r)=>_.jsx(Pn,{ref:r,decorative:i,orientation:t,className:g("shrink-0 bg-border","horizontal"===t?"h-[1px] w-full":"h-full w-[1px]",e),...s}));Ln.displayName=Pn.displayName;const In=[{tool:"claude",label:"Claude Code",supportsContinue:!0},{tool:"codex",label:"Codex",supportsContinue:!0},{tool:"gemini",label:"Gemini CLI",supportsContinue:!0},{tool:"opencode",label:"OpenCode",supportsContinue:!1},{tool:"qwen",label:"Qwen Code",supportsContinue:!1},{tool:"terminal",label:"Bare Shell",supportsContinue:!1}];function Tn(e){var t;return(null==(t=In.find(t=>t.tool===e))?void 0:t.label)??String(e??"")}function Bn(e){var t;return(null==(t=In.find(t=>t.tool===e))?void 0:t.supportsContinue)??!1}function On({open:e,onOpenChange:t,currentCliTool:i,loading:s,onConfirm:r}){const{t:n}=Ze(),[o,a]=h.useState(null),[l,c]=h.useState(!1),[d,u]=h.useState(null);h.useEffect(()=>{e&&(a(null),c(!1),u(null))},[e]),h.useEffect(()=>{o&&!Bn(o)&&c(!1)},[o]);const f=!!o&&Bn(o);return _.jsx(se,{open:e,onOpenChange:t,children:_.jsxs(re,{className:"max-w-lg",children:[_.jsxs(ne,{children:[_.jsx(oe,{children:n("switch_cli.title")}),_.jsx(ae,{children:n("switch_cli.description",{current:Tn(i)})})]}),_.jsxs("div",{className:"space-y-4",children:[_.jsxs("div",{className:"space-y-2",children:[_.jsx("div",{className:"text-sm font-medium",children:n("switch_cli.target_label")}),_.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:In.map(e=>{const t=e.tool===i,r=e.tool===o;return _.jsxs("button",{type:"button",disabled:t||s,onClick:()=>a(e.tool),className:g("text-left px-3 py-2 rounded-md border text-sm transition-colors",r?"border-primary bg-accent":"border-border hover:bg-accent/50",t&&"opacity-50 cursor-not-allowed"),children:[_.jsx("div",{className:"font-medium",children:e.label}),_.jsx("div",{className:"text-xs text-muted-foreground",children:t?n("switch_cli.tag_current"):e.supportsContinue?n("switch_cli.tag_supports_continue"):n("switch_cli.tag_no_continue")})]},e.tool)})})]}),_.jsxs("div",{className:"space-y-2",children:[_.jsx("div",{className:"text-sm font-medium",children:n("switch_cli.mode_label")}),_.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[_.jsxs("button",{type:"button",disabled:s,onClick:()=>c(!1),className:g("text-left px-3 py-2 rounded-md border text-sm transition-colors",l?"border-border hover:bg-accent/50":"border-primary bg-accent"),children:[_.jsx("div",{className:"font-medium",children:n("switch_cli.mode_fresh")}),_.jsx("div",{className:"text-xs text-muted-foreground",children:n("switch_cli.mode_fresh_hint")})]}),_.jsxs("button",{type:"button",disabled:s||!o||!f,onClick:()=>c(!0),title:o&&!f?n("switch_cli.mode_continue_unsupported",{tool:Tn(o)}):void 0,className:g("text-left px-3 py-2 rounded-md border text-sm transition-colors",l?"border-primary bg-accent":"border-border hover:bg-accent/50",(!o||!f)&&"opacity-50 cursor-not-allowed"),children:[_.jsx("div",{className:"font-medium",children:n("switch_cli.mode_continue")}),_.jsx("div",{className:"text-xs text-muted-foreground",children:o&&!f?n("switch_cli.mode_continue_unsupported",{tool:Tn(o)}):n("switch_cli.mode_continue_hint")})]})]})]}),d&&_.jsx("div",{className:"text-xs text-red-500 break-words",children:d})]}),_.jsxs(ce,{children:[_.jsx(K,{variant:"outline",onClick:()=>t(!1),disabled:s,children:n("switch_cli.cancel")}),_.jsx(K,{onClick:()=>{(async()=>{if(o){u(null);try{await r(o,l)}catch(e){u(e instanceof Error?e.message:String(e))}}})()},disabled:!o||s,children:n(s?"switch_cli.confirming":"switch_cli.confirm")})]})]})})}function An({status:e}){return _.jsxs("span",{className:g("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",{running:"bg-green-500/10 text-green-600 border-green-500/20",stopped:"bg-muted text-muted-foreground border-border",restarting:"bg-yellow-500/10 text-yellow-600 border-yellow-500/20"}[e]),children:[_.jsx("span",{className:g("w-1.5 h-1.5 rounded-full",{"bg-green-500":"running"===e,"bg-muted-foreground":"stopped"===e,"bg-yellow-400 animate-pulse":"restarting"===e})}),e.charAt(0).toUpperCase()+e.slice(1)]})}function zn({project:e,projectId:t,showFileTree:i,showShortcuts:s,showChatOverlay:r,onToggleFileTree:n,onToggleShortcuts:o,onToggleChatOverlay:a,onProjectUpdate:l}){const{t:c}=Ze(),d=Je(),[u,f]=h.useState(!1),[p,v]=h.useState(!1),[y,x]=h.useState(0),[C,k]=h.useState(!1),[E,N]=h.useState(!1),[M,j]=h.useState(!1),[D,R]=h.useState(!1),P=Nn(e.id);Qe({onStart:e=>{e.projectId===t&&x(0)},onProgress:e=>{e.projectId===t&&x(e.filesTransferred)},onDone:e=>{e.projectId===t&&x(0)}}),h.useEffect(()=>{const e=()=>N(!!document.fullscreenElement);return document.addEventListener("fullscreenchange",e),()=>document.removeEventListener("fullscreenchange",e)},[]);const L=et(e=>e.updateProject);return _.jsx("header",{className:"border-b border-border flex-shrink-0 bg-muted/50",children:_.jsxs("div",{className:"px-3 h-12 flex items-center gap-2",children:[_.jsx(K,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>d("/"),children:_.jsx(qe,{className:"h-4 w-4"})}),_.jsx(Ln,{orientation:"vertical",className:"h-5 mx-0.5"}),_.jsx(K,{variant:"ghost",size:"icon",className:g("h-7 w-7",i&&"bg-accent"),onClick:n,title:c("project_header.toggle_file_tree"),children:_.jsx(Si,{className:"h-4 w-4"})}),_.jsx(K,{variant:"ghost",size:"icon",className:g("h-7 w-7",s&&"bg-accent"),onClick:o,title:c("project_header.toggle_right_panel"),children:_.jsx(Ci,{className:"h-4 w-4"})}),"terminal"!==e.cliTool&&_.jsx(K,{variant:"ghost",size:"icon",className:g("h-7 w-7",r&&"bg-accent"),onClick:a,title:c("project_header.toggle_chat_overlay"),children:_.jsx(xi,{className:"h-4 w-4"})}),_.jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-2 ml-2",children:[_.jsx("h1",{className:"font-semibold text-foreground truncate text-sm",children:e.name}),_.jsx(An,{status:e.status}),_.jsx(tt,{variant:"outline",className:"text-xs",children:"unlimited"===e.permissionMode?"Unlimited":"Limited"}),P.state&&_.jsx(kn,{projectId:e.id,state:P.state,running:P.running,onRefresh:P.refresh}),_.jsxs("button",{type:"button",onClick:()=>j(!0),disabled:D,title:`${c("project_header.switch_cli_title")} (${Tn(e.cliTool)})`,className:"inline-flex items-center gap-1 text-xs px-2 py-0.5 rounded-full border border-border bg-background hover:bg-accent transition-colors disabled:opacity-50 flex-shrink-0",children:[_.jsx(I,{className:"h-3 w-3"}),_.jsx("span",{className:"font-medium hidden sm:inline",children:Tn(e.cliTool)})]}),_.jsx("span",{className:"text-xs text-muted-foreground font-mono truncate hidden lg:block",children:e.folderPath})]}),_.jsx(it,{}),_.jsx(st,{}),_.jsx(K,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>{document.fullscreenElement?document.exitFullscreen():document.documentElement.requestFullscreen()},title:c(E?"project_header.fullscreen_exit":"project_header.fullscreen_enter"),children:E?_.jsx(b,{className:"h-3.5 w-3.5"}):_.jsx(w,{className:"h-3.5 w-3.5"})}),_.jsx(Ln,{orientation:"vertical",className:"h-5 mx-0.5"}),p?_.jsxs(K,{variant:"outline",size:"sm",className:"flex-shrink-0",onClick:()=>{(async()=>{if(p&&!C){k(!0);try{(await nt(t)).cancelled?m.info(c("project_header.sync_cancelled")):m.error(c("project_header.sync_cancel_failed"))}catch(e){m.error(e instanceof Error?e.message:c("project_header.sync_cancel_failed")),k(!1)}}})()},disabled:C,title:c("project_header.sync_cancel_title"),children:[C?_.jsx(ie,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):_.jsx(S,{className:"h-3.5 w-3.5 mr-1.5"}),_.jsx("span",{className:"tabular-nums",children:y>0?c("project_header.sync_progress_label",{files:y}):c("project_header.sync_progress_label_empty")})]}):_.jsxs(K,{variant:"outline",size:"sm",className:"flex-shrink-0",onClick:()=>{(async()=>{if(!p){v(!0),x(0);try{const e=await ot(t);e.skipped?m.info(c("project_header.sync_skipped")):e.ok?m.success(c("project_header.sync_success",{files:e.filesTransferred,seconds:Math.round(e.durationMs/1e3)})):"cancelled"===e.reason||m.error(e.reason?c("project_header.sync_failed_with_reason",{reason:e.reason}):c("project_header.sync_failed"))}catch(e){m.error(e instanceof Error?e.message:c("project_header.sync_failed"))}finally{v(!1),x(0),k(!1)}}})()},title:c("project_header.sync_button_title"),children:[_.jsx(rt,{className:"h-3.5 w-3.5 mr-1.5"}),c("project_header.sync")]}),_.jsx(On,{open:M,onOpenChange:e=>{D||j(e)},currentCliTool:e.cliTool,loading:D,onConfirm:async(t,i)=>{R(!0);try{const s=await at(e.id,t,i);l(s),L(s),j(!1),m.success(c("switch_cli.switched_toast",{tool:Tn(t)}))}catch(s){const e=s instanceof Error?s.message:String(s);throw m.error(c("switch_cli.switch_failed",{reason:e})),s}finally{R(!1)}}}),P.pendingAskUser&&_.jsx(En,{projectId:e.id,open:!!P.pendingAskUser,request:P.pendingAskUser,onSubmitted:()=>P.refresh()}),"stopped"===e.status&&_.jsxs(K,{variant:"outline",size:"sm",className:"flex-shrink-0",onClick:()=>{(async()=>{f(!0);try{l(await lt(e.id))}catch(t){console.error(t)}finally{f(!1)}})()},disabled:u,children:[_.jsx(ki,{className:"h-3.5 w-3.5 mr-1.5"}),"Start"]})]})})}
14
+ */const $i=new Set(["png","jpg","jpeg","gif","webp","svg","bmp","ico","avif","tiff","tif"]);function Hi(e){return"md"===e?"Markdown":"html"===e||"htm"===e?"HTML":"高亮"}const Wi=[50,75,100,125,150,200,250,300],Fi=100;function Ki({filePath:e,onClose:t,onMinimize:i}){const s=c(),r=e.endsWith("/.notebook/graph.yaml"),n=r?e.replace(/\/.notebook\/graph\.yaml$/,""):"",[o,a]=h.useState(null),[l,N]=h.useState(null),[M,D]=h.useState(()=>r?"graph":"rendered"),[R,P]=h.useState(!1),[L,T]=h.useState(Fi),[I,B]=h.useState(""),[O,A]=h.useState(!1),[z,$]=h.useState(!1),H=h.useRef(null),[W,F]=h.useState(!0),{resolved:K}=d(),U=e.split("/").pop()??e,V=h.useMemo(()=>function(e){const t=e.split("/").pop()??"",i=t.toLowerCase();if("dockerfile"===i)return"dockerfile";if("makefile"===i)return"makefile";const s=t.lastIndexOf(".");return s>=0?t.slice(s+1).toLowerCase():""}(e),[e]),q=$i.has(V),Y=Oi.has(V),X=Ai.has(V),G=function(e){return"md"===e||"html"===e||"htm"===e||e in zi}(V),Z=zi[V]||V,J=h.useMemo(()=>{if(!q)return"";const t=C(e),i=u(),s=`${t}&t=${Date.now()}`;return i?`${s}&token=${encodeURIComponent(i)}`:s},[e,q]);h.useEffect(()=>{if(F(!0),a(null),N(null),T(function(e){const t=k(E.fileZoom,{},!0)[e];return Wi.includes(t)?t:Fi}(e)),$(!1),q||Y||X)return a({path:e,binary:!1,tooLarge:!1,size:0,content:null}),void D("rendered");D(e.endsWith("/.notebook/graph.yaml")?"graph":"rendered"),f(e).then(e=>{a(e),B(e.content??"")}).catch(e=>N(e instanceof Error?e.message:"Failed to load file"))},[e,q,Y,X]);const Q=h.useCallback(async()=>{A(!0);try{await p(e,I),a(e=>e?{...e,content:I,size:new Blob([I]).size}:e),$(!1)}catch(t){m.error(t instanceof Error?t.message:"保存失败")}finally{A(!1)}},[e,I]);h.useEffect(()=>{const e=e=>{(e.metaKey||e.ctrlKey)&&"s"===e.key&&"edit"===M&&(e.preventDefault(),Q())};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[M,Q]),h.useEffect(()=>{const e=async e=>{if("Escape"===e.key&&W){if(z){if(!(await s({description:"有未保存的修改,确定关闭?",confirmLabel:"放弃修改",destructive:!0})))return}t()}};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[W,t,z,s]);const ee=async()=>{if(z){if(!(await s({description:"有未保存的修改,确定退出编辑?",confirmLabel:"放弃修改",destructive:!0})))return}D(r?"graph":G?"rendered":"plain"),$(!1)},te=t=>{T(t),function(e,t){const i=k(E.fileZoom,{},!0);t===Fi?delete i[e]:i[e]=t,j(E.fileZoom,i,!0)}(e,t)},ie=(null==o?void 0:o.content)??"",se="dark"===K?jt:Dt,re=L/100*12,ne=o&&!o.binary&&!o.tooLarge&&!X,oe=h.useDeferredValue(I),ae=h.useMemo(()=>{var e,t;if(!o||o.binary||o.tooLarge)return null;if(q||Y||X)return null;const i="edit"===M?oe:ie;if(null==i)return null;return{bytes:new Blob([i]).size,words:((null==(e=i.match(/[\u4e00-\u9fff\u3400-\u4dbf]/g))?void 0:e.length)??0)+((null==(t=i.replace(/[\u4e00-\u9fff\u3400-\u4dbf]/g," ").match(/[a-zA-Z0-9]+/g))?void 0:t.length)??0),lines:""===i?0:i.split("\n").length}},[o,q,Y,M,oe,ie]);return _.jsx("div",{className:g("fixed inset-0 z-50 flex items-center justify-center transition-all duration-200",W?"bg-black/60 backdrop-blur-sm pointer-events-auto":"bg-transparent pointer-events-none"),onClick:e=>{e.target===e.currentTarget&&F(!1)},children:_.jsxs("div",{className:g("relative flex flex-col bg-background border border-border shadow-sm transition-all duration-200 pointer-events-auto",R?"w-screen h-screen rounded-none":"w-[72vw] max-w-4xl h-[80vh] rounded-xl",!W&&!R&&"opacity-50"),onClick:()=>F(!0),onFocus:e=>{e.stopPropagation(),F(!0)},children:[_.jsxs("div",{className:"flex items-center gap-2 px-4 h-10 border-b border-border flex-shrink-0",children:[_.jsx(wt,{className:"h-3.5 w-3.5 text-muted-foreground flex-shrink-0"}),_.jsxs("span",{className:"flex-1 text-sm text-foreground font-medium truncate",title:e,children:[U,z&&_.jsx("span",{className:"text-muted-foreground ml-1",children:"*"}),ae&&_.jsxs("span",{className:"text-muted-foreground font-normal ml-2 text-xs tabular-nums",children:[(le=ae.bytes,le<1024?`${le} B`:le<1048576?`${(le/1024).toFixed(1)} KB`:`${(le/1024/1024).toFixed(2)} MB`)," · ",ae.words.toLocaleString()," 词 · ",ae.lines.toLocaleString()," 行"]})]}),ne&&!q&&!Y&&_.jsxs("div",{className:"flex items-center rounded-md border border-border bg-muted/50 p-0.5",children:[G&&_.jsxs(_.Fragment,{children:[_.jsxs("button",{onClick:()=>"edit"===M?ee():D("plain"),className:g("p-1 rounded-md transition-colors flex items-center gap-1 text-xs","plain"===M?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),title:"纯文本",children:[_.jsx(ui,{className:"h-3 w-3"}),_.jsx("span",{className:"hidden sm:inline",children:"源码"})]}),_.jsxs("button",{onClick:()=>"edit"===M?ee():D("rendered"),className:g("p-1 rounded-md transition-colors flex items-center gap-1 text-xs","rendered"===M?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),title:Hi(V),children:[_.jsx(v,{className:"h-3 w-3"}),_.jsx("span",{className:"hidden sm:inline",children:Hi(V)})]})]}),r&&_.jsxs("button",{onClick:()=>"edit"===M?ee():D("graph"),className:g("p-1 rounded-md transition-colors flex items-center gap-1 text-xs","graph"===M?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),title:"图谱",children:[_.jsx(wi,{className:"h-3 w-3"}),_.jsx("span",{className:"hidden sm:inline",children:"图谱"})]}),_.jsxs("button",{onClick:()=>"edit"===M?ee():(B((null==o?void 0:o.content)??""),$(!1),D("edit"),void setTimeout(()=>{var e;return null==(e=H.current)?void 0:e.focus()},0)),className:g("p-1 rounded-md transition-colors flex items-center gap-1 text-xs","edit"===M?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),title:"编辑",children:[_.jsx(y,{className:"h-3 w-3"}),_.jsx("span",{className:"hidden sm:inline",children:"编辑"})]})]}),"edit"===M&&_.jsxs("button",{onClick:()=>{Q()},disabled:O||!z,className:g("flex items-center gap-1 text-xs px-2 py-1 rounded transition-colors",z?"bg-blue-600 hover:bg-blue-500 text-white":"bg-muted text-muted-foreground"),title:"保存 (⌘S)",children:[_.jsx(Bt,{className:"h-3 w-3"}),O?"保存中...":"保存"]}),(ne||q||X)&&"edit"!==M&&"graph"!==M&&_.jsxs("div",{className:"flex items-center rounded-md border border-border bg-muted/50 p-0.5 gap-0.5",children:[_.jsx("button",{onClick:()=>{const e=[...Wi].reverse().find(e=>e<L);e&&te(e)},disabled:L<=Wi[0],className:"p-1 rounded-md text-muted-foreground hover:text-foreground transition-colors disabled:opacity-30",title:"缩小",children:_.jsx(Li,{className:"h-3 w-3"})}),_.jsxs("button",{onClick:()=>te(Fi),className:"px-1 text-xs text-muted-foreground hover:text-foreground transition-colors min-w-[36px] text-center",title:"重置缩放",children:[L,"%"]}),_.jsx("button",{onClick:()=>{const e=Wi.find(e=>e>L);e&&te(e)},disabled:L>=Wi[Wi.length-1],className:"p-1 rounded-md text-muted-foreground hover:text-foreground transition-colors disabled:opacity-30",title:"放大",children:_.jsx(Pi,{className:"h-3 w-3"})})]}),i&&_.jsx("button",{className:"p-1 rounded text-muted-foreground hover:text-foreground transition-colors",onClick:i,title:"最小化到 dock",children:_.jsx(x,{className:"h-3.5 w-3.5"})}),_.jsx("button",{className:"p-1 rounded text-muted-foreground hover:text-foreground transition-colors",onClick:()=>P(e=>!e),title:R?"退出全屏":"全屏",children:R?_.jsx(b,{className:"h-3.5 w-3.5"}):_.jsx(w,{className:"h-3.5 w-3.5"})}),_.jsx("button",{className:"p-0.5 rounded text-muted-foreground hover:text-foreground transition-colors",onClick:async()=>{if(z){if(!(await s({description:"有未保存的修改,确定关闭?",confirmLabel:"放弃修改",destructive:!0})))return}t()},children:_.jsx(S,{className:"h-4 w-4"})})]}),_.jsxs("div",{className:g("flex-1 min-h-0","graph"===M?"overflow-hidden":"overflow-auto"),children:["graph"===M&&_.jsx(h.Suspense,{fallback:_.jsx("p",{className:"text-sm text-muted-foreground p-4",children:"Loading…"}),children:_.jsx(Ti,{folderPath:n})}),"graph"!==M&&!o&&!l&&_.jsx("p",{className:"text-sm text-muted-foreground p-4",children:"Loading…"}),"graph"!==M&&l&&_.jsx("p",{className:"text-sm text-red-400 p-4",children:l}),"graph"!==M&&q&&o&&_.jsx("div",{className:"flex items-center justify-center p-4 h-full",children:_.jsx("img",{src:J,alt:U,className:"max-w-full max-h-full object-contain rounded-md",style:{transform:`scale(${L/100})`,transformOrigin:"center center"},draggable:!1})}),"graph"!==M&&Y&&o&&_.jsx(h.Suspense,{fallback:_.jsx("p",{className:"text-sm text-muted-foreground p-4",children:"Loading…"}),children:_.jsx(Ii,{filePath:e,ext:V,zoom:L})}),"graph"!==M&&X&&o&&_.jsx(h.Suspense,{fallback:_.jsx("p",{className:"text-sm text-muted-foreground p-4",children:"Loading…"}),children:_.jsx(Bi,{filePath:e,zoom:L})}),"graph"!==M&&!q&&!Y&&!X&&o&&o.binary&&_.jsxs("div",{className:"flex flex-col items-center gap-2 py-12 text-muted-foreground p-4",children:[_.jsx(wt,{className:"h-8 w-8"}),_.jsx("p",{className:"text-sm",children:"Binary file — cannot preview"}),_.jsxs("p",{className:"text-xs text-muted-foreground",children:[(o.size/1024).toFixed(1)," KB"]})]}),"graph"!==M&&!Y&&o&&o.tooLarge&&_.jsxs("div",{className:"flex flex-col items-center gap-2 py-12 text-muted-foreground p-4",children:[_.jsx(wt,{className:"h-8 w-8"}),_.jsx("p",{className:"text-sm",children:"File too large to preview"}),_.jsxs("p",{className:"text-xs text-muted-foreground",children:[(o.size/1024/1024).toFixed(2)," MB (limit 5 MB)"]})]}),"graph"!==M&&ne&&null!==ie&&_.jsxs(_.Fragment,{children:["edit"===M&&_.jsx("textarea",{ref:H,value:I,onChange:e=>{B(e.target.value),$(!0)},className:"w-full h-full bg-transparent text-foreground font-mono outline-none resize-none p-4 leading-relaxed",style:{fontSize:`${re}px`,minHeight:"100%"},spellCheck:!1}),"edit"!==M&&_.jsxs("div",{className:"p-4",style:{fontSize:`${re}px`},children:["plain"===M&&_.jsx("pre",{className:"font-mono text-foreground whitespace-pre-wrap break-words leading-relaxed",style:{fontSize:"inherit"},children:ie}),"rendered"===M&&"md"===V&&_.jsx("div",{className:"prose dark:prose-invert max-w-none prose-pre:bg-muted prose-pre:border prose-pre:border-border prose-code:text-foreground",style:{fontSize:"inherit"},children:_.jsx(St,{remarkPlugins:[kt,Et],rehypePlugins:[Ct],urlTransform:(e,t,i)=>"src"===t&&"img"===i.tagName?e:Rt(e),components:{code({className:e,children:t,...i}){const s=/language-(\w+)/.exec(e||"");return!s&&!e?_.jsx("code",{className:e,...i,children:t}):_.jsx(Mt,{style:se,language:(null==s?void 0:s[1])||"text",PreTag:"div",customStyle:{fontSize:"inherit",borderRadius:"6px",margin:0},children:String(t).replace(/\n$/,"")})},img:({src:t,alt:i,...s})=>_.jsx("img",{...s,src:Nt(e,t,u()),alt:i??"",loading:"lazy",style:{maxWidth:"100%",height:"auto"}})},children:ie})}),"rendered"===M&&("html"===V||"htm"===V)&&_.jsx("iframe",{srcDoc:bt.sanitize(ie,{WHOLE_DOCUMENT:!0,ADD_TAGS:["style","link"]}),className:"w-full h-full border-0 rounded bg-white",sandbox:"",title:U,style:{minHeight:"60vh",transform:`scale(${L/100})`,transformOrigin:"top left",width:1e4/L+"%",height:1e4/L+"%"}}),"rendered"===M&&"md"!==V&&"html"!==V&&"htm"!==V&&Z&&_.jsx(Mt,{style:se,language:Z,showLineNumbers:!0,lineNumberStyle:{color:"dark"===K?"#555":"#aaa",fontSize:"inherit"},customStyle:{fontSize:"inherit",borderRadius:"6px",margin:0,background:"transparent"},children:ie}),"rendered"===M&&!G&&_.jsx("pre",{className:"font-mono text-foreground whitespace-pre-wrap break-words leading-relaxed",style:{fontSize:"inherit"},children:ie})]})]})]})]})});var le}async function Ui(e){var t;if("undefined"!=typeof navigator&&(null==(t=navigator.clipboard)?void 0:t.writeText))try{return await navigator.clipboard.writeText(e),!0}catch{}try{const t=document.createElement("textarea");t.value=e,t.style.position="fixed",t.style.left="-9999px",t.style.top="0",t.setAttribute("readonly",""),document.body.appendChild(t),t.select(),t.setSelectionRange(0,e.length);const i=document.execCommand("copy");return document.body.removeChild(t),i}catch{return!1}}const Vi=new Set(["png","jpg","jpeg","gif","webp","svg","bmp","ico","avif","tiff","tif"]);function qi(e){const t=e.lastIndexOf(".");return t>=0&&Vi.has(e.slice(t+1).toLowerCase())}function Yi({projectPath:e,projectId:t}){var i;const[s,r]=h.useState(new Map),[n,o]=h.useState(new Set([e])),[a,l]=h.useState(new Set),d=D(e=>e.get(t).activePreviewPath),f=D(e=>e.get(t).filePreviews),p=D(e=>e.openFilePreview),v=D(e=>e.closeFilePreview),y=D(e=>e.minimizeFilePreview),x=!!(null==(i=f.find(e=>e.path===d))?void 0:i.minimized),[b,w]=h.useState(null),[S,k]=h.useState(!1),[E,N]=h.useState(null),[M,j]=h.useState(!1),W=c(),F=h.useRef(null),K=h.useRef(null),U=h.useRef(null),V=function(e={}){const t=e.duration??500,i=e.moveTolerance??10,s=h.useRef(null),r=h.useRef(null),n=h.useRef(!1),o=h.useCallback(()=>{s.current&&(clearTimeout(s.current),s.current=null),r.current=null},[]);return{bind:h.useCallback(e=>({onTouchStart:i=>{if(1!==i.touches.length)return;const o=i.touches[0];r.current={x:o.clientX,y:o.clientY},n.current=!1,s.current&&clearTimeout(s.current),s.current=setTimeout(()=>{if(n.current=!0,"undefined"!=typeof navigator&&"vibrate"in navigator)try{navigator.vibrate(15)}catch{}e(o.clientX,o.clientY)},t)},onTouchMove:e=>{if(!r.current||!s.current)return;const t=e.touches[0],n=t.clientX-r.current.x,a=t.clientY-r.current.y;Math.hypot(n,a)>i&&o()},onTouchEnd:o,onTouchCancel:o}),[t,i,o]),wasTriggered:n}}();h.useEffect(()=>{if(!b)return;const e=()=>w(null);return window.addEventListener("click",e),window.addEventListener("scroll",e,!0),()=>{window.removeEventListener("click",e),window.removeEventListener("scroll",e,!0)}},[b]);const q=async(t,i)=>{var s;if(0===t.length)return;const r=i??e,n=t.reduce((e,t)=>e+t.size,0);k(!0),N({loaded:0,total:n});try{const i=await O(r,t,(e,t)=>{N({loaded:e,total:t})});r!==e&&o(e=>new Set(e).add(r)),X(r);const n=i.uploaded.length,a=(null==(s=i.skipped)?void 0:s.length)??0,l=i.errors.length;l>0?m.error(`上传完成:${n} 成功,${l} 失败${a?`,${a} 跳过`:""}`):a>0?m.info(`已上传 ${n} 个文件,${a} 个同名文件被跳过`):m.success(`已上传 ${n} 个文件`)}catch(a){console.error("[FileTree] Upload failed:",a),m.error(`上传失败: ${a.message}`)}finally{k(!1),N(null)}},Y=e=>e>=1073741824?(e/1073741824).toFixed(2)+" GB":e>=1048576?(e/1048576).toFixed(1)+" MB":e>=1024?(e/1024).toFixed(0)+" KB":e+" B",X=h.useCallback(async e=>{l(t=>{if(t.has(e))return t;const i=new Set(t);return i.add(e),i});try{const t=await R(e);r(i=>new Map(i).set(e,t.entries))}catch(t){console.error("[FileTree] Failed to load:",e,t),r(t=>new Map(t).set(e,[]))}finally{l(t=>{const i=new Set(t);return i.delete(e),i})}},[]);h.useEffect(()=>{r(new Map),o(new Set([e])),l(new Set),X(e)},[e,X]);const G=h.useCallback(e=>{o(t=>{const i=new Set(t);return i.has(e)?i.delete(e):(i.add(e),s.has(e)||X(e)),i})},[s,X]),Z=h.useCallback(()=>{r(new Map),o(new Set([e])),l(new Set),X(e)},[e,X]),J=(e,i)=>e.map(e=>{const r=n.has(e.path),o=a.has(e.path),l=s.get(e.path),c=e.name.startsWith(".");return _.jsxs("div",{children:[_.jsxs("div",{className:g("flex items-center gap-1 py-[3px] rounded cursor-pointer","hover:bg-muted-foreground/10",c&&"opacity-50"),style:{paddingLeft:14*i+6+"px",paddingRight:"6px",WebkitTouchCallout:"none"},onClick:i=>{if(V.wasTriggered.current)return V.wasTriggered.current=!1,void i.stopPropagation();"dir"===e.type?G(e.path):p(t,e.path)},onContextMenu:t=>{t.preventDefault(),w({x:t.clientX,y:t.clientY,filePath:e.path,fileName:e.name,type:e.type})},...V.bind((t,i)=>{w({x:t,y:i,filePath:e.path,fileName:e.name,type:e.type})}),children:[_.jsx("span",{className:"w-3 flex-shrink-0 text-muted-foreground",children:"dir"===e.type&&(o?_.jsx(T,{className:"h-2.5 w-2.5 animate-spin"}):r?_.jsx(ii,{className:"h-2.5 w-2.5"}):_.jsx(A,{className:"h-2.5 w-2.5"}))}),"dir"===e.type?r?_.jsx(I,{className:"h-3.5 w-3.5 text-blue-400 flex-shrink-0"}):_.jsx(z,{className:"h-3.5 w-3.5 text-blue-400 flex-shrink-0"}):qi(e.name)?_.jsx(Pt,{className:"h-3.5 w-3.5 text-green-400 flex-shrink-0"}):_.jsx(wt,{className:"h-3.5 w-3.5 text-muted-foreground flex-shrink-0"}),_.jsx("span",{className:g("text-xs truncate leading-none","dir"===e.type?"text-foreground":"text-muted-foreground"),title:e.path,children:e.name})]}),_.jsx($,{initial:!1,children:"dir"===e.type&&r&&_.jsxs(H.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.15,ease:"easeInOut"},className:"overflow-hidden",children:[!l&&!o&&_.jsx("div",{className:"text-xs text-muted-foreground/50 py-0.5",style:{paddingLeft:14*(i+1)+6+16+"px"},children:"—"}),0===(null==l?void 0:l.length)&&_.jsx("div",{className:"text-xs text-muted-foreground/50 py-0.5",style:{paddingLeft:14*(i+1)+6+16+"px"},children:"empty"}),l&&l.length>0&&J(l,i+1)]})})]},e.path)}),Q=s.get(e),ee=a.has(e),te=e.split("/").filter(Boolean).pop()??e;return _.jsxs(_.Fragment,{children:[d&&!x&&_.jsx(Ki,{filePath:d,onClose:()=>v(t,d),onMinimize:()=>y(t,d)},d),b&&_.jsxs("div",{ref:F,className:"fixed z-50 min-w-[140px] bg-popover border border-border rounded-md shadow-md py-1",style:{left:b.x,top:b.y},onClick:e=>e.stopPropagation(),children:[_.jsxs("button",{className:"flex items-center gap-2 w-full px-3 py-1.5 text-xs hover:bg-accent hover:text-accent-foreground text-left",onClick:()=>{Ui(b.filePath.startsWith(e+"/")?b.filePath.slice(e.length+1):b.filePath).then(e=>{e?m.success("已复制相对路径"):m.error("复制失败")}),w(null)},children:[_.jsx(fi,{className:"h-3.5 w-3.5"}),"复制相对路径"]}),_.jsxs("button",{className:"flex items-center gap-2 w-full px-3 py-1.5 text-xs hover:bg-accent hover:text-accent-foreground text-left",onClick:()=>{Ui(b.filePath).then(e=>{e?m.success("已复制绝对路径"):m.error("复制失败")}),w(null)},children:[_.jsx(di,{className:"h-3.5 w-3.5"}),"复制绝对路径"]}),"file"===b.type&&_.jsxs(_.Fragment,{children:[_.jsx("div",{className:"my-1 border-t border-border"}),_.jsxs("button",{className:"flex items-center gap-2 w-full px-3 py-1.5 text-xs hover:bg-accent hover:text-accent-foreground text-left",onClick:()=>{(async(e,t)=>{let i=C(e);const s=u();s&&(i+=`${i.includes("?")?"&":"?"}token=${encodeURIComponent(s)}`);const r=`${i}${i.includes("?")?"&":"?"}dl=1`;try{const e=await fetch(r,{method:"HEAD"});if(!e.ok)return void m.error(`下载失败 (${e.status})`)}catch{return void m.error("下载失败:网络错误")}const n=document.createElement("a");n.href=r,n.download=t,document.body.appendChild(n),n.click(),document.body.removeChild(n)})(b.filePath,b.fileName),w(null)},children:[_.jsx(P,{className:"h-3.5 w-3.5"}),"下载"]})]}),"dir"===b.type&&_.jsxs(_.Fragment,{children:[_.jsx("div",{className:"my-1 border-t border-border"}),_.jsxs("button",{className:"flex items-center gap-2 w-full px-3 py-1.5 text-xs hover:bg-accent hover:text-accent-foreground text-left",disabled:S,onClick:()=>{var e;U.current=b.filePath,w(null),null==(e=K.current)||e.click()},children:[_.jsx(Ot,{className:"h-3.5 w-3.5"}),"上传文件到此文件夹"]})]}),_.jsx("div",{className:"my-1 border-t border-border"}),_.jsxs("button",{className:"flex items-center gap-2 w-full px-3 py-1.5 text-xs hover:bg-destructive/80 hover:text-destructive-foreground text-left",onClick:()=>{(async(t,i,r)=>{const n="dir"===r?`文件夹 "${i}" 及其所有内容`:`文件 "${i}"`;if(await W({title:"确认删除",description:`确认删除${n}?此操作不可撤销。`,destructive:!0,confirmLabel:"删除"}))try{await B(t),m.success(`已删除: ${i}`);const r=t.substring(0,t.lastIndexOf("/"));r&&s.has(r)?X(r):X(e)}catch(o){m.error(`删除失败: ${o.message}`)}})(b.filePath,b.fileName,b.type),w(null)},children:[_.jsx(L,{className:"h-3.5 w-3.5"}),"删除"]})]}),_.jsxs("div",{className:"h-full flex flex-col text-foreground select-none",children:[_.jsxs("div",{className:"flex items-center justify-between px-3 h-9 border-b border-border flex-shrink-0",children:[_.jsx("span",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Files"}),_.jsxs("div",{className:"flex items-center gap-0.5",children:[_.jsx("input",{ref:K,type:"file",multiple:!0,className:"hidden",onChange:e=>{const t=Array.from(e.target.files??[]),i=U.current;U.current=null,t.length>0&&q(t,i??void 0),e.target.value=""}}),_.jsx("button",{className:"text-muted-foreground hover:text-foreground p-0.5 rounded transition-colors",onClick:()=>{var e;U.current=null,null==(e=K.current)||e.click()},disabled:S,title:"上传文件",children:_.jsx(Ot,{className:g("h-3 w-3",S&&"animate-pulse")})}),_.jsx("button",{className:"text-muted-foreground hover:text-foreground p-0.5 rounded transition-colors",onClick:Z,title:"Refresh file tree",children:_.jsx(T,{className:g("h-3 w-3",ee&&"animate-spin")})})]})]}),_.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-2 border-b border-border flex-shrink-0",children:[_.jsx(I,{className:"h-3.5 w-3.5 text-blue-400 flex-shrink-0"}),_.jsx("span",{className:"text-xs text-foreground font-medium truncate",title:e,children:te})]}),_.jsxs("div",{className:g("flex-1 overflow-y-auto py-1 min-h-0 transition-colors",M&&"bg-accent/30 ring-1 ring-inset ring-accent"),onDragOver:e=>{e.preventDefault(),j(!0)},onDragEnter:e=>{e.preventDefault(),j(!0)},onDragLeave:()=>j(!1),onDrop:e=>{e.preventDefault(),j(!1);const t=Array.from(e.dataTransfer.files);t.length>0&&q(t)},children:[S&&E&&_.jsxs("div",{className:"px-3 py-2 border-b border-border space-y-1",children:[_.jsxs("div",{className:"flex items-center justify-between text-[10px] text-muted-foreground",children:[_.jsxs("span",{children:["上传中 ",Math.floor(E.loaded/Math.max(E.total,1)*100),"%"]}),_.jsxs("span",{className:"font-mono",children:[Y(E.loaded)," / ",Y(E.total)]})]}),_.jsx("div",{className:"h-1 bg-muted rounded-full overflow-hidden",children:_.jsx("div",{className:"h-full bg-primary transition-[width] duration-150",style:{width:E.loaded/Math.max(E.total,1)*100+"%"}})})]}),M&&!S&&_.jsx("div",{className:"text-xs text-muted-foreground px-4 py-1",children:"松开以上传文件"}),ee&&!Q?_.jsx("div",{className:"text-xs text-muted-foreground px-4 py-3",children:"Loading…"}):Q&&0!==Q.length?J(Q,0):_.jsx("div",{className:"text-xs text-muted-foreground px-4 py-3",children:"Empty folder"})]})]})]})}function Xi(e){const t=new Date(e),i=Date.now()-t.getTime();return i<36e5?`${Math.floor(i/6e4)}分钟前`:i<864e5?`${Math.floor(i/36e5)}小时前`:i<6048e5?`${Math.floor(i/864e5)}天前`:t.toLocaleDateString()}function Gi({projectId:e}){const[t,i]=h.useState(null),[s,r]=h.useState(!0),[n,o]=h.useState(null),[a,l]=h.useState(null),[c,d]=h.useState(""),[u,f]=h.useState(!1),[p,v]=h.useState([]),[y,x]=h.useState(0),[b,w]=h.useState(!0),[S,C]=h.useState(!1),k=h.useCallback(async()=>{r(!0);try{i(await W(e))}catch{i(null)}finally{r(!1)}},[e]),E=h.useCallback(async(t=!1)=>{C(!0);try{const i=t?p.length:0,s=await F(e,30,i);v(e=>t?[...e,...s.commits]:s.commits),x(s.total)}catch{}finally{C(!1)}},[e,p.length]);h.useEffect(()=>{k(),E()},[e]);const N=async t=>{try{const{diff:i}=await Y(e,t);o(i||"(no diff)"),l(t??"all changes")}catch{m.error("获取 diff 失败")}},M=async t=>{try{await X(e,[t]),m.success(`已暂存 ${t}`),await k()}catch{m.error("git add 失败")}},j=async()=>{if(c.trim()){f(!0);try{await G(e,c),m.success("提交成功"),d(""),await k()}catch(t){m.error(t instanceof Error?t.message:"提交失败")}finally{f(!1)}}};if(!t&&s)return _.jsxs("div",{className:"flex flex-col items-center gap-2 py-8 text-muted-foreground/50 text-xs",children:[_.jsx(_i,{className:"h-5 w-5"}),_.jsx("p",{children:"加载中…"})]});if(!t||!t.isRepo)return _.jsxs("div",{className:"flex flex-col items-center gap-2 py-8 text-muted-foreground/50 text-xs",children:[_.jsx(_i,{className:"h-5 w-5"}),_.jsx("p",{children:t?"非 Git 仓库":"加载失败"}),_.jsx(K,{variant:"ghost",size:"sm",className:"h-6 text-xs",onClick:()=>{k()},children:"重试"})]});const D=[...t.modified??[],...t.deleted??[]],R=t.staged??[],P=t.untracked??[];return _.jsxs("div",{className:"flex flex-col h-full overflow-y-auto p-2 space-y-2 text-xs",children:[_.jsxs("div",{className:"flex items-center justify-between",children:[_.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground font-medium",children:[_.jsx(_i,{className:"h-3 w-3"}),_.jsx("span",{children:t.branch}),(t.ahead??0)>0&&_.jsxs("span",{className:"text-blue-400",children:["↑",t.ahead]}),(t.behind??0)>0&&_.jsxs("span",{className:"text-yellow-400",children:["↓",t.behind]})]}),_.jsx(K,{variant:"ghost",size:"icon",className:"h-5 w-5",onClick:()=>{k()},disabled:s,children:_.jsx(T,{className:g("h-3 w-3",s&&"animate-spin")})})]}),R.length>0&&_.jsxs("div",{children:[_.jsxs("div",{className:"text-muted-foreground mb-1 font-medium",children:["已暂存 (",R.length,")"]}),R.map(e=>_.jsxs("div",{className:"flex items-center gap-1 py-0.5 px-1 rounded hover:bg-muted-foreground/10",children:[_.jsx(U,{className:"h-2.5 w-2.5 text-green-500 flex-shrink-0"}),_.jsx("button",{className:"flex-1 text-left truncate text-green-400",onClick:()=>{N(e)},children:e})]},e))]}),D.length>0&&_.jsxs("div",{children:[_.jsxs("div",{className:"text-muted-foreground mb-1 font-medium",children:["未暂存 (",D.length,")"]}),D.map(e=>_.jsxs("div",{className:"flex items-center gap-1 py-0.5 px-1 rounded hover:bg-muted-foreground/10",children:[_.jsx("button",{className:"flex-shrink-0 h-4 w-4 flex items-center justify-center rounded hover:bg-green-500/20 text-muted-foreground hover:text-green-400",title:"git add",onClick:()=>{M(e)},children:_.jsx(V,{className:"h-2.5 w-2.5"})}),_.jsx("button",{className:"flex-1 text-left truncate text-yellow-400",onClick:()=>{N(e)},children:e})]},e))]}),P.length>0&&_.jsxs("div",{children:[_.jsxs("div",{className:"text-muted-foreground mb-1 font-medium",children:["未跟踪 (",P.length,")"]}),P.map(e=>_.jsxs("div",{className:"flex items-center gap-1 py-0.5 px-1 rounded hover:bg-muted-foreground/10",children:[_.jsx("button",{className:"flex-shrink-0 h-4 w-4 flex items-center justify-center rounded hover:bg-green-500/20 text-muted-foreground hover:text-green-400",title:"git add",onClick:()=>{M(e)},children:_.jsx(V,{className:"h-2.5 w-2.5"})}),_.jsx("span",{className:"flex-1 truncate text-muted-foreground",children:e})]},e))]}),0===D.length&&0===R.length&&0===P.length&&_.jsx("p",{className:"text-muted-foreground/50 text-center py-4",children:"工作区干净"}),R.length>0&&_.jsxs("div",{className:"space-y-1.5 pt-1 border-t border-border",children:[_.jsx(q,{placeholder:"提交消息…",value:c,onChange:e=>d(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||j()},className:"h-7 text-xs"}),_.jsx(K,{size:"sm",className:"w-full h-7 text-xs",onClick:()=>{j()},disabled:!c.trim()||u,children:u?"提交中…":`提交 (${R.length} 文件)`})]}),(null==t?void 0:t.isRepo)&&_.jsxs("div",{className:"border-t border-border pt-2",children:[_.jsxs("button",{className:"flex items-center gap-1 text-muted-foreground font-medium mb-1 w-full text-left",onClick:()=>w(e=>!e),children:[_.jsx(ii,{className:g("h-3 w-3 transition-transform",!b&&"-rotate-90")}),_.jsx(gi,{className:"h-3 w-3"}),_.jsxs("span",{children:["提交历史 (",y,")"]})]}),b&&_.jsxs("div",{className:"space-y-0.5",children:[p.map((e,t)=>{const i=e.parents.length>1;return _.jsxs("div",{className:"flex gap-1.5 items-start group",children:[_.jsxs("div",{className:"flex flex-col items-center flex-shrink-0 w-3",children:[_.jsx("div",{className:g("w-2 h-2 rounded-full flex-shrink-0 mt-1",0===t?"bg-blue-400":i?"bg-purple-400":"bg-muted-foreground/40")}),t<p.length-1&&_.jsx("div",{className:"w-px flex-1 bg-border min-h-[12px]"})]}),_.jsxs("div",{className:"flex-1 min-w-0 pb-1",children:[_.jsxs("div",{className:"flex items-baseline gap-1",children:[_.jsx("span",{className:"font-mono text-muted-foreground/60 text-[10px] flex-shrink-0",children:e.hashShort}),_.jsx("span",{className:"truncate leading-tight",children:e.message.split("\n")[0]})]}),_.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] text-muted-foreground/50 mt-0.5",children:[_.jsx("span",{children:e.author}),_.jsx("span",{children:Xi(e.date)}),e.branches.length>0&&e.branches.slice(0,2).map(e=>_.jsx("span",{className:"px-1 py-px rounded bg-blue-500/10 text-blue-400 text-[9px]",children:e.replace("remotes/origin/","↑")},e))]})]})]},e.hash)}),p.length<y&&_.jsx("button",{className:"w-full text-center text-[10px] text-muted-foreground hover:text-foreground py-1",onClick:()=>{E(!0)},disabled:S,children:S?"加载中...":`加载更多 (${p.length}/${y})`})]})]}),null!==n&&_.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",onClick:()=>o(null),children:[_.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),_.jsxs("div",{className:"relative z-10 w-[700px] max-w-[95vw] max-h-[80vh] flex flex-col bg-background border border-border rounded-xl shadow-sm",onClick:e=>e.stopPropagation(),children:[_.jsxs("div",{className:"flex items-center justify-between px-4 h-10 border-b border-border text-sm font-medium flex-shrink-0",children:[_.jsx("span",{className:"truncate text-muted-foreground",children:a}),_.jsx("button",{className:"text-muted-foreground hover:text-foreground",onClick:()=>o(null),children:"✕"})]}),_.jsx("pre",{className:"flex-1 overflow-auto p-3 text-[11px] font-mono whitespace-pre leading-relaxed",children:n.split("\n").map((e,t)=>_.jsx("span",{className:g("block",e.startsWith("+")&&!e.startsWith("+++")&&"text-green-400 bg-green-400/5",e.startsWith("-")&&!e.startsWith("---")&&"text-red-400 bg-red-400/5",e.startsWith("@@")&&"text-blue-400"),children:e},t))})]})]})]})}function Zi(e){if(!e)return"-";const t=e-Date.now(),i=Math.abs(t),s=t<0,r=Math.round(i/1e3);if(r<60)return s?`${r} 秒前`:`${r} 秒后`;const n=Math.round(r/60);if(n<60)return s?`${n} 分钟前`:`${n} 分钟后`;const o=Math.round(n/60);if(o<24)return s?`${o} 小时前`:`${o} 小时后`;const a=Math.round(o/24);return s?`${a} 天前`:`${a} 天后`}function Ji(e){if(!e)return"";return new Date(e).toLocaleString(void 0,{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"})}function Qi({projectId:e}){const[t,i]=h.useState(null),[s,r]=h.useState(!0),[n,o]=h.useState(null),[,a]=h.useState(0),l=h.useRef(!0),c=h.useRef(0),d=h.useCallback(async()=>{const t=++c.current;r(!0),o(null);try{const{tasks:s}=await Z(e);if(!l.current||t!==c.current)return;i(s)}catch(ll){if(!l.current||t!==c.current)return;o(ll.message),i([])}finally{l.current&&t===c.current&&r(!1)}},[e]);return h.useEffect(()=>{l.current=!0,d();const e=setInterval(()=>{d()},3e4),t=setInterval(()=>a(e=>e+1),1e3);return()=>{l.current=!1,clearInterval(e),clearInterval(t)}},[d]),_.jsxs("div",{className:"h-full flex flex-col bg-muted text-foreground overflow-hidden",children:[_.jsxs("div",{className:"flex-shrink-0 px-3 py-2 flex items-center justify-between border-b border-border",children:[_.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium text-muted-foreground",children:[_.jsx(Lt,{className:"size-4"}),_.jsx("span",{children:"已排程任务"})]}),_.jsx(K,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{d()},title:"刷新","aria-label":"刷新",children:_.jsx(T,{className:g("size-3.5",s&&"animate-spin")})})]}),_.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-2 space-y-1.5",children:[_.jsxs("div",{className:"rounded-md bg-muted-foreground/5 px-2 py-1.5 text-[11px] text-muted-foreground flex items-start gap-1.5",children:[_.jsx(vi,{className:"size-3 mt-0.5 shrink-0"}),_.jsxs("span",{className:"leading-snug",children:["best-effort 重建:从 session JSONL 反推「Claude 创建过的 schedule」,",_.jsx("strong",{className:"text-foreground/80",children:"不是"}),"权威活动列表。已触发 / 已删除 无法直接观测。"]})]}),n&&_.jsx("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 text-destructive p-2 text-xs",children:n}),!n&&t&&0===t.length&&!s&&_.jsxs("div",{className:"px-2 py-6 text-center text-xs text-muted-foreground",children:[_.jsx("p",{children:"本项目最近 7 天没有创建过 schedule。"}),_.jsx("p",{className:"mt-2 leading-relaxed",children:"一次性 ScheduleWakeup 触发时间过了的会被隐藏(认为已触发); CronCreate 仅显示 7 天内创建的(与 Claude 自动过期窗口对齐)。"})]}),t&&t.map(e=>{const t=e.nextFireAt?Date.parse(e.nextFireAt):null,i="CronCreate"===e.type&&(e.recurring||/[,*\/-]/.test(e.cron??"")),s="ScheduleWakeup"===e.type&&null!==e.delaySeconds?function(e){if(e<60)return`${e} 秒后`;const t=Math.round(e/60);return t<60?`${t} 分钟后`:Math.round(t/60*10)/10+" 小时后"}(e.delaySeconds):e.cron??"?";return _.jsx("div",{className:"rounded-md border border-border bg-background px-2.5 py-2 text-xs",children:_.jsxs("div",{className:"flex items-start gap-2",children:[_.jsx("div",{className:"shrink-0 mt-0.5 text-muted-foreground",children:i?_.jsx(Ni,{className:"size-3.5"}):_.jsx(J,{className:"size-3.5"})}),_.jsxs("div",{className:"flex-1 min-w-0",children:[_.jsxs("div",{className:"flex flex-wrap items-center gap-1 mb-1",children:[_.jsx("span",{className:"text-[10px] font-mono px-1.5 rounded bg-muted-foreground/10 text-muted-foreground",children:"ScheduleWakeup"===e.type?"SW":"CC"}),e.durable&&_.jsx("span",{className:"text-[10px] px-1.5 rounded bg-primary/10 text-primary",children:"durable"}),_.jsx("code",{className:"text-[10px] bg-muted-foreground/10 px-1 rounded font-mono",children:s})]}),_.jsx("div",{className:"font-medium text-foreground line-clamp-2 leading-snug",children:e.prompt.trim()||"(无 prompt)"}),e.reason&&_.jsxs("div",{className:"mt-0.5 text-muted-foreground line-clamp-1 italic text-[11px]",children:["reason: ",e.reason]}),_.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-x-3 gap-y-0.5 text-[11px] text-muted-foreground",children:[null!==t&&_.jsxs("span",{title:Ji(t),children:["下次: ",_.jsx("span",{className:"text-foreground/90",children:Zi(t)})]}),_.jsxs("span",{title:Ji(e.createdAt),children:["创建: ",Zi(e.createdAt)]}),_.jsx("span",{className:"font-mono text-muted-foreground/70",children:e.sessionId.slice(0,8)})]})]})]})},`${e.sessionId}:${e.id}`)}),s&&!t&&_.jsx("div",{className:"space-y-1.5",children:[0,1].map(e=>_.jsx("div",{className:"rounded-md border border-border bg-background px-2.5 py-2 h-16 animate-pulse"},e))})]})]})}function es(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:e<1073741824?`${(e/1024/1024).toFixed(1)} MB`:`${(e/1024/1024/1024).toFixed(2)} GB`}function ts(e){if(!e)return"-";const t=e-Date.now(),i=Math.abs(t),s=t<0,r=Math.round(i/1e3);if(r<60)return s?`${r} 秒前`:`${r} 秒后`;const n=Math.round(r/60);if(n<60)return s?`${n} 分钟前`:`${n} 分钟后`;const o=Math.round(n/60);if(o<24)return s?`${o} 小时前`:`${o} 小时后`;const a=Math.round(o/24);return s?`${a} 天前`:`${a} 天后`}function is(e){return new Date(e).toLocaleString(void 0,{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"})}function ss({projectId:e}){const[t,i]=h.useState(null),[s,r]=h.useState(!0),[n,o]=h.useState(!1),[a,l]=h.useState(null),[,c]=h.useState(0),d=h.useRef(!0),u=h.useCallback(async()=>{l(null);try{const t=await Q(e);if(!d.current)return;i(t)}catch(ll){if(!d.current)return;l(ll.message)}finally{d.current&&r(!1)}},[e]),f=h.useCallback(async()=>{o(!0);try{const t=await ee(e);if(!d.current)return;const i=[];t.copied>0&&i.push(`新增/更新 ${t.copied}`),t.deleted>0&&i.push(`删除 ${t.deleted}`),t.skipped>0&&i.push(`跳过 ${t.skipped}`),m.success(`同步完成:${i.join("·")||"无变化"}`),await u()}catch(ll){m.error(`同步失败:${ll.message}`)}finally{d.current&&o(!1)}},[e,u]);h.useEffect(()=>{d.current=!0,u();const e=setInterval(()=>{u()},3e4),t=setInterval(()=>c(e=>e+1),5e3);return()=>{d.current=!1,clearInterval(e),clearInterval(t)}},[u]);const p=(null==t?void 0:t.files.reduce((e,t)=>e+t.bytes,0))??0;return _.jsxs("div",{className:"h-full flex flex-col bg-muted text-foreground overflow-hidden",children:[_.jsxs("div",{className:"flex-shrink-0 px-3 py-2 flex items-center justify-between border-b border-border",children:[_.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium text-muted-foreground",children:[_.jsx(te,{className:"size-4"}),_.jsx("span",{children:"聊天记录备份"})]}),_.jsx(K,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{u()},title:"刷新","aria-label":"刷新",disabled:s,children:_.jsx(T,{className:g("size-3.5",s&&"animate-spin")})})]}),_.jsx("div",{className:"flex-shrink-0 px-3 py-2 border-b border-border bg-background/40",children:_.jsxs("div",{className:"flex items-center justify-between gap-2",children:[_.jsxs("div",{className:"text-[11px] text-muted-foreground min-w-0",children:[_.jsxs("div",{children:["最后同步:"," ",_.jsx("span",{className:"text-foreground/90",title:(null==t?void 0:t.meta)?is(t.meta.lastBackupAt):void 0,children:(null==t?void 0:t.meta)?ts(t.meta.lastBackupAt):"从未同步"})]}),t&&_.jsxs("div",{className:"mt-0.5 text-muted-foreground/80",children:[t.files.length," 个文件 · ",es(p)]})]}),_.jsx(K,{size:"sm",className:"h-7 px-2.5 text-xs",onClick:()=>{f()},disabled:n||!(null==t?void 0:t.supported),children:n?"同步中…":"立即同步"})]})}),_.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-2 space-y-1",children:[a&&_.jsxs("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 text-destructive p-2 text-xs flex items-start gap-2",children:[_.jsx(ai,{className:"size-3.5 shrink-0 mt-0.5"}),_.jsx("span",{children:a})]}),t&&!t.supported&&_.jsx("div",{className:"px-2 py-6 text-center text-xs text-muted-foreground",children:_.jsxs("p",{children:["此项目使用 ",_.jsx("code",{className:"text-[10px] bg-muted-foreground/10 px-1 rounded",children:"terminal"})," 模式,无聊天记录需备份。"]})}),(null==t?void 0:t.supported)&&0===t.files.length&&!s&&!a&&_.jsxs("div",{className:"px-2 py-6 text-center text-xs text-muted-foreground",children:[_.jsx("p",{children:"暂无已备份的聊天记录"}),_.jsx("p",{className:"mt-2 leading-relaxed text-muted-foreground/80",children:'定时每 5 分钟同步一次,也可点击右上方"立即同步"手动触发。'}),_.jsxs("p",{className:"mt-1 text-muted-foreground/70",children:["备份路径: ",_.jsx("code",{className:"text-[10px] bg-muted-foreground/10 px-1 rounded break-all",children:t.backupDir})]})]}),null==t?void 0:t.files.map(e=>_.jsxs("div",{className:"rounded-md border border-border bg-background px-2.5 py-1.5 text-xs flex items-center gap-2 hover:bg-accent/50 transition-colors",children:[_.jsx(wt,{className:"size-3.5 shrink-0 text-muted-foreground"}),_.jsxs("div",{className:"flex-1 min-w-0",children:[_.jsx("div",{className:"font-mono text-[11px] text-foreground truncate",title:e.name,children:e.name}),_.jsxs("div",{className:"text-muted-foreground/80 text-[10px] flex items-center gap-2",children:[_.jsx("span",{title:is(e.mtime),children:ts(e.mtime)}),_.jsx("span",{className:"text-muted-foreground/40",children:"·"}),_.jsx("span",{children:es(e.bytes)})]})]})]},e.name)),s&&!t&&_.jsx("div",{className:"space-y-1",children:[0,1].map(e=>_.jsx("div",{className:"rounded-md border border-border bg-background h-10 animate-pulse"},e))})]})]})}async function rs(e,t,i){const s={"Content-Type":"application/json"},r=u();r&&(s.Authorization=`Bearer ${r}`);const n=await fetch(t,{method:e,headers:s,body:void 0!==i?JSON.stringify(i):void 0});if(!n.ok){let e,t=`HTTP ${n.status}`;try{e=await n.json();const i=e;(null==i?void 0:i.error)&&(t=i.error)}catch{}const i=new Error(t);throw i.status=n.status,i.detail=e,i}return n.json()}function ns(e,t){return rs("GET",`/api/projects/${e}/track-flows/file/${encodeURIComponent(t)}`)}function os(e,t,i,s,r){const n={flow:i};return void 0!==s&&(n.trainJson=s),(null==r?void 0:r.createOnly)&&(n.createOnly=!0),rs("PUT",`/api/projects/${e}/track-flows/file/${encodeURIComponent(t)}`,n)}function as(e,t,i){return rs("POST",`/api/projects/${e}/track-flows/file/${encodeURIComponent(t)}/cancel`,i?{runId:i}:{})}function ls(e,t){return rs("GET",`/api/projects/${e}/track-flows/runs/${encodeURIComponent(t)}/state`)}function cs(e){return`${e}_${"undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID().replace(/-/g,"").slice(0,6):Math.random().toString(36).slice(2,8)}`}function hs(e,t="claude-code"){return{version:3,trackName:e,adapter:t,variables:[],nodes:[],edges:[]}}function ds(e){if(!e||"object"!=typeof e)return{ok:!1,reason:"not an object"};const t=e;return 3!==t.version?{ok:!1,reason:`unsupported version: ${t.version}`}:"string"!=typeof t.trackName?{ok:!1,reason:"trackName missing"}:"string"!=typeof t.adapter?{ok:!1,reason:"adapter missing"}:Array.isArray(t.variables)&&Array.isArray(t.nodes)&&Array.isArray(t.edges)?{ok:!0,flow:t}:{ok:!1,reason:"variables/nodes/edges must be arrays"}}function us(e){const t={};for(const i of e)t[i.key]=i.initialValue??null;return t}const fs=28;function ps({flow:e,nodeStates:t,currentNodeId:i,status:s,onClose:r,embedded:n}){if(0===e.nodes.length)return null;const o=n?240:320,a=n?320:240,l=e.nodes.map(e=>e.position.x),c=e.nodes.map(e=>e.position.y),h=Math.min(...l),d=Math.max(...l),u=Math.min(...c),f=Math.max(...c),p=Math.max(1,d-h)+240,m=Math.max(1,f-u)+100,g=Math.min((o-24-80)/p,(a-24-fs)/m);function v(e){return 12+(e-h)*g}function y(e){return 12+(e-u)*g}function x(e){return{x:v(e.position.x)+40,y:y(e.position.y)+14}}const b=n?"w-full overflow-hidden rounded-md border border-border bg-card text-muted-foreground":"fixed bottom-4 right-4 z-40 rounded-lg shadow-lg border border-border backdrop-blur-md bg-card/70 text-muted-foreground";return _.jsxs("div",{className:b,style:n?void 0:{width:o},children:[_.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 border-b border-border",children:[_.jsxs("div",{className:"flex items-center gap-2 text-xs min-w-0",children:[_.jsx("span",{className:_s(s)}),_.jsx("span",{className:"font-medium text-foreground truncate",children:e.trackName}),_.jsx("span",{className:"text-muted-foreground shrink-0",children:(w=s,"running"===w?"运行中":"waiting_user_input"===w?"等待输入":"completed"===w?"已完成":"failed"===w?"失败":"已取消")})]}),_.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[("running"===s||"waiting_user_input"===s)&&_.jsx(K,{type:"button",variant:"destructive",size:"icon",onClick:()=>window.dispatchEvent(new CustomEvent("ccweb:flow-cancel-request")),title:"取消运行",className:"h-5 w-5",children:_.jsx(ji,{className:"h-2.5 w-2.5 fill-current"})}),r&&!n&&_.jsx(K,{type:"button",variant:"ghost",size:"icon",onClick:r,title:"关闭",className:"h-5 w-5",children:_.jsx(S,{className:"h-3 w-3"})})]})]}),_.jsxs("svg",{viewBox:`0 0 ${o} ${a}`,width:n?"100%":o,height:n?void 0:a,preserveAspectRatio:"xMinYMin meet",className:"block",children:[_.jsx("defs",{children:_.jsx("marker",{id:"mm-arrow",viewBox:"0 0 10 10",refX:"8",refY:"5",markerWidth:"6",markerHeight:"6",orient:"auto",children:_.jsx("path",{d:"M 0 0 L 10 5 L 0 10 z",fill:"currentColor"})})}),e.edges.map(t=>{const i=e.nodes.find(e=>e.id===t.source),s=t.target?e.nodes.find(e=>e.id===t.target):null;if(!i)return null;const r=x(i),n=s?x(s):{x:r.x,y:r.y+30},o="true"===t.sourceHandle?"stroke-emerald-500 dark:stroke-emerald-400":"false"===t.sourceHandle?"stroke-red-500 dark:stroke-red-400":"stroke-muted-foreground/60";return _.jsx("line",{x1:r.x,y1:r.y+14,x2:n.x,y2:s?n.y-14:n.y,className:o,strokeWidth:1.5,strokeDasharray:s?void 0:"3 3",markerEnd:"url(#mm-arrow)"},t.id)}),e.nodes.map(e=>{var s;const r=v(e.position.x),n=y(e.position.y),o=t.get(e.id)??null,a=i===e.id,{fillClass:l,strokeClass:c,textClass:h}=function(e,t,i){if("active"===t||i)return{fillClass:"fill-amber-100 dark:fill-amber-900/50",strokeClass:"stroke-amber-500",textClass:"fill-amber-900 dark:fill-amber-100"};if("completed"===t)return{fillClass:"fill-emerald-100 dark:fill-emerald-900/50",strokeClass:"stroke-emerald-500",textClass:"fill-emerald-900 dark:fill-emerald-100"};if("failed"===t)return{fillClass:"fill-red-100 dark:fill-red-900/50",strokeClass:"stroke-red-500",textClass:"fill-red-900 dark:fill-red-100"};if("skipped"===t)return{fillClass:"fill-muted dark:fill-muted",strokeClass:"stroke-muted-foreground/60",textClass:"fill-muted-foreground"};return"user_input"===e?{fillClass:"fill-pink-100 dark:fill-pink-900/40",strokeClass:"stroke-pink-400 dark:stroke-pink-700",textClass:"fill-foreground/80"}:"llm"===e?{fillClass:"fill-orange-100 dark:fill-orange-900/40",strokeClass:"stroke-orange-400 dark:stroke-orange-700",textClass:"fill-foreground/80"}:{fillClass:"fill-sky-100 dark:fill-sky-900/40",strokeClass:"stroke-sky-400 dark:stroke-sky-700",textClass:"fill-foreground/80"}}(e.type,o,a),d=(null==(s=e.label)?void 0:s.trim())||("user_input"===(u=e.type)?"用户输入":"llm"===u?"LLM":"判断");var u;return _.jsxs("g",{children:[_.jsx("rect",{x:r,y:n,width:80,height:fs,rx:6,ry:6,className:`${l} ${c}`,strokeWidth:a?2:1,style:a?{animationDuration:"1.5s"}:void 0,children:a&&_.jsx("animate",{attributeName:"opacity",values:"1;0.55;1",dur:"1.5s",repeatCount:"indefinite"})}),_.jsx("text",{x:r+40,y:n+14+1,textAnchor:"middle",dominantBaseline:"middle",className:`text-[10px] font-mono select-none ${h}`,children:ms(d,10)})]},e.id)})]})]});var w}function ms(e,t){return e.length>t?e.slice(0,t-1)+"…":e}function _s(e){const t="inline-block w-2 h-2 rounded-full shrink-0";return"running"===e?`${t} bg-amber-500 animate-pulse`:"waiting_user_input"===e?`${t} bg-sky-500`:"completed"===e?`${t} bg-emerald-500`:"failed"===e?`${t} bg-destructive`:`${t} bg-muted-foreground`}const gs=/^[a-zA-Z0-9_一-鿿぀-ヿㇰ-ㇿ-]+$/;function vs({projectId:e,onOpenEditor:t}){const i=c(),[s,r]=h.useState([]),[n,o]=h.useState(!1),[a,l]=h.useState(null),[d,u]=h.useState(!1),[f,p]=h.useState(null),[g,v]=h.useState(!1),[y,x]=h.useState(""),[b,w]=h.useState(null),C=h.useCallback(async()=>{o(!0),l(null);try{const t=await function(e){return rs("GET",`/api/projects/${e}/track-flows`)}(e);r(t.files)}catch(ll){l(ll.message)}finally{o(!1)}},[e]);h.useEffect(()=>{C()},[C]),h.useEffect(()=>{const e=()=>{C()};return window.addEventListener("ccweb:track-editor-closed",e),()=>window.removeEventListener("ccweb:track-editor-closed",e)},[C]),h.useEffect(()=>{let t=null,i=null;const s=()=>{i&&(clearTimeout(i),i=null)},r=r=>{const n=r.detail;if((null==n?void 0:n.type)&&(!n.type.startsWith("flow_")||n.runId)){if("flow_started"===n.type&&n.basename&&n.runId){s(),t=n.runId;const i=n.runId,r=n.basename;return p({flow:null,runId:i,basename:r,currentNodeId:null,nodeStates:new Map,status:"running"}),void(async()=>{try{const[s,n]=await Promise.all([ns(e,`${r}.flow`),ls(e,i)]);if(t!==i)return;const o=ds(s.flow);if(!o.ok||!o.flow)return;p(e=>{if(!e||e.runId!==i)return e;const t=new Map(Object.entries(n.nodeStates));for(const[i,s]of e.nodeStates)t.set(i,s);return{...e,flow:o.flow,currentNodeId:e.currentNodeId??n.currentNodeId,nodeStates:t}})}catch{}})()}if(p(e=>{if(!e)return e;if(n.runId!==e.runId)return e;if("flow_node_active"===n.type&&n.nodeId){const t=new Map(e.nodeStates);return t.set(n.nodeId,"active"),{...e,nodeStates:t,currentNodeId:n.nodeId,status:"running"}}if("flow_node_completed"===n.type&&n.nodeId){const t=new Map(e.nodeStates);return t.set(n.nodeId,"completed"),{...e,nodeStates:t}}if("flow_node_failed"===n.type&&n.nodeId){const t=new Map(e.nodeStates);return t.set(n.nodeId,"failed"),{...e,nodeStates:t,status:"failed",currentNodeId:null}}return"flow_user_input_required"===n.type?{...e,status:"waiting_user_input"}:"flow_done"===n.type?{...e,status:"completed",currentNodeId:null}:"flow_cancelled"===n.type?{...e,status:"cancelled",currentNodeId:null}:e}),"flow_done"===n.type||"flow_cancelled"===n.type||"flow_error"===n.type||"flow_node_failed"===n.type){const e=n.runId;s(),i=setTimeout(()=>{p(t=>t&&t.runId===e?null:t),i=null},3e3)}}};return window.addEventListener("ccweb:flow-msg",r),()=>{window.removeEventListener("ccweb:flow-msg",r),s()}},[e]);const k=async()=>{var i;const r=y.trim();if(r)if(gs.test(r))if(s.some(e=>e.filename===`${r}.flow`))w(`工作轨 "${r}" 已存在,请用不同名字`);else{u(!0),w(null);try{const i=hs(r),s=us(i.variables);await os(e,`${r}.flow`,i,s,{createOnly:!0}),await C(),v(!1),x(""),t(`${r}.flow`)}catch(ll){const t=ll;"FLOW_FILE_EXISTS"===(null==(i=t.detail)?void 0:i.code)?w(`工作轨 "${r}" 已存在(backend 二道闸拦截)`):w(t.message)}finally{u(!1)}}else w("名字只允许字母/数字/下划线/中文/连字符");else w("工作轨名不能为空")},E=async(t,s)=>{var r;s.stopPropagation();if(await i({description:`删除 ${t}?`,confirmLabel:"删除",destructive:!0}))try{await function(e,t){return rs("DELETE",`/api/projects/${e}/track-flows/file/${encodeURIComponent(t)}`)}(e,t),await C()}catch(n){const e=n;"FLOW_RUN_ACTIVE"===(null==(r=e.detail)?void 0:r.code)?m.error(`${t} 正在运行,请先取消运行再删除`):m.error(e.message)}};return f&&f.flow?_.jsxs("div",{className:"h-full flex flex-col p-2 gap-2 overflow-y-auto bg-background",children:[_.jsxs("div",{className:"text-xs text-muted-foreground px-1 flex items-center gap-1",children:[_.jsx(Di,{className:"h-3 w-3"}),"运行中"]}),_.jsx(ps,{flow:f.flow,nodeStates:f.nodeStates,currentNodeId:f.currentNodeId,status:f.status,embedded:!0}),_.jsx(K,{type:"button",variant:"link",size:"sm",onClick:()=>t(`${f.basename}.flow`),className:"h-7 justify-start px-1 text-xs",children:"打开编辑页查看详情 →"})]}):_.jsxs("div",{className:"h-full flex flex-col overflow-hidden bg-background",children:[_.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5 border-b border-border",children:[_.jsx(Di,{className:"h-3.5 w-3.5 text-muted-foreground"}),_.jsx("div",{className:"text-xs font-medium flex-1 text-foreground",children:"工作轨"}),_.jsx(K,{type:"button",size:"sm",onClick:()=>{x(""),w(null),v(!0)},disabled:d,className:"h-6 px-2 text-xs",children:d?_.jsx(ie,{className:"h-3 w-3 animate-spin"}):_.jsxs(_.Fragment,{children:[_.jsx(V,{className:"h-3 w-3 mr-0.5"}),"新建"]})})]}),_.jsxs("div",{className:"flex-1 overflow-y-auto p-1",children:[n&&_.jsx("div",{className:"text-xs text-muted-foreground p-2",children:"加载中…"}),a&&_.jsxs("div",{className:"text-xs text-destructive p-2",children:["错误:",a]}),!n&&!a&&0===s.length&&_.jsx("div",{className:"text-xs text-muted-foreground p-2 text-center",children:"暂无工作轨。"}),s.map(e=>_.jsxs("div",{className:"flex items-center gap-1 px-1.5 py-1 rounded-md hover:bg-accent cursor-pointer text-xs group",onClick:()=>t(e.filename),title:`${(e.size/1024).toFixed(1)} KB · ${new Date(e.mtimeMs).toLocaleString()}`,children:[_.jsx(Ri,{className:"h-3 w-3 text-muted-foreground shrink-0"}),_.jsx("span",{className:"flex-1 font-mono truncate text-foreground",children:e.filename.replace(/\.flow$/,"")}),_.jsx(K,{type:"button",size:"icon",onClick:t=>{t.stopPropagation(),window.dispatchEvent(new CustomEvent("ccweb:flow-run-request",{detail:{filename:e.filename}}))},title:"直接运行(不打开编辑器)",className:"h-5 w-5 bg-emerald-600 text-white hover:bg-emerald-700 dark:bg-emerald-600 dark:hover:bg-emerald-500",children:_.jsx(ki,{className:"h-2.5 w-2.5 fill-current"})}),_.jsx(K,{type:"button",variant:"ghost",size:"icon",onClick:t=>{E(e.filename,t)},title:"删除",className:"h-5 w-5 text-muted-foreground hover:text-destructive",children:_.jsx(S,{className:"h-3 w-3"})})]},e.filename))]}),_.jsx(se,{open:g,onOpenChange:e=>{e||v(!1)},children:_.jsxs(re,{className:"max-w-sm",children:[_.jsxs(ne,{children:[_.jsx(oe,{children:"新建工作轨"}),_.jsx(ae,{children:"工作轨文件名(不含 .flow 后缀),只允许字母/数字/下划线/中文/连字符。"})]}),_.jsxs("div",{className:"space-y-2",children:[_.jsx(le,{htmlFor:"new-flow-name",className:"text-xs text-muted-foreground",children:"文件名"}),_.jsx(q,{id:"new-flow-name",autoFocus:!0,value:y,onChange:e=>{x(e.target.value),w(null)},onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),k())},placeholder:"例:search-and-summarize",className:"font-mono"}),b&&_.jsx("div",{className:"text-xs text-destructive",children:b})]}),_.jsxs(ce,{children:[_.jsx(K,{variant:"outline",size:"sm",onClick:()=>v(!1),disabled:d,children:"取消"}),_.jsx(K,{size:"sm",onClick:()=>{k()},disabled:d,children:d?"创建中…":"创建"})]})]})})]})}function ys({projectPath:e,projectId:t,cliTool:i,onOpenTrackEditor:s}){const[r,n]=he(E.leftPanelTab,"files"),o="claude"===i,a="terminal"!==i,l="terminal"!==i;let c;return c="git"===r?"git":"tracks"===r&&l?"tracks":"scheduled"===r&&o?"scheduled":"backup"===r&&a?"backup":"files",_.jsxs(At,{value:c,onValueChange:e=>n(e),orientation:"vertical",className:"h-full flex bg-muted text-foreground overflow-hidden",children:[_.jsxs(zt,{className:g("flex flex-col items-center justify-start shrink-0","h-full w-9 border-r border-border rounded-none p-1 gap-1"),children:[_.jsx($t,{value:"files",title:"Files","aria-label":"Files",className:g("h-7 w-7 p-0 rounded-md flex items-center justify-center"),children:_.jsx(I,{className:"h-3.5 w-3.5"})}),_.jsx($t,{value:"git",title:"Git","aria-label":"Git",className:g("h-7 w-7 p-0 rounded-md flex items-center justify-center"),children:_.jsx(_i,{className:"h-3.5 w-3.5"})}),l&&_.jsx($t,{value:"tracks",title:"工作轨","aria-label":"Tracks",className:g("h-7 w-7 p-0 rounded-md flex items-center justify-center"),children:_.jsx(Di,{className:"h-3.5 w-3.5"})}),o&&_.jsx($t,{value:"scheduled",title:"已排程任务","aria-label":"Scheduled tasks",className:g("h-7 w-7 p-0 rounded-md flex items-center justify-center"),children:_.jsx(Lt,{className:"h-3.5 w-3.5"})}),a&&_.jsx($t,{value:"backup",title:"聊天记录备份","aria-label":"Sessions backup",className:g("h-7 w-7 p-0 rounded-md flex items-center justify-center"),children:_.jsx(te,{className:"h-3.5 w-3.5"})})]}),_.jsxs("div",{className:"flex-1 min-w-0 flex flex-col border-l border-border",children:[_.jsx(Ht,{value:"files",className:"flex-1 min-h-0 mt-0 data-[state=inactive]:hidden",children:_.jsx(Yi,{projectPath:e,projectId:t})}),_.jsx(Ht,{value:"git",className:"flex-1 min-h-0 mt-0 data-[state=inactive]:hidden",children:_.jsx(Gi,{projectId:t})}),l&&_.jsx(Ht,{value:"tracks",className:"flex-1 min-h-0 mt-0 data-[state=inactive]:hidden",children:_.jsx(vs,{projectId:t,onOpenEditor:e=>null==s?void 0:s(e)})}),o&&_.jsx(Ht,{value:"scheduled",className:"flex-1 min-h-0 mt-0 data-[state=inactive]:hidden",children:_.jsx(Qi,{projectId:t})}),a&&_.jsx(Ht,{value:"backup",className:"flex-1 min-h-0 mt-0 data-[state=inactive]:hidden",children:_.jsx(ss,{projectId:t})})]})]})}function xs(e){const t=bs(e),i=h.forwardRef((e,i)=>{const{children:s,...r}=e,n=h.Children.toArray(s),o=n.find(Ss);if(o){const e=o.props.children,s=n.map(t=>t===o?h.Children.count(e)>1?h.Children.only(null):h.isValidElement(e)?e.props.children:null:t);return _.jsx(t,{...r,ref:i,children:h.isValidElement(e)?h.cloneElement(e,void 0,s):null})}return _.jsx(t,{...r,ref:i,children:s})});return i.displayName=`${e}.Slot`,i}function bs(e){const t=h.forwardRef((e,t)=>{const{children:i,...s}=e;if(h.isValidElement(i)){const e=function(e){var t,i;let s=null==(t=Object.getOwnPropertyDescriptor(e.props,"ref"))?void 0:t.get,r=s&&"isReactWarning"in s&&s.isReactWarning;if(r)return e.ref;if(s=null==(i=Object.getOwnPropertyDescriptor(e,"ref"))?void 0:i.get,r=s&&"isReactWarning"in s&&s.isReactWarning,r)return e.props.ref;return e.props.ref||e.ref}(i),r=function(e,t){const i={...t};for(const s in t){const r=e[s],n=t[s];/^on[A-Z]/.test(s)?r&&n?i[s]=(...e)=>{const t=n(...e);return r(...e),t}:r&&(i[s]=r):"style"===s?i[s]={...r,...n}:"className"===s&&(i[s]=[r,n].filter(Boolean).join(" "))}return{...e,...i}}(s,i.props);return i.type!==h.Fragment&&(r.ref=t?de(t,e):e),h.cloneElement(i,r)}return h.Children.count(i)>1?h.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var ws=Symbol("radix.slottable");function Ss(e){return h.isValidElement(e)&&"function"==typeof e.type&&"__radixId"in e.type&&e.type.__radixId===ws}var Cs=["Enter"," "],ks=["ArrowUp","PageDown","End"],Es=["ArrowDown","PageUp","Home",...ks],Ns={ltr:[...Cs,"ArrowRight"],rtl:[...Cs,"ArrowLeft"]},Ms={ltr:["ArrowLeft"],rtl:["ArrowRight"]},js="Menu",[Ds,Rs,Ps]=Vt(js),[Ls,Ts]=fe(js,[Ps,Kt,Ut]),Is=Kt(),Bs=Ut(),[Os,As]=Ls(js),[zs,$s]=Ls(js),Hs=e=>{const{__scopeMenu:t,open:i=!1,children:s,dir:r,onOpenChange:n,modal:o=!0}=e,a=Is(t),[l,c]=h.useState(null),d=h.useRef(!1),u=ue(n),f=si(r);return h.useEffect(()=>{const e=()=>{d.current=!0,document.addEventListener("pointerdown",t,{capture:!0,once:!0}),document.addEventListener("pointermove",t,{capture:!0,once:!0})},t=()=>d.current=!1;return document.addEventListener("keydown",e,{capture:!0}),()=>{document.removeEventListener("keydown",e,{capture:!0}),document.removeEventListener("pointerdown",t,{capture:!0}),document.removeEventListener("pointermove",t,{capture:!0})}},[]),_.jsx(Wt,{...a,children:_.jsx(Os,{scope:t,open:i,onOpenChange:u,content:l,onContentChange:c,children:_.jsx(zs,{scope:t,onClose:h.useCallback(()=>u(!1),[u]),isUsingKeyboardRef:d,dir:f,modal:o,children:s})})})};Hs.displayName=js;var Ws=h.forwardRef((e,t)=>{const{__scopeMenu:i,...s}=e,r=Is(i);return _.jsx(Ft,{...r,...s,ref:t})});Ws.displayName="MenuAnchor";var Fs="MenuPortal",[Ks,Us]=Ls(Fs,{forceMount:void 0}),Vs=e=>{const{__scopeMenu:t,forceMount:i,children:s,container:r}=e,n=As(Fs,t);return _.jsx(Ks,{scope:t,forceMount:i,children:_.jsx(pe,{present:i||n.open,children:_.jsx(me,{asChild:!0,container:r,children:s})})})};Vs.displayName=Fs;var qs="MenuContent",[Ys,Xs]=Ls(qs),Gs=h.forwardRef((e,t)=>{const i=Us(qs,e.__scopeMenu),{forceMount:s=i.forceMount,...r}=e,n=As(qs,e.__scopeMenu),o=$s(qs,e.__scopeMenu);return _.jsx(Ds.Provider,{scope:e.__scopeMenu,children:_.jsx(pe,{present:s||n.open,children:_.jsx(Ds.Slot,{scope:e.__scopeMenu,children:o.modal?_.jsx(Zs,{...r,ref:t}):_.jsx(Js,{...r,ref:t})})})})}),Zs=h.forwardRef((e,t)=>{const i=As(qs,e.__scopeMenu),s=h.useRef(null),r=_e(t,s);return h.useEffect(()=>{const e=s.current;if(e)return ye(e)},[]),_.jsx(er,{...e,ref:r,trapFocus:i.open,disableOutsidePointerEvents:i.open,disableOutsideScroll:!0,onFocusOutside:ge(e.onFocusOutside,e=>e.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>i.onOpenChange(!1)})}),Js=h.forwardRef((e,t)=>{const i=As(qs,e.__scopeMenu);return _.jsx(er,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>i.onOpenChange(!1)})}),Qs=xs("MenuContent.ScrollLock"),er=h.forwardRef((e,t)=>{const{__scopeMenu:i,loop:s=!1,trapFocus:r,onOpenAutoFocus:n,onCloseAutoFocus:o,disableOutsidePointerEvents:a,onEntryFocus:l,onEscapeKeyDown:c,onPointerDownOutside:d,onFocusOutside:u,onInteractOutside:f,onDismiss:p,disableOutsideScroll:m,...g}=e,v=As(qs,i),y=$s(qs,i),x=Is(i),b=Bs(i),w=Rs(i),[S,C]=h.useState(null),k=h.useRef(null),E=_e(t,k,v.onContentChange),N=h.useRef(0),M=h.useRef(""),j=h.useRef(0),D=h.useRef(null),R=h.useRef("right"),P=h.useRef(0),L=m?we:h.Fragment,T=m?{as:Qs,allowPinchZoom:!0}:void 0,I=e=>{var t,i;const s=M.current+e,r=w().filter(e=>!e.disabled),n=document.activeElement,o=null==(t=r.find(e=>e.ref.current===n))?void 0:t.textValue,a=function(e,t,i){const s=t.length>1&&Array.from(t).every(e=>e===t[0]),r=s?t[0]:t,n=i?e.indexOf(i):-1;let o=(a=e,l=Math.max(n,0),a.map((e,t)=>a[(l+t)%a.length]));var a,l;1===r.length&&(o=o.filter(e=>e!==i));const c=o.find(e=>e.toLowerCase().startsWith(r.toLowerCase()));return c!==i?c:void 0}(r.map(e=>e.textValue),s,o),l=null==(i=r.find(e=>e.textValue===a))?void 0:i.ref.current;!function e(t){M.current=t,window.clearTimeout(N.current),""!==t&&(N.current=window.setTimeout(()=>e(""),1e3))}(s),l&&setTimeout(()=>l.focus())};h.useEffect(()=>()=>window.clearTimeout(N.current),[]),be();const B=h.useCallback(e=>{var t,i;return R.current===(null==(t=D.current)?void 0:t.side)&&function(e,t){if(!t)return!1;const i={x:e.clientX,y:e.clientY};return function(e,t){const{x:i,y:s}=e;let r=!1;for(let n=0,o=t.length-1;n<t.length;o=n++){const e=t[n],a=t[o],l=e.x,c=e.y,h=a.x,d=a.y;c>s!=d>s&&i<(h-l)*(s-c)/(d-c)+l&&(r=!r)}return r}(i,t)}(e,null==(i=D.current)?void 0:i.area)},[]);return _.jsx(Ys,{scope:i,searchRef:M,onItemEnter:h.useCallback(e=>{B(e)&&e.preventDefault()},[B]),onItemLeave:h.useCallback(e=>{var t;B(e)||(null==(t=k.current)||t.focus(),C(null))},[B]),onTriggerLeave:h.useCallback(e=>{B(e)&&e.preventDefault()},[B]),pointerGraceTimerRef:j,onPointerGraceIntentChange:h.useCallback(e=>{D.current=e},[]),children:_.jsx(L,{...T,children:_.jsx(Se,{asChild:!0,trapped:r,onMountAutoFocus:ge(n,e=>{var t;e.preventDefault(),null==(t=k.current)||t.focus({preventScroll:!0})}),onUnmountAutoFocus:o,children:_.jsx(Ce,{asChild:!0,disableOutsidePointerEvents:a,onEscapeKeyDown:c,onPointerDownOutside:d,onFocusOutside:u,onInteractOutside:f,onDismiss:p,children:_.jsx(Yt,{asChild:!0,...b,dir:y.dir,orientation:"vertical",loop:s,currentTabStopId:S,onCurrentTabStopIdChange:C,onEntryFocus:ge(l,e=>{y.isUsingKeyboardRef.current||e.preventDefault()}),preventScrollOnEntryFocus:!0,children:_.jsx(Xt,{role:"menu","aria-orientation":"vertical","data-state":Er(v.open),"data-radix-menu-content":"",dir:y.dir,...x,...g,ref:E,style:{outline:"none",...g.style},onKeyDown:ge(g.onKeyDown,e=>{const t=e.target.closest("[data-radix-menu-content]")===e.currentTarget,i=e.ctrlKey||e.altKey||e.metaKey,s=1===e.key.length;t&&("Tab"===e.key&&e.preventDefault(),!i&&s&&I(e.key));const r=k.current;if(e.target!==r)return;if(!Es.includes(e.key))return;e.preventDefault();const n=w().filter(e=>!e.disabled).map(e=>e.ref.current);ks.includes(e.key)&&n.reverse(),function(e){const t=document.activeElement;for(const i of e){if(i===t)return;if(i.focus(),document.activeElement!==t)return}}(n)}),onBlur:ge(e.onBlur,e=>{e.currentTarget.contains(e.target)||(window.clearTimeout(N.current),M.current="")}),onPointerMove:ge(e.onPointerMove,jr(e=>{const t=e.target,i=P.current!==e.clientX;if(e.currentTarget.contains(t)&&i){const t=e.clientX>P.current?"right":"left";R.current=t,P.current=e.clientX}}))})})})})})})});Gs.displayName=qs;var tr=h.forwardRef((e,t)=>{const{__scopeMenu:i,...s}=e;return _.jsx(ve.div,{role:"group",...s,ref:t})});tr.displayName="MenuGroup";var ir=h.forwardRef((e,t)=>{const{__scopeMenu:i,...s}=e;return _.jsx(ve.div,{...s,ref:t})});ir.displayName="MenuLabel";var sr="MenuItem",rr="menu.itemSelect",nr=h.forwardRef((e,t)=>{const{disabled:i=!1,onSelect:s,...r}=e,n=h.useRef(null),o=$s(sr,e.__scopeMenu),a=Xs(sr,e.__scopeMenu),l=_e(t,n),c=h.useRef(!1);return _.jsx(or,{...r,ref:l,disabled:i,onClick:ge(e.onClick,()=>{const e=n.current;if(!i&&e){const t=new CustomEvent(rr,{bubbles:!0,cancelable:!0});e.addEventListener(rr,e=>null==s?void 0:s(e),{once:!0}),xe(e,t),t.defaultPrevented?c.current=!1:o.onClose()}}),onPointerDown:t=>{var i;null==(i=e.onPointerDown)||i.call(e,t),c.current=!0},onPointerUp:ge(e.onPointerUp,e=>{var t;c.current||null==(t=e.currentTarget)||t.click()}),onKeyDown:ge(e.onKeyDown,e=>{const t=""!==a.searchRef.current;i||t&&" "===e.key||Cs.includes(e.key)&&(e.currentTarget.click(),e.preventDefault())})})});nr.displayName=sr;var or=h.forwardRef((e,t)=>{const{__scopeMenu:i,disabled:s=!1,textValue:r,...n}=e,o=Xs(sr,i),a=Bs(i),l=h.useRef(null),c=_e(t,l),[d,u]=h.useState(!1),[f,p]=h.useState("");return h.useEffect(()=>{const e=l.current;e&&p((e.textContent??"").trim())},[n.children]),_.jsx(Ds.ItemSlot,{scope:i,disabled:s,textValue:r??f,children:_.jsx(qt,{asChild:!0,...a,focusable:!s,children:_.jsx(ve.div,{role:"menuitem","data-highlighted":d?"":void 0,"aria-disabled":s||void 0,"data-disabled":s?"":void 0,...n,ref:c,onPointerMove:ge(e.onPointerMove,jr(e=>{if(s)o.onItemLeave(e);else if(o.onItemEnter(e),!e.defaultPrevented){e.currentTarget.focus({preventScroll:!0})}})),onPointerLeave:ge(e.onPointerLeave,jr(e=>o.onItemLeave(e))),onFocus:ge(e.onFocus,()=>u(!0)),onBlur:ge(e.onBlur,()=>u(!1))})})})}),ar=h.forwardRef((e,t)=>{const{checked:i=!1,onCheckedChange:s,...r}=e;return _.jsx(mr,{scope:e.__scopeMenu,checked:i,children:_.jsx(nr,{role:"menuitemcheckbox","aria-checked":Nr(i)?"mixed":i,...r,ref:t,"data-state":Mr(i),onSelect:ge(r.onSelect,()=>null==s?void 0:s(!!Nr(i)||!i),{checkForDefaultPrevented:!1})})})});ar.displayName="MenuCheckboxItem";var lr="MenuRadioGroup",[cr,hr]=Ls(lr,{value:void 0,onValueChange:()=>{}}),dr=h.forwardRef((e,t)=>{const{value:i,onValueChange:s,...r}=e,n=ue(s);return _.jsx(cr,{scope:e.__scopeMenu,value:i,onValueChange:n,children:_.jsx(tr,{...r,ref:t})})});dr.displayName=lr;var ur="MenuRadioItem",fr=h.forwardRef((e,t)=>{const{value:i,...s}=e,r=hr(ur,e.__scopeMenu),n=i===r.value;return _.jsx(mr,{scope:e.__scopeMenu,checked:n,children:_.jsx(nr,{role:"menuitemradio","aria-checked":n,...s,ref:t,"data-state":Mr(n),onSelect:ge(s.onSelect,()=>{var e;return null==(e=r.onValueChange)?void 0:e.call(r,i)},{checkForDefaultPrevented:!1})})})});fr.displayName=ur;var pr="MenuItemIndicator",[mr,_r]=Ls(pr,{checked:!1}),gr=h.forwardRef((e,t)=>{const{__scopeMenu:i,forceMount:s,...r}=e,n=_r(pr,i);return _.jsx(pe,{present:s||Nr(n.checked)||!0===n.checked,children:_.jsx(ve.span,{...r,ref:t,"data-state":Mr(n.checked)})})});gr.displayName=pr;var vr=h.forwardRef((e,t)=>{const{__scopeMenu:i,...s}=e;return _.jsx(ve.div,{role:"separator","aria-orientation":"horizontal",...s,ref:t})});vr.displayName="MenuSeparator";var yr=h.forwardRef((e,t)=>{const{__scopeMenu:i,...s}=e,r=Is(i);return _.jsx(Gt,{...r,...s,ref:t})});yr.displayName="MenuArrow";var[xr,br]=Ls("MenuSub"),wr="MenuSubTrigger",Sr=h.forwardRef((e,t)=>{const i=As(wr,e.__scopeMenu),s=$s(wr,e.__scopeMenu),r=br(wr,e.__scopeMenu),n=Xs(wr,e.__scopeMenu),o=h.useRef(null),{pointerGraceTimerRef:a,onPointerGraceIntentChange:l}=n,c={__scopeMenu:e.__scopeMenu},d=h.useCallback(()=>{o.current&&window.clearTimeout(o.current),o.current=null},[]);return h.useEffect(()=>d,[d]),h.useEffect(()=>{const e=a.current;return()=>{window.clearTimeout(e),l(null)}},[a,l]),_.jsx(Ws,{asChild:!0,...c,children:_.jsx(or,{id:r.triggerId,"aria-haspopup":"menu","aria-expanded":i.open,"aria-controls":r.contentId,"data-state":Er(i.open),...e,ref:de(t,r.onTriggerChange),onClick:t=>{var s;null==(s=e.onClick)||s.call(e,t),e.disabled||t.defaultPrevented||(t.currentTarget.focus(),i.open||i.onOpenChange(!0))},onPointerMove:ge(e.onPointerMove,jr(t=>{n.onItemEnter(t),t.defaultPrevented||e.disabled||i.open||o.current||(n.onPointerGraceIntentChange(null),o.current=window.setTimeout(()=>{i.onOpenChange(!0),d()},100))})),onPointerLeave:ge(e.onPointerLeave,jr(e=>{var t,s;d();const r=null==(t=i.content)?void 0:t.getBoundingClientRect();if(r){const t=null==(s=i.content)?void 0:s.dataset.side,o="right"===t,l=o?-5:5,c=r[o?"left":"right"],h=r[o?"right":"left"];n.onPointerGraceIntentChange({area:[{x:e.clientX+l,y:e.clientY},{x:c,y:r.top},{x:h,y:r.top},{x:h,y:r.bottom},{x:c,y:r.bottom}],side:t}),window.clearTimeout(a.current),a.current=window.setTimeout(()=>n.onPointerGraceIntentChange(null),300)}else{if(n.onTriggerLeave(e),e.defaultPrevented)return;n.onPointerGraceIntentChange(null)}})),onKeyDown:ge(e.onKeyDown,t=>{var r;const o=""!==n.searchRef.current;e.disabled||o&&" "===t.key||Ns[s.dir].includes(t.key)&&(i.onOpenChange(!0),null==(r=i.content)||r.focus(),t.preventDefault())})})})});Sr.displayName=wr;var Cr="MenuSubContent",kr=h.forwardRef((e,t)=>{const i=Us(qs,e.__scopeMenu),{forceMount:s=i.forceMount,...r}=e,n=As(qs,e.__scopeMenu),o=$s(qs,e.__scopeMenu),a=br(Cr,e.__scopeMenu),l=h.useRef(null),c=_e(t,l);return _.jsx(Ds.Provider,{scope:e.__scopeMenu,children:_.jsx(pe,{present:s||n.open,children:_.jsx(Ds.Slot,{scope:e.__scopeMenu,children:_.jsx(er,{id:a.contentId,"aria-labelledby":a.triggerId,...r,ref:c,align:"start",side:"rtl"===o.dir?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:e=>{var t;o.isUsingKeyboardRef.current&&(null==(t=l.current)||t.focus()),e.preventDefault()},onCloseAutoFocus:e=>e.preventDefault(),onFocusOutside:ge(e.onFocusOutside,e=>{e.target!==a.trigger&&n.onOpenChange(!1)}),onEscapeKeyDown:ge(e.onEscapeKeyDown,e=>{o.onClose(),e.preventDefault()}),onKeyDown:ge(e.onKeyDown,e=>{var t;const i=e.currentTarget.contains(e.target),s=Ms[o.dir].includes(e.key);i&&s&&(n.onOpenChange(!1),null==(t=a.trigger)||t.focus(),e.preventDefault())})})})})})});function Er(e){return e?"open":"closed"}function Nr(e){return"indeterminate"===e}function Mr(e){return Nr(e)?"indeterminate":e?"checked":"unchecked"}function jr(e){return t=>"mouse"===t.pointerType?e(t):void 0}kr.displayName=Cr;var Dr=Hs,Rr=Ws,Pr=Vs,Lr=Gs,Tr=tr,Ir=ir,Br=nr,Or=ar,Ar=dr,zr=fr,$r=gr,Hr=vr,Wr=yr,Fr=Sr,Kr=kr,Ur="ContextMenu",[Vr]=fe(Ur,[Ts]),qr=Ts(),[Yr,Xr]=Vr(Ur),Gr=e=>{const{__scopeContextMenu:t,children:i,onOpenChange:s,dir:r,modal:n=!0}=e,[o,a]=h.useState(!1),l=qr(t),c=ue(s),d=h.useCallback(e=>{a(e),c(e)},[c]);return _.jsx(Yr,{scope:t,open:o,onOpenChange:d,modal:n,children:_.jsx(Dr,{...l,dir:r,open:o,onOpenChange:d,modal:n,children:i})})};Gr.displayName=Ur;var Zr="ContextMenuTrigger",Jr=h.forwardRef((e,t)=>{const{__scopeContextMenu:i,disabled:s=!1,...r}=e,n=Xr(Zr,i),o=qr(i),a=h.useRef({x:0,y:0}),l=h.useRef({getBoundingClientRect:()=>DOMRect.fromRect({width:0,height:0,...a.current})}),c=h.useRef(0),d=h.useCallback(()=>window.clearTimeout(c.current),[]),u=e=>{a.current={x:e.clientX,y:e.clientY},n.onOpenChange(!0)};return h.useEffect(()=>d,[d]),h.useEffect(()=>{s&&d()},[s,d]),_.jsxs(_.Fragment,{children:[_.jsx(Rr,{...o,virtualRef:l}),_.jsx(ve.span,{"data-state":n.open?"open":"closed","data-disabled":s?"":void 0,...r,ref:t,style:{WebkitTouchCallout:"none",...e.style},onContextMenu:s?e.onContextMenu:ge(e.onContextMenu,e=>{d(),u(e),e.preventDefault()}),onPointerDown:s?e.onPointerDown:ge(e.onPointerDown,nn(e=>{d(),c.current=window.setTimeout(()=>u(e),700)})),onPointerMove:s?e.onPointerMove:ge(e.onPointerMove,nn(d)),onPointerCancel:s?e.onPointerCancel:ge(e.onPointerCancel,nn(d)),onPointerUp:s?e.onPointerUp:ge(e.onPointerUp,nn(d))})]})});Jr.displayName=Zr;var Qr=e=>{const{__scopeContextMenu:t,...i}=e,s=qr(t);return _.jsx(Pr,{...s,...i})};Qr.displayName="ContextMenuPortal";var en="ContextMenuContent",tn=h.forwardRef((e,t)=>{const{__scopeContextMenu:i,...s}=e,r=Xr(en,i),n=qr(i),o=h.useRef(!1);return _.jsx(Lr,{...n,...s,ref:t,side:"right",sideOffset:2,align:"start",onCloseAutoFocus:t=>{var i;null==(i=e.onCloseAutoFocus)||i.call(e,t),!t.defaultPrevented&&o.current&&t.preventDefault(),o.current=!1},onInteractOutside:t=>{var i;null==(i=e.onInteractOutside)||i.call(e,t),t.defaultPrevented||r.modal||(o.current=!0)},style:{...e.style,"--radix-context-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-context-menu-content-available-width":"var(--radix-popper-available-width)","--radix-context-menu-content-available-height":"var(--radix-popper-available-height)","--radix-context-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-context-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});tn.displayName=en;h.forwardRef((e,t)=>{const{__scopeContextMenu:i,...s}=e,r=qr(i);return _.jsx(Tr,{...r,...s,ref:t})}).displayName="ContextMenuGroup";h.forwardRef((e,t)=>{const{__scopeContextMenu:i,...s}=e,r=qr(i);return _.jsx(Ir,{...r,...s,ref:t})}).displayName="ContextMenuLabel";var sn=h.forwardRef((e,t)=>{const{__scopeContextMenu:i,...s}=e,r=qr(i);return _.jsx(Br,{...r,...s,ref:t})});sn.displayName="ContextMenuItem";h.forwardRef((e,t)=>{const{__scopeContextMenu:i,...s}=e,r=qr(i);return _.jsx(Or,{...r,...s,ref:t})}).displayName="ContextMenuCheckboxItem";h.forwardRef((e,t)=>{const{__scopeContextMenu:i,...s}=e,r=qr(i);return _.jsx(Ar,{...r,...s,ref:t})}).displayName="ContextMenuRadioGroup";h.forwardRef((e,t)=>{const{__scopeContextMenu:i,...s}=e,r=qr(i);return _.jsx(zr,{...r,...s,ref:t})}).displayName="ContextMenuRadioItem";h.forwardRef((e,t)=>{const{__scopeContextMenu:i,...s}=e,r=qr(i);return _.jsx($r,{...r,...s,ref:t})}).displayName="ContextMenuItemIndicator";var rn=h.forwardRef((e,t)=>{const{__scopeContextMenu:i,...s}=e,r=qr(i);return _.jsx(Hr,{...r,...s,ref:t})});rn.displayName="ContextMenuSeparator";h.forwardRef((e,t)=>{const{__scopeContextMenu:i,...s}=e,r=qr(i);return _.jsx(Wr,{...r,...s,ref:t})}).displayName="ContextMenuArrow";h.forwardRef((e,t)=>{const{__scopeContextMenu:i,...s}=e,r=qr(i);return _.jsx(Fr,{...r,...s,ref:t})}).displayName="ContextMenuSubTrigger";function nn(e){return t=>"mouse"!==t.pointerType?e(t):void 0}h.forwardRef((e,t)=>{const{__scopeContextMenu:i,...s}=e,r=qr(i);return _.jsx(Kr,{...r,...s,ref:t,style:{...e.style,"--radix-context-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-context-menu-content-available-width":"var(--radix-popper-available-width)","--radix-context-menu-content-available-height":"var(--radix-popper-available-height)","--radix-context-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-context-menu-trigger-height":"var(--radix-popper-anchor-height)"}})}).displayName="ContextMenuSubContent";var on=Qr,an=tn,ln=sn,cn=rn;const hn=Gr,dn=Jr,un=h.forwardRef(({className:e,...t},i)=>_.jsx(on,{children:_.jsx(an,{ref:i,className:g("z-50 min-w-[10rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md","data-[state=open]:animate-in data-[state=closed]:animate-out","data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0","data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95",e),...t})}));un.displayName=an.displayName;const fn=h.forwardRef(({className:e,destructive:t,...i},s)=>_.jsx(ln,{ref:s,className:g("relative flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none","focus:bg-accent focus:text-accent-foreground","data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"text-red-500 focus:text-red-500 focus:bg-red-500/10",e),...i}));fn.displayName=ln.displayName;const pn=h.forwardRef(({className:e,...t},i)=>_.jsx(cn,{ref:i,className:g("-mx-1 my-1 h-px bg-border",e),...t}));function mn({kind:e,label:t,preview:i,inserted:s,unclicked:r,onLeftClick:n,onEdit:o,onDelete:a,onShare:l,onRefresh:c,footer:d,readOnly:u,noContextMenu:f,cornerHint:p,instructionsFile:m="CLAUDE.md"}){const v=h.useRef(null),x=g("agent-prompt"===e?s?"border-green-500/50 bg-green-500/10 hover:bg-green-500/15":"border-dashed border-border hover:border-border/80 hover:bg-muted-foreground/10 dark:hover:bg-muted-foreground/20":r?"border-blue-500/30 bg-blue-500/15 hover:bg-blue-500/20 dark:bg-blue-500/15 dark:hover:bg-blue-500/25":"border-transparent bg-background dark:bg-muted-foreground/10 hover:bg-muted-foreground/10 dark:hover:bg-muted-foreground/20 hover:border-muted-foreground/30"),b="agent-prompt"===e,w=!f||c?" · 右键更多":"",S="quick-prompt"===e?`点击发送${w}`:(s?`点击从 ${m} 移除`:`点击插入 ${m}`)+w,C=_.jsxs("div",{ref:v,className:g("group relative rounded-md border text-xs transition-colors cursor-pointer select-none",x),onClick:n,title:S,children:[b&&_.jsx("span",{"aria-hidden":!0,className:g("absolute top-1.5 left-1.5 h-2 w-2 rounded-full transition-colors",s?"bg-green-500 ring-1 ring-green-500/40":"border border-muted-foreground/40 bg-transparent")}),_.jsxs("div",{className:g("py-1.5",f&&p?"pr-10":f?"pr-2":"pr-7",b?"pl-5":"pl-3"),children:[_.jsx("div",{className:"font-medium truncate",children:t}),i&&i!==t&&_.jsx("div",{className:"mt-0.5 text-muted-foreground/80 truncate font-mono",children:i}),d]}),f&&p&&_.jsx("span",{"aria-hidden":!0,className:"absolute top-1.5 right-2 text-[10px] leading-none font-mono tabular-nums text-muted-foreground/60 pointer-events-none",children:p}),!f&&_.jsx("button",{onClick:e=>{e.stopPropagation(),e.preventDefault();const t=v.current;if(!t)return;const i=t.getBoundingClientRect(),s=new MouseEvent("contextmenu",{bubbles:!0,cancelable:!0,clientX:i.right-8,clientY:i.top+i.height/2,button:2});t.dispatchEvent(s)},className:g("absolute top-1 right-1 p-0.5 rounded transition-opacity","md:opacity-0 md:group-hover:opacity-100 md:focus-visible:opacity-100","hover:bg-muted-foreground/10 focus-visible:bg-muted-foreground/10","text-muted-foreground hover:text-foreground"),title:"更多","aria-label":"更多操作",children:_.jsx(bi,{className:"h-3.5 w-3.5"})})]});return!(!c&&(f||!o&&!a&&!l))?_.jsxs(hn,{children:[_.jsx(dn,{asChild:!0,children:C}),_.jsxs(un,{children:[c&&_.jsxs(fn,{onSelect:c,children:[_.jsx(T,{className:"h-3.5 w-3.5"}),"更新"]}),!f&&!u&&o&&a&&_.jsxs(_.Fragment,{children:[c&&_.jsx(pn,{}),_.jsxs(fn,{onSelect:o,children:[_.jsx(y,{className:"h-3.5 w-3.5"}),"编辑"]}),_.jsxs(fn,{destructive:!0,onSelect:a,children:[_.jsx(L,{className:"h-3.5 w-3.5"}),"删除"]}),l&&_.jsx(pn,{})]}),!f&&l&&_.jsxs(fn,{onSelect:l,children:[_.jsx(ke,{className:"h-3.5 w-3.5"}),"共享到 ccweb-hub"]})]})]}):_.jsx("div",{onContextMenu:e=>e.preventDefault(),children:C})}function _n({open:e,onOpenChange:t,initialLabel:i,initialCommand:s,title:r,onSave:n}){const[o,a]=h.useState(i),[l,c]=h.useState(s),[d,u]=h.useState(!0);h.useEffect(()=>{e&&u(!0)},[e]),h.useEffect(()=>{e&&(a(i),c(s))},[e,i,s]);const f=()=>{const e=l.trim();e&&(n(o.trim()||e,e),t(!1))};return _.jsx(se,{open:e,onOpenChange:t,modal:!1,children:_.jsxs(re,{noOverlay:!0,className:g("sm:max-w-2xl max-h-[85vh] flex flex-col transition-opacity",!d&&"opacity-50"),onInteractOutside:e=>{e.preventDefault(),u(!1)},onClick:()=>u(!0),children:[_.jsxs(ne,{children:[_.jsx(oe,{children:r}),_.jsx(ae,{children:"左键点击卡片会把此命令发送到 CLI。"})]}),_.jsxs("div",{className:"space-y-4 flex-1 min-h-0 flex flex-col",children:[_.jsxs("div",{className:"space-y-2",children:[_.jsx(le,{htmlFor:"qp-label",children:"标签"}),_.jsx(q,{id:"qp-label",placeholder:"显示名(可选,默认用命令文本)",value:o,onChange:e=>a(e.target.value),className:"text-base",autoFocus:!0})]}),_.jsxs("div",{className:"space-y-2 flex-1 flex flex-col min-h-0",children:[_.jsx(le,{htmlFor:"qp-command",children:"命令"}),_.jsx("textarea",{id:"qp-command",placeholder:"输入要发送的命令...",value:l,onChange:e=>c(e.target.value),className:g("flex-1 min-h-[200px] w-full rounded-md border border-input bg-background px-4 py-3","text-base leading-relaxed font-mono","ring-offset-background placeholder:text-muted-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2","resize-none"),onKeyDown:e=>{"Enter"===e.key&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),f())}})]})]}),_.jsxs(ce,{className:"flex items-center justify-between sm:justify-between",children:[_.jsx("span",{className:"text-xs text-muted-foreground",children:"⌘↩ 保存"}),_.jsxs("div",{className:"flex gap-2",children:[_.jsx(K,{variant:"outline",onClick:()=>t(!1),children:"取消"}),_.jsx(K,{onClick:f,disabled:!l.trim(),children:"保存"})]})]})]})})}function gn({title:e,count:t,onAdd:i,children:s}){return _.jsxs("div",{className:"px-2 py-2",children:[_.jsxs("div",{className:"flex items-center justify-between mb-1.5 px-1",children:[_.jsxs("div",{className:"flex items-center gap-1.5 text-xs font-medium text-muted-foreground",children:[_.jsx("span",{children:e}),_.jsxs("span",{className:"text-muted-foreground/60",children:["(",t,")"]})]}),_.jsx("button",{onClick:i,className:"p-0.5 rounded text-muted-foreground hover:text-foreground hover:bg-muted-foreground/10 transition-colors",title:"新建","aria-label":"新建",children:_.jsx(V,{className:"h-3 w-3"})})]}),s]})}function vn({projectId:e,onSend:t}){const i=c(),[s,r]=h.useState([]),[n,o]=h.useState([]),a=D(),l=a.get(e),[d,u]=h.useState({open:!1}),[f,p]=h.useState(l.shareHubOpen),[m,g]=h.useState(l.shareHubLabel),[v,y]=h.useState(l.shareHubCommand),x=h.useCallback(t=>{r(e=>{const i=e.findIndex(e=>e.id===t);if(i<0||e[i].used)return e;const s=[...e];return s[i]={...s[i],used:!0},s}),Ee(e,t,!0).catch(e=>{console.error("Failed to mark shortcut used:",e)})},[e]);h.useEffect(()=>{Ne(e).then(r).catch(()=>r([]))},[e]),h.useEffect(()=>{Me().then(o).catch(()=>o([]))},[]);const b=h.useCallback(e=>{const t=[],i=new Set;let s=e;const r=[];for(;s&&!i.has(s.id);)i.add(s.id),r.unshift(s),s=s.parentId?n.find(e=>e.id===s.parentId):void 0;for(const n of r)t.push(n.command);return t},[n]),w=h.useCallback(async e=>{const i=b(e);for(const s of i)try{await Promise.resolve(t(s+"\r"))}catch{return}},[b,t]),S=e=>u({open:!0,mode:"create",scope:e}),C=(t,i)=>{g(t),y(i),p(!0),a.setShareHub(e,!0,t,i)};return _.jsxs("div",{className:"h-full flex flex-col text-foreground overflow-hidden",children:[_.jsxs("div",{className:"px-3 pt-2.5 pb-2 border-b border-border/50 shrink-0",children:[_.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Quick Prompts"}),_.jsx("p",{className:"mt-1 text-[11px] text-muted-foreground/70 leading-snug",children:"点击卡片发送命令到 CLI;新建的命令在首次点击前以浅蓝色标识"})]}),_.jsxs("div",{className:"flex-1 overflow-y-auto min-h-0",children:[_.jsx(gn,{title:"项目",count:s.length,onAdd:()=>S("project"),children:0===s.length?_.jsx("div",{className:"px-1 py-3 text-xs text-muted-foreground/60",children:"暂无项目命令"}):_.jsx("div",{className:"space-y-1.5",children:s.map(s=>_.jsx(mn,{kind:"quick-prompt",label:s.label,preview:s.label!==s.command?s.command:"",unclicked:!s.used,onLeftClick:()=>(e=>{t(e.command+"\r"),x(e.id)})(s),onEdit:()=>(e=>u({open:!0,mode:"edit",scope:"project",id:e.id,label:e.label,command:e.command}))(s),onDelete:()=>{(async t=>{if(await i({title:"删除项目快捷 Prompt",description:`确认删除「${t.label}」?此操作不可撤销。`,destructive:!0,confirmLabel:"删除"}))try{await Re(e,t.id),r(e=>e.filter(e=>e.id!==t.id))}catch(s){console.error("Failed to delete shortcut:",s)}})(s)},onShare:()=>C(s.label,s.command)},s.id))})}),_.jsx("div",{className:"h-px bg-border mx-2"}),_.jsx(gn,{title:"全局",count:n.length,onAdd:()=>S("global"),children:0===n.length?_.jsx("div",{className:"px-1 py-3 text-xs text-muted-foreground/60",children:"暂无全局命令"}):_.jsx("div",{className:"space-y-1.5",children:n.map(e=>{var t;const s=e.parentId?null==(t=n.find(t=>t.id===e.parentId))?void 0:t.label:void 0;return _.jsx(mn,{kind:"quick-prompt",label:e.label,preview:s?"":e.label!==e.command?e.command:"",onLeftClick:()=>w(e),onEdit:()=>(e=>u({open:!0,mode:"edit",scope:"global",id:e.id,label:e.label,command:e.command}))(e),onDelete:()=>{(async e=>{const t=n.filter(t=>t.parentId===e.id);if(await i({title:"删除全局快捷 Prompt",description:t.length>0?`「${e.label}」被 ${t.length} 个其他全局命令继承。删除后这些命令的继承会断链。确认删除?`:`确认删除「${e.label}」?此操作不可撤销。`,destructive:!0,confirmLabel:"删除"}))try{await Pe(e.id),o(t=>t.filter(t=>t.id!==e.id))}catch(s){console.error("Failed to delete global shortcut:",s)}})(e)},onShare:()=>C(e.label,e.command),footer:s?_.jsxs("div",{className:"flex items-center gap-1 mt-0.5",children:[_.jsx(je,{className:"h-2.5 w-2.5 text-muted-foreground"}),_.jsxs("span",{className:"text-muted-foreground truncate",children:["继承: ",s,"(继承链仅可在 Dashboard 编辑)"]})]}):null},e.id)})})})]}),_.jsx(_n,{open:d.open,onOpenChange:e=>{e||u({open:!1})},initialLabel:d.open&&"edit"===d.mode?d.label:"",initialCommand:d.open&&"edit"===d.mode?d.command:"",title:d.open?"create"===d.mode?`新建${"global"===d.scope?"全局":"项目"}命令`:"编辑命令":"",onSave:(t,i)=>{(async(t,i)=>{if(d.open)try{if("create"===d.mode)if("global"===d.scope){const e=await Le({label:t,command:i});o(t=>[...t,e])}else{const s=await Te(e,{label:t,command:i});r(e=>[...e,s])}else if("global"===d.scope){const e=n.find(e=>e.id===d.id),s=await Ie(d.id,{label:t,command:i,parentId:(null==e?void 0:e.parentId)??null});o(e=>e.map(e=>e.id===s.id?s:e))}else{const s=await Be(e,d.id,{label:t,command:i});r(e=>e.map(e=>e.id===s.id?s:e))}}catch(s){console.error("Failed to save shortcut:",s)}})(t,i)}}),_.jsx(De,{open:f,onOpenChange:t=>{p(t),t||a.setShareHub(e,!1)},kind:"quick-prompt",label:m,content:v})]})}pn.displayName=cn.displayName;function yn({open:e,onOpenChange:t,title:i,initialLabel:s,initialCommand:r,onSave:n,instructionsFile:o="CLAUDE.md"}){const[a,l]=h.useState(s),[c,d]=h.useState(r),[u,f]=h.useState(!0);h.useEffect(()=>{e&&(l(s),d(r),f(!0))},[e,s,r]);const p=a.trim(),m=c.trim(),v=p.length>100,y=m.length>8e3,x=m.length>0&&p.length>0&&!v&&!y,b=()=>{x&&(n(p,c),t(!1))};return _.jsx(se,{open:e,onOpenChange:t,modal:!1,children:_.jsxs(re,{noOverlay:!0,className:g("sm:max-w-2xl max-h-[85vh] flex flex-col transition-opacity",!u&&"opacity-50"),onInteractOutside:e=>{e.preventDefault(),f(!1)},onClick:()=>f(!0),children:[_.jsxs(ne,{children:[_.jsx(oe,{children:i}),_.jsxs(ae,{children:["This prompt can be clicked once in the sidebar to insert into ",o,", and clicked again to remove (by exact text match)."]})]}),_.jsxs("div",{className:"space-y-4 flex-1 min-h-0 flex flex-col",children:[_.jsxs("div",{className:"space-y-2",children:[_.jsxs("div",{className:"flex items-center justify-between",children:[_.jsx(le,{htmlFor:"prompt-label",children:"Label"}),_.jsxs("span",{className:g("text-xs text-muted-foreground",v&&"text-red-500"),children:[p.length," / ",100]})]}),_.jsx(q,{id:"prompt-label",placeholder:"A short name for this prompt",value:a,onChange:e=>l(e.target.value),className:"text-base",autoFocus:!0})]}),_.jsxs("div",{className:"space-y-2 flex-1 flex flex-col min-h-0",children:[_.jsxs("div",{className:"flex items-center justify-between",children:[_.jsx(le,{htmlFor:"prompt-command",children:"Prompt"}),_.jsxs("span",{className:g("text-xs text-muted-foreground",y&&"text-red-500"),children:[m.length," / ",8e3]})]}),_.jsx("textarea",{id:"prompt-command",placeholder:`The exact text that will be appended to ${o}...`,value:c,onChange:e=>d(e.target.value),className:g("flex-1 min-h-[200px] w-full rounded-md border border-input bg-background px-4 py-3","text-sm leading-relaxed font-mono","ring-offset-background placeholder:text-muted-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2","resize-none"),onKeyDown:e=>{"Enter"===e.key&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),b())}})]})]}),_.jsxs(ce,{className:"flex items-center justify-between sm:justify-between",children:[_.jsx("span",{className:"text-xs text-muted-foreground",children:"⌘↩ to save"}),_.jsxs("div",{className:"flex gap-2",children:[_.jsx(K,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),_.jsx(K,{onClick:b,disabled:!x,children:"Save"})]})]})]})})}function xn({projectId:e}){const t=c(),[i,s]=h.useState([]),[r,n]=h.useState([]),[o,a]=h.useState("CLAUDE.md"),[l,d]=h.useState(!0),[u,f]=h.useState({open:!1}),[p,g]=h.useState({open:!1,label:"",content:""}),v=h.useCallback(async()=>{try{const t=await Oe(e);s(t.global),n(t.project),t.instructionsFilename&&a(t.instructionsFilename)}catch(t){m.error(`加载提示词失败: ${t.message}`)}finally{d(!1)}},[e]);h.useEffect(()=>{d(!0),v()},[v]);const y=h.useRef(new Set),x=h.useCallback(async(t,i)=>{if(y.current.has(i.id))return;y.current.add(i.id);const r=i.inserted?"remove":"insert",a=e=>e.map(e=>e.id===i.id?{...e,inserted:!e.inserted}:e);"global"===t?s(a):n(a);try{const t=await Ae(e,i.command,r);if("remove"===r&&!1===t.changed)return"not-found"===t.reason?m.error(`${o} 中找不到该提示词的精确文本,请自行编辑 ${o} 移除。`):m.warning(`该提示词当前不在 ${o} 中(可能被手动编辑过),已重新同步状态。`),void v();v()}catch(l){m.error(`操作失败: ${l.message}`),"global"===t?s(a):n(a)}finally{y.current.delete(i.id)}},[e,v,o]),b=h.useCallback(async(t,i,s,r,n)=>{try{if("create"===t)"global"===i?await ze({label:r,command:n}):await $e(e,{label:r,command:n}),m.success("已添加");else{if(!s)return;"global"===i?await He(s,{label:r,command:n}):await We(e,s,{label:r,command:n}),m.success("已更新")}v()}catch(o){m.error(`保存失败: ${o.message}`)}},[e,v]),w=h.useCallback(async(i,s)=>{const r=s.inserted?`此提示词目前已插入当前项目的 ${o}。\n\n删除后它会在 ${o} 中成为"孤儿文本"——仅删除提示词记录,不会自动从 ${o} 移除。\n\n确认删除?`:"确认删除此提示词?此操作不可撤销。";if(await t({title:"删除提示词",description:r,destructive:!0,confirmLabel:"删除"}))try{"global"===i?await Fe(s.id):await Ke(e,s.id),m.success("已删除"),v()}catch(n){m.error(`删除失败: ${n.message}`)}},[e,v,t,o]),S=h.useCallback(e=>{g({open:!0,label:e.label,content:e.command})},[]);return _.jsxs("div",{className:"flex flex-col h-full overflow-y-auto",children:[_.jsxs("div",{className:"px-3 pt-2.5 pb-2 border-b border-border/50 shrink-0",children:[_.jsx("span",{className:"text-xs font-medium uppercase tracking-wider text-muted-foreground",children:"Agent Prompts"}),_.jsxs("p",{className:"mt-1 text-[11px] text-muted-foreground/70 leading-snug",children:["点击卡片插入 / 移出当前项目的 ",o,";左上角绿点表示已插入"]})]}),_.jsx(bn,{title:"项目",count:r.length,loading:l,prompts:r,emptyText:"暂无项目提示词",instructionsFile:o,onAdd:()=>f({open:!0,mode:"create",scope:"project"}),onToggle:e=>{x("project",e)},onEdit:e=>f({open:!0,mode:"edit",scope:"project",id:e.id,label:e.label,command:e.command}),onDelete:e=>{w("project",e)},onShare:S}),_.jsx("div",{className:"h-px bg-border mx-2"}),_.jsx(bn,{title:"全局",count:i.length,loading:l,prompts:i,emptyText:"暂无全局提示词",instructionsFile:o,onAdd:()=>f({open:!0,mode:"create",scope:"global"}),onToggle:e=>{x("global",e)},onEdit:e=>f({open:!0,mode:"edit",scope:"global",id:e.id,label:e.label,command:e.command}),onDelete:e=>{w("global",e)},onShare:S}),_.jsx(yn,{open:u.open,onOpenChange:e=>{e||f({open:!1})},title:!1===u.open?"":"create"===u.mode?`新建${"global"===u.scope?"全局":"项目"}提示词`:`编辑${"global"===u.scope?"全局":"项目"}提示词`,initialLabel:u.open&&"edit"===u.mode?u.label:"",initialCommand:u.open&&"edit"===u.mode?u.command:"",instructionsFile:o,onSave:(e,t)=>{if(!u.open)return;const i="edit"===u.mode?u.id:null;b(u.mode,u.scope,i,e,t)}}),_.jsx(De,{open:p.open,onOpenChange:e=>g(t=>({...t,open:e})),kind:"agent-prompt",label:p.label,content:p.content})]})}function bn({title:e,count:t,loading:i,prompts:s,emptyText:r,onAdd:n,onToggle:o,onEdit:a,onDelete:l,onShare:c,instructionsFile:h}){return _.jsxs("div",{className:"px-2 py-2",children:[_.jsxs("div",{className:"flex items-center justify-between mb-1.5 px-1",children:[_.jsxs("div",{className:"flex items-center gap-1.5 text-xs font-medium text-muted-foreground uppercase tracking-wider",children:[_.jsx("span",{children:e}),_.jsxs("span",{className:"text-muted-foreground/60 normal-case tracking-normal",children:["(",t,")"]})]}),_.jsx("button",{onClick:n,className:"p-0.5 rounded text-muted-foreground hover:text-foreground hover:bg-muted-foreground/10 transition-colors",title:"新建","aria-label":"新建",children:_.jsx(V,{className:"h-3 w-3"})})]}),i?_.jsx("div",{className:"px-1 py-3 text-xs text-muted-foreground/60",children:"加载中…"}):0===s.length?_.jsx("div",{className:"px-1 py-3 text-xs text-muted-foreground/60",children:r}):_.jsx("div",{className:"space-y-1.5",children:s.map(e=>{const t=e.command.split("\n").find(e=>e.trim())??e.command.trim();return _.jsx(mn,{kind:"agent-prompt",label:e.label,preview:t,inserted:e.inserted,instructionsFile:h,onLeftClick:()=>o(e),onEdit:()=>a(e),onDelete:()=>l(e),onShare:()=>c(e)},e.id)})})]})}function wn({projectId:e}){const[t,i]=h.useState([]),[s,r]=h.useState(null),[n,o]=h.useState("CLAUDE.md"),[a,l]=h.useState(!0),[c,d]=h.useState(!1),u=h.useRef(new Set),f=h.useCallback(async()=>{l(!0);try{const t=await Ue(e);i(t.items),r(t.claudeMdLineCount),t.instructionsFilename&&o(t.instructionsFilename)}catch(t){m.error(`加载失败: ${t.message}`)}finally{l(!1)}},[e]);h.useEffect(()=>{f()},[f]);const p=h.useCallback(async t=>{if(u.current.has(t.filename))return;u.current.add(t.filename),i(e=>e.map(e=>e.filename===t.filename?{...e,inserted:!e.inserted}:e));const s=t.inserted?"remove":"insert";try{const n=await Ve(e,t.filename,s);if(!n.ok)return m.error("操作失败"+(n.reason?`(${n.reason})`:"")),void f();i(e=>e.map(e=>e.filename===t.filename?{...e,inserted:n.inserted}:e)),"number"==typeof n.claudeMdLineCount&&r(n.claudeMdLineCount),"insert"===s&&"refreshed"===n.reason&&m.info(`${t.name} 已更新(文件内容有变化)`)}catch(n){m.error(`操作失败: ${n.message}`),i(e=>e.map(e=>e.filename===t.filename?{...e,inserted:t.inserted}:e))}finally{u.current.delete(t.filename)}},[e,f]),v=h.useCallback(async()=>{if(c)return;const s=t.filter(e=>e.inserted);if(0===s.length)return void m.info("没有已插入的 memory 卡片");d(!0);let n=0,o=0;for(const t of s)if(u.current.has(t.filename))o++;else{u.current.add(t.filename);try{const s=await Ve(e,t.filename,"insert");s.ok?(i(e=>e.map(e=>e.filename===t.filename?{...e,inserted:s.inserted}:e)),"number"==typeof s.claudeMdLineCount&&r(s.claudeMdLineCount),n++):o++}catch{o++}finally{u.current.delete(t.filename)}}d(!1),0===o?m.success(`已从磁盘更新 ${n} 个 memory 卡片`):m.error(`${n} 个更新成功,${o} 个失败`)},[e,t,c]),y=h.useCallback(async t=>{if(!u.current.has(t.filename))if(t.inserted){u.current.add(t.filename);try{const s=await Ve(e,t.filename,"insert");if(!s.ok)return m.error("更新失败"+(s.reason?`(${s.reason})`:"")),void f();i(e=>e.map(e=>e.filename===t.filename?{...e,inserted:s.inserted}:e)),"number"==typeof s.claudeMdLineCount&&r(s.claudeMdLineCount),m.success(`${t.name} 已从磁盘重新加载`)}catch(s){m.error(`更新失败: ${s.message}`)}finally{u.current.delete(t.filename)}}else m.info("卡片未插入,无需更新")},[e,f]);return _.jsxs("div",{className:"flex flex-col h-full overflow-y-auto",children:[_.jsxs("div",{className:"px-3 pt-2.5 pb-2 border-b border-border/50 shrink-0",children:[_.jsxs("div",{className:"flex items-center justify-between",children:[_.jsx("span",{className:"text-xs font-medium uppercase tracking-wider text-muted-foreground",children:"Memory Prompts"}),_.jsxs("div",{className:"flex items-center gap-0.5",children:[_.jsx("button",{onClick:()=>{v()},disabled:c||!t.some(e=>e.inserted),className:g("p-0.5 rounded text-muted-foreground transition-colors","hover:text-foreground hover:bg-muted-foreground/10","disabled:opacity-30 disabled:cursor-not-allowed disabled:hover:bg-transparent disabled:hover:text-muted-foreground"),title:`把所有已插入卡片的内容从磁盘重新加载到 ${n}`,children:_.jsx(yi,{className:g("h-3.5 w-3.5",c&&"animate-spin")})}),_.jsx("button",{onClick:()=>{f()},className:"p-0.5 rounded text-muted-foreground hover:text-foreground hover:bg-muted-foreground/10 transition-colors",title:"刷新(重新扫描 .ccweb/memory/)",children:_.jsx(T,{className:g("h-3.5 w-3.5",a&&"animate-spin")})})]})]}),_.jsxs("p",{className:"mt-1 text-[11px] text-muted-foreground/70 leading-snug",children:["来自 ",_.jsx("code",{className:"text-[11px]",children:".ccweb/memory/*.md"})," 的文件,点击插入 / 移除 ",n,"(以",_.jsx("code",{className:"text-[11px]",children:" START 名 / END 名 "}),"包裹)"]}),null!==s&&_.jsxs("p",{className:"mt-0.5 text-[11px] text-muted-foreground/60 font-mono tabular-nums",children:[n,": ",s," 行"]})]}),_.jsx("div",{className:"px-2 py-2 flex-1 min-h-0",children:a&&0===t.length?_.jsx("div",{className:"px-1 py-6 text-xs text-muted-foreground/60 text-center",children:"加载中…"}):0===t.length?_.jsxs("div",{className:"px-1 py-8 text-xs text-muted-foreground/60 flex flex-col items-center gap-2",children:[_.jsx(pi,{className:"h-5 w-5"}),_.jsxs("div",{className:"text-center leading-relaxed",children:["暂无 memory 文件",_.jsx("br",{}),"新建 ",_.jsx("code",{className:"text-[11px]",children:".ccweb/memory/*.md"})," 文件后点刷新"]})]}):_.jsx("div",{className:"space-y-1.5",children:t.map(e=>_.jsx(mn,{kind:"agent-prompt",noContextMenu:!0,label:e.name,preview:e.preview,inserted:e.inserted,instructionsFile:n,cornerHint:`${e.lineCount} 行`,onLeftClick:()=>{p(e)},onRefresh:e.inserted?()=>{y(e)}:void 0},e.filename))})})]})}function Sn(){const[e,t]=h.useState(null),[i,s]=h.useState(null),[r,n]=h.useState(()=>k(E.browserLastUrl,"http://127.0.0.1")),[o,a]=h.useState(r),[l,c]=h.useState(!1),[d,f]=h.useState([r]),[p,v]=h.useState(0),y=h.useRef(null),x=h.useRef(null),b=h.useRef(null),w=h.useRef(null);h.useEffect(()=>{let e=!1;return(async()=>{try{const i=u(),r=await fetch("/api/browser-chrome/_session",{method:"POST",headers:i?{Authorization:`Bearer ${i}`}:{}});if(e)return;if(403===r.status)return void s("Browser 仅限 admin 用户");if(!r.ok){const e=await r.json().catch(()=>({}));return void s((null==e?void 0:e.error)||`会话创建失败 (HTTP ${r.status})`)}const o=await r.json();t(o),o.url&&"about:blank"!==o.url&&(n(o.url),a(o.url))}catch(i){e||s("无法连接 daemon")}})(),()=>{e=!0}},[]),h.useEffect(()=>{if(!e)return;const t=new WebSocket(`${"https:"===location.protocol?"wss:":"ws:"}//${location.host}/ws/browser-chrome/${e.sid}?token=${encodeURIComponent(e.token)}`);return b.current=t,t.onmessage=e=>{let t;try{t=JSON.parse(e.data)}catch{return}if("frame"===t.type&&t.data&&y.current){const e=w.current||new Image;w.current=e,e.onload=()=>{const t=y.current;if(!t)return;t.width!==e.width&&(t.width=e.width),t.height!==e.height&&(t.height=e.height);const i=t.getContext("2d");i&&i.drawImage(e,0,0)},e.src=`data:image/${t.format||"jpeg"};base64,${t.data}`}},t.onerror=()=>{},t.onclose=e=>{1e3!==e.code&&1001!==e.code&&m.error(`Browser 连接断开 (${e.code})`)},()=>{t.close(1e3),b.current=null}},[e]),h.useEffect(()=>{j(E.browserLastUrl,r)},[r]),h.useEffect(()=>{if(!e)return;const t=x.current;if(!t)return;let i=null;const s={w:0,h:0},r=new ResizeObserver(e=>{const t=e[0].contentRect,r=Math.max(200,Math.round(t.width)),n=Math.max(200,Math.round(t.height));i&&clearTimeout(i),i=setTimeout(()=>{if(r===s.w&&n===s.h)return;s.w=r,s.h=n;const e=b.current;e&&e.readyState===WebSocket.OPEN&&e.send(JSON.stringify({type:"resize",w:r,h:n}))},200)});return r.observe(t),()=>{r.disconnect(),i&&clearTimeout(i)}},[e]);const S=h.useCallback(async t=>{if(!e)return;const i=function(e){const t=e.trim();return t?/^https?:\/\//i.test(t)?t:`http://${t}`:""}(t);if(!i)return;const s=u();c(!0);try{const t=await fetch(`/api/browser-chrome/${e.sid}/nav`,{method:"POST",headers:{"Content-Type":"application/json",...s?{Authorization:`Bearer ${s}`}:{}},body:JSON.stringify({url:i})});if(!t.ok){const e=await t.json().catch(()=>({}));return void m.error((null==e?void 0:e.error)||`导航失败 (${t.status})`)}const r=await t.json();n(r.url),a(r.url),f(e=>{const t=e.slice(0,p+1);return t.push(r.url),t.slice(-20)}),v(e=>Math.min(e+1,19))}catch{m.error("导航网络错误")}finally{c(!1)}},[e,p]),C=h.useCallback(e=>{e.preventDefault(),S(o)},[o,S]),N=h.useCallback(()=>{if(p>0){const e=p-1;v(e),S(d[e])}},[p,d,S]),M=h.useCallback(()=>{if(p<d.length-1){const e=p+1;v(e),S(d[e])}},[p,d,S]),D=h.useCallback(()=>S(r),[r,S]),R=h.useCallback(e=>{const t=b.current;t&&t.readyState===WebSocket.OPEN&&t.send(JSON.stringify(e))},[]),P=h.useCallback(t=>{const i=y.current;if(!i||!e)return{x:0,y:0};const s=i.getBoundingClientRect(),r=e.viewport.w/s.width,n=e.viewport.h/s.height;return{x:(t.clientX-s.left)*r,y:(t.clientY-s.top)*n}},[e]),L=h.useCallback(e=>{var t;null==(t=y.current)||t.focus();const{x:i,y:s}=P(e),r=[];e.shiftKey&&r.push("Shift"),e.ctrlKey&&r.push("Control"),e.altKey&&r.push("Alt"),e.metaKey&&r.push("Meta"),R({type:"click",x:i,y:s,button:2===e.button?"right":1===e.button?"middle":"left",modifiers:r})},[P,R]),T=h.useCallback(e=>{const{x:t,y:i}=P(e);R({type:"scroll",x:t,y:i,deltaX:e.deltaX,deltaY:e.deltaY})},[P,R]),I=h.useMemo(()=>new Set(["Enter","Escape","Tab","Backspace","Delete","Home","End","PageUp","PageDown","ArrowLeft","ArrowRight","ArrowUp","ArrowDown","F1","F2","F3","F4","F5","F6","F7","F8","F9","F10","F11","F12","Insert","CapsLock"]),[]),B=h.useCallback(e=>{const t=e.metaKey||e.ctrlKey;return"F5"===e.key||(!(!t||!["w","W","t","T","n","N","r","R"].includes(e.key))||(!!(t&&e.shiftKey&&["i","I","j","J","c","C"].includes(e.key))||!(!e.metaKey||"Tab"!==e.key&&"`"!==e.key)))},[]),O=h.useCallback(e=>{if(B(e))return;if("Unidentified"===e.key||"Process"===e.key||"Dead"===e.key)return;e.preventDefault();const t=[];e.shiftKey&&t.push("Shift"),e.ctrlKey&&t.push("Control"),e.altKey&&t.push("Alt"),e.metaKey&&t.push("Meta");const i=1===e.key.length,s=t.some(e=>"Shift"!==e);I.has(e.key)||s?R({type:"key",action:"press",key:e.key,modifiers:t}):i&&R({type:"type",text:e.key})},[B,I,R]),A=p>0,z=p<d.length-1;return _.jsxs("div",{className:"h-full flex flex-col bg-background min-h-0",children:[_.jsxs("div",{className:"shrink-0 flex items-center gap-1 px-2 py-1.5 border-b border-border bg-muted/40",children:[_.jsx(K,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:N,disabled:!A||!e,title:"后退","aria-label":"后退",children:_.jsx(qe,{className:"h-3.5 w-3.5"})}),_.jsx(K,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:M,disabled:!z||!e,title:"前进","aria-label":"前进",children:_.jsx(li,{className:"h-3.5 w-3.5"})}),_.jsx(K,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:D,disabled:!e||l,title:"刷新","aria-label":"刷新",children:l?_.jsx(ie,{className:"h-3.5 w-3.5 animate-spin"}):_.jsx(Mi,{className:"h-3.5 w-3.5"})}),_.jsx("form",{className:"flex-1 min-w-0",onSubmit:C,children:_.jsx(q,{value:o,onChange:e=>a(e.target.value),placeholder:"http://127.0.0.1:8080",className:"h-7 text-xs font-mono",spellCheck:!1,autoComplete:"off",disabled:!e})})]}),_.jsx("div",{ref:x,className:"flex-1 min-h-0 bg-white relative overflow-hidden",children:i?_.jsxs("div",{className:g("h-full flex flex-col items-center justify-center gap-2 text-destructive text-xs px-4 text-center"),children:[_.jsx(Tt,{className:"h-8 w-8 opacity-40"}),_.jsx("div",{children:i})]}):e?_.jsx("canvas",{ref:y,tabIndex:0,onClick:L,onWheel:T,onKeyDown:O,onContextMenu:e=>e.preventDefault(),className:"w-full h-full block cursor-pointer outline-none focus:ring-2 focus:ring-primary/30",style:{imageRendering:"pixelated"}}):_.jsxs("div",{className:g("h-full flex flex-col items-center justify-center gap-2 text-muted-foreground text-xs"),children:[_.jsx(ie,{className:"h-8 w-8 opacity-40 animate-spin"}),_.jsx("div",{children:"启动浏览器…"})]})}),_.jsx("div",{className:"shrink-0 px-2 py-1 text-[10px] text-muted-foreground border-t border-border bg-muted/20",children:"点击页面可聚焦输入键盘 · 仅 RFC1918/loopback · 中文输入 / 上传下载 / 剪贴板 Phase 2.2+ 跟进"})]})}function Cn({projectId:e,onSend:t}){const[i,s]=he(E.rightPanelTab,"shortcuts"),r="prompts"===i?"prompts":"memory"===i?"memory":"browser"===i?"browser":"shortcuts";return _.jsxs(At,{value:r,onValueChange:e=>s(e),orientation:"vertical",className:"h-full flex bg-muted text-foreground overflow-hidden",children:[_.jsxs("div",{className:"flex-1 min-w-0 flex flex-col border-r border-border",children:[_.jsx(Ht,{value:"shortcuts",className:"flex-1 min-h-0 mt-0 data-[state=inactive]:hidden",children:_.jsx(vn,{projectId:e,onSend:t})}),_.jsx(Ht,{value:"prompts",className:"flex-1 min-h-0 mt-0 data-[state=inactive]:hidden",children:_.jsx(xn,{projectId:e})}),_.jsx(Ht,{value:"memory",className:"flex-1 min-h-0 mt-0 data-[state=inactive]:hidden",children:_.jsx(wn,{projectId:e})}),_.jsx(Ht,{value:"browser",className:"flex-1 min-h-0 mt-0 data-[state=inactive]:hidden",children:_.jsx(Sn,{})})]}),_.jsxs(zt,{className:g("flex flex-col items-center justify-start shrink-0","h-full w-9 border-l border-border rounded-none p-1 gap-1"),children:[_.jsx($t,{value:"shortcuts",title:"Quick Prompts (快捷 Prompts)","aria-label":"Quick Prompts",className:g("h-7 w-7 p-0 rounded-md flex items-center justify-center"),children:_.jsx(Ye,{className:"h-3.5 w-3.5"})}),_.jsx($t,{value:"prompts",title:"Agent Prompts","aria-label":"Agent Prompts",className:g("h-7 w-7 p-0 rounded-md flex items-center justify-center"),children:_.jsx(Xe,{className:"h-3.5 w-3.5"})}),_.jsx($t,{value:"memory",title:"Memory Prompts (.ccweb/memory/*.md)","aria-label":"Memory Prompts",className:g("h-7 w-7 p-0 rounded-md flex items-center justify-center"),children:_.jsx(pi,{className:"h-3.5 w-3.5"})}),_.jsx($t,{value:"browser",title:"Browser (访问 daemon 所在机器的本地 / 局域网网页)","aria-label":"Browser",className:g("h-7 w-7 p-0 rounded-md flex items-center justify-center"),children:_.jsx(Tt,{className:"h-3.5 w-3.5"})})]})]})}function kn({projectId:e,state:t,running:i,onRefresh:s}){if(!t)return null;let r=_.jsx(ie,{className:"h-3 w-3 animate-spin"}),n="text-blue-600 dark:text-blue-400",o="运行中";switch(t.status){case"running":r=_.jsx(ie,{className:"h-3 w-3 animate-spin"}),n="text-blue-600 dark:text-blue-400",o="运行中";break;case"paused":r=_.jsx(ie,{className:"h-3 w-3"}),n="text-amber-600 dark:text-amber-400",o="等待输入";break;case"completed":r=_.jsx(ri,{className:"h-3 w-3"}),n="text-emerald-600 dark:text-emerald-400",o="已完成";break;case"failed":r=_.jsx(ai,{className:"h-3 w-3"}),n="text-red-600 dark:text-red-400",o="失败";break;case"cancelled":r=_.jsx(ai,{className:"h-3 w-3"}),n="text-muted-foreground",o="已取消";break;default:r=_.jsx(ie,{className:"h-3 w-3"})}return _.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[_.jsxs("span",{className:`flex items-center gap-1 ${n}`,children:[r,_.jsx("span",{className:"font-medium",children:o})]}),_.jsx("span",{className:"text-muted-foreground font-mono truncate max-w-[200px]",children:t.trackFilename}),void 0!==t.currentTaskIndex&&_.jsxs("span",{className:"text-muted-foreground",children:["#",t.currentTaskIndex]}),i&&_.jsx(K,{size:"sm",variant:"ghost",onClick:async()=>{try{await Promise.reject(new Error("track run API not available in v3 M0")),m.success("已请求中止"),s()}catch(e){m.error(e instanceof Error?e.message:"中止失败")}},title:"中止",className:"h-6 w-6 p-0",children:_.jsx(S,{className:"h-3 w-3"})}),"failed"===t.status&&t.error&&_.jsxs("span",{className:"text-red-600 dark:text-red-400 truncate max-w-[300px] font-mono",title:`${t.error.errorType}${t.error.code?` [${t.error.code}]`:""}: ${t.error.message}`,children:[t.error.code?`[${t.error.code}] `:"",t.error.message]})]})}function En({projectId:e,open:t,request:i,onSubmitted:s}){const r=c(),[n,o]=h.useState(()=>{var e;const t={};for(const s of i.fields)switch(s.type){case"bool":t[s.key]=!1;break;case"number":t[s.key]=0;break;case"enum":t[s.key]=(null==(e=s.variants)?void 0:e[0])??"";break;default:t[s.key]=""}return t}),[a,l]=h.useState(!1),d=(e,t)=>{o(i=>({...i,[e]:t}))};return _.jsx(se,{open:t,onOpenChange:()=>{},children:_.jsxs(re,{className:"max-w-lg",onPointerDownOutside:e=>e.preventDefault(),onEscapeKeyDown:e=>e.preventDefault(),children:[_.jsx(ne,{children:_.jsx(oe,{children:"工作轨需要输入"})}),_.jsx("div",{className:"space-y-3",children:i.fields.map(e=>_.jsxs("div",{className:"space-y-1.5",children:[_.jsxs(le,{className:"text-xs text-muted-foreground",children:[e.label," ",_.jsxs("span",{className:"opacity-60 font-mono",children:["(",e.key,")"]})]}),"text"===e.type&&_.jsx(q,{value:n[e.key]??"",placeholder:e.placeholder,onChange:t=>d(e.key,t.target.value)}),"number"===e.type&&_.jsx(q,{type:"number",value:String(n[e.key]??""),placeholder:e.placeholder,onChange:t=>{const i=Number(t.target.value);d(e.key,Number.isNaN(i)?"":i)}}),"bool"===e.type&&_.jsxs("div",{className:"flex items-center gap-2",children:[_.jsx("input",{type:"checkbox",checked:!!n[e.key],onChange:t=>d(e.key,t.target.checked),className:"h-4 w-4"}),_.jsx("span",{className:"text-sm",children:n[e.key]?"是":"否"})]}),"enum"===e.type&&_.jsxs(Zt,{value:n[e.key]??"",onValueChange:t=>d(e.key,t),children:[_.jsx(Jt,{children:_.jsx(Qt,{placeholder:"选择..."})}),_.jsx(ei,{children:(e.variants??[]).map(e=>_.jsx(ti,{value:e,children:e},e))})]})]},e.key))}),_.jsxs("div",{className:"flex justify-between items-center gap-2 pt-2",children:[_.jsx(K,{onClick:async()=>{if(await r({description:"中止整个工作轨运行?正在等待的 LLM 调用会被取消。",confirmLabel:"中止",destructive:!0}))try{await Promise.reject(new Error("track run API not available in v3 M0")),m.success("已请求中止"),s()}catch(e){m.error(e instanceof Error?e.message:"中止失败")}},variant:"ghost",size:"sm",disabled:a,className:"text-muted-foreground hover:text-destructive",children:"中止运行"}),_.jsx(K,{onClick:async()=>{l(!0);try{await(i.requestId,Promise.reject(new Error("track run API not available in v3 M0"))),s()}catch(e){m.error(e instanceof Error?e.message:"提交失败")}finally{l(!1)}},disabled:a,size:"sm",children:a?"提交中…":"提交"})]})]})})}function Nn(e){const[t,i]=h.useState(null),[s,r]=h.useState(!1),[n,o]=h.useState(null),a=h.useRef(e);a.current=e;const l=h.useCallback(async()=>{const e=a.current;if(e)try{const t=await Promise.resolve({running:!1,state:null,pendingAskUser:null});if(e!==a.current)return;i(t.state),r(t.running),o(t.pendingAskUser)}catch{}},[]),c=h.useRef(5e3),d=!!t||s||!!n;return h.useEffect(()=>{if(!e)return;const t=e=>{const t=e.detail;if(t&&t.type)switch(t.type){case"track_status_change":{const e=t;if(i(e.state),r("running"===e.state.status||"paused"===e.state.status),"failed"===e.state.status&&e.state.error){const t=e.state.error.code?`[${e.state.error.code}] `:"";m.error(`工作轨失败: ${t}${e.state.error.message}`)}else"cancelled"===e.state.status&&m.info("工作轨已取消");break}case"track_ask_user":{const e=t;o({runId:e.runId,requestId:e.requestId,fields:e.fields});break}case"track_run_complete":t.ok||o(null);break}};return window.addEventListener("ccweb:track-msg",t),()=>window.removeEventListener("ccweb:track-msg",t)},[e]),h.useEffect(()=>{if(!e)return i(null),r(!1),void o(null);let t=null;const s=d?5e3:3e4;c.current=s;const n=()=>{l(),t=setInterval(()=>{l()},s)},a=()=>{null!==t&&(clearInterval(t),t=null)},h=()=>{document.hidden?a():t||n()};return document.hidden||n(),document.addEventListener("visibilitychange",h),()=>{a(),document.removeEventListener("visibilitychange",h)}},[e,l,d]),{state:t,running:s,pendingAskUser:n,refresh:l}}var Mn=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"].reduce((e,t)=>{const i=Ge(`Primitive.${t}`),s=h.forwardRef((e,s)=>{const{asChild:r,...n}=e,o=r?i:t;return"undefined"!=typeof window&&(window[Symbol.for("radix-ui")]=!0),_.jsx(o,{...n,ref:s})});return s.displayName=`Primitive.${t}`,{...e,[t]:s}},{}),jn="horizontal",Dn=["horizontal","vertical"],Rn=h.forwardRef((e,t)=>{const{decorative:i,orientation:s=jn,...r}=e,n=function(e){return Dn.includes(e)}(s)?s:jn,o=i?{role:"none"}:{"aria-orientation":"vertical"===n?n:void 0,role:"separator"};return _.jsx(Mn.div,{"data-orientation":n,...o,...r,ref:t})});Rn.displayName="Separator";var Pn=Rn;const Ln=h.forwardRef(({className:e,orientation:t="horizontal",decorative:i=!0,...s},r)=>_.jsx(Pn,{ref:r,decorative:i,orientation:t,className:g("shrink-0 bg-border","horizontal"===t?"h-[1px] w-full":"h-full w-[1px]",e),...s}));Ln.displayName=Pn.displayName;const Tn=[{tool:"claude",label:"Claude Code",supportsContinue:!0},{tool:"codex",label:"Codex",supportsContinue:!0},{tool:"gemini",label:"Gemini CLI",supportsContinue:!0},{tool:"opencode",label:"OpenCode",supportsContinue:!1},{tool:"qwen",label:"Qwen Code",supportsContinue:!1},{tool:"terminal",label:"Bare Shell",supportsContinue:!1}];function In(e){var t;return(null==(t=Tn.find(t=>t.tool===e))?void 0:t.label)??String(e??"")}function Bn(e){var t;return(null==(t=Tn.find(t=>t.tool===e))?void 0:t.supportsContinue)??!1}function On({open:e,onOpenChange:t,currentCliTool:i,loading:s,onConfirm:r}){const{t:n}=Ze(),[o,a]=h.useState(null),[l,c]=h.useState(!1),[d,u]=h.useState(null);h.useEffect(()=>{e&&(a(null),c(!1),u(null))},[e]),h.useEffect(()=>{o&&!Bn(o)&&c(!1)},[o]);const f=!!o&&Bn(o);return _.jsx(se,{open:e,onOpenChange:t,children:_.jsxs(re,{className:"max-w-lg",children:[_.jsxs(ne,{children:[_.jsx(oe,{children:n("switch_cli.title")}),_.jsx(ae,{children:n("switch_cli.description",{current:In(i)})})]}),_.jsxs("div",{className:"space-y-4",children:[_.jsxs("div",{className:"space-y-2",children:[_.jsx("div",{className:"text-sm font-medium",children:n("switch_cli.target_label")}),_.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:Tn.map(e=>{const t=e.tool===i,r=e.tool===o;return _.jsxs("button",{type:"button",disabled:t||s,onClick:()=>a(e.tool),className:g("text-left px-3 py-2 rounded-md border text-sm transition-colors",r?"border-primary bg-accent":"border-border hover:bg-accent/50",t&&"opacity-50 cursor-not-allowed"),children:[_.jsx("div",{className:"font-medium",children:e.label}),_.jsx("div",{className:"text-xs text-muted-foreground",children:t?n("switch_cli.tag_current"):e.supportsContinue?n("switch_cli.tag_supports_continue"):n("switch_cli.tag_no_continue")})]},e.tool)})})]}),_.jsxs("div",{className:"space-y-2",children:[_.jsx("div",{className:"text-sm font-medium",children:n("switch_cli.mode_label")}),_.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[_.jsxs("button",{type:"button",disabled:s,onClick:()=>c(!1),className:g("text-left px-3 py-2 rounded-md border text-sm transition-colors",l?"border-border hover:bg-accent/50":"border-primary bg-accent"),children:[_.jsx("div",{className:"font-medium",children:n("switch_cli.mode_fresh")}),_.jsx("div",{className:"text-xs text-muted-foreground",children:n("switch_cli.mode_fresh_hint")})]}),_.jsxs("button",{type:"button",disabled:s||!o||!f,onClick:()=>c(!0),title:o&&!f?n("switch_cli.mode_continue_unsupported",{tool:In(o)}):void 0,className:g("text-left px-3 py-2 rounded-md border text-sm transition-colors",l?"border-primary bg-accent":"border-border hover:bg-accent/50",(!o||!f)&&"opacity-50 cursor-not-allowed"),children:[_.jsx("div",{className:"font-medium",children:n("switch_cli.mode_continue")}),_.jsx("div",{className:"text-xs text-muted-foreground",children:o&&!f?n("switch_cli.mode_continue_unsupported",{tool:In(o)}):n("switch_cli.mode_continue_hint")})]})]})]}),d&&_.jsx("div",{className:"text-xs text-red-500 break-words",children:d})]}),_.jsxs(ce,{children:[_.jsx(K,{variant:"outline",onClick:()=>t(!1),disabled:s,children:n("switch_cli.cancel")}),_.jsx(K,{onClick:()=>{(async()=>{if(o){u(null);try{await r(o,l)}catch(e){u(e instanceof Error?e.message:String(e))}}})()},disabled:!o||s,children:n(s?"switch_cli.confirming":"switch_cli.confirm")})]})]})})}function An({status:e}){return _.jsxs("span",{className:g("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",{running:"bg-green-500/10 text-green-600 border-green-500/20",stopped:"bg-muted text-muted-foreground border-border",restarting:"bg-yellow-500/10 text-yellow-600 border-yellow-500/20"}[e]),children:[_.jsx("span",{className:g("w-1.5 h-1.5 rounded-full",{"bg-green-500":"running"===e,"bg-muted-foreground":"stopped"===e,"bg-yellow-400 animate-pulse":"restarting"===e})}),e.charAt(0).toUpperCase()+e.slice(1)]})}function zn({project:e,projectId:t,showFileTree:i,showShortcuts:s,showChatOverlay:r,onToggleFileTree:n,onToggleShortcuts:o,onToggleChatOverlay:a,onProjectUpdate:l}){const{t:c}=Ze(),d=Je(),[u,f]=h.useState(!1),[p,v]=h.useState(!1),[y,x]=h.useState(0),[C,k]=h.useState(!1),[E,N]=h.useState(!1),[M,j]=h.useState(!1),[D,R]=h.useState(!1),P=Nn(e.id);Qe({onStart:e=>{e.projectId===t&&x(0)},onProgress:e=>{e.projectId===t&&x(e.filesTransferred)},onDone:e=>{e.projectId===t&&x(0)}}),h.useEffect(()=>{const e=()=>N(!!document.fullscreenElement);return document.addEventListener("fullscreenchange",e),()=>document.removeEventListener("fullscreenchange",e)},[]);const L=et(e=>e.updateProject);return _.jsx("header",{className:"border-b border-border flex-shrink-0 bg-muted/50",children:_.jsxs("div",{className:"px-3 h-12 flex items-center gap-2",children:[_.jsx(K,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>d("/"),children:_.jsx(qe,{className:"h-4 w-4"})}),_.jsx(Ln,{orientation:"vertical",className:"h-5 mx-0.5"}),_.jsx(K,{variant:"ghost",size:"icon",className:g("h-7 w-7",i&&"bg-accent"),onClick:n,title:c("project_header.toggle_file_tree"),children:_.jsx(Si,{className:"h-4 w-4"})}),_.jsx(K,{variant:"ghost",size:"icon",className:g("h-7 w-7",s&&"bg-accent"),onClick:o,title:c("project_header.toggle_right_panel"),children:_.jsx(Ci,{className:"h-4 w-4"})}),"terminal"!==e.cliTool&&_.jsx(K,{variant:"ghost",size:"icon",className:g("h-7 w-7",r&&"bg-accent"),onClick:a,title:c("project_header.toggle_chat_overlay"),children:_.jsx(xi,{className:"h-4 w-4"})}),_.jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-2 ml-2",children:[_.jsx("h1",{className:"font-semibold text-foreground truncate text-sm",children:e.name}),_.jsx(An,{status:e.status}),_.jsx(tt,{variant:"outline",className:"text-xs",children:"unlimited"===e.permissionMode?"Unlimited":"Limited"}),P.state&&_.jsx(kn,{projectId:e.id,state:P.state,running:P.running,onRefresh:P.refresh}),_.jsxs("button",{type:"button",onClick:()=>j(!0),disabled:D,title:`${c("project_header.switch_cli_title")} (${In(e.cliTool)})`,className:"inline-flex items-center gap-1 text-xs px-2 py-0.5 rounded-full border border-border bg-background hover:bg-accent transition-colors disabled:opacity-50 flex-shrink-0",children:[_.jsx(T,{className:"h-3 w-3"}),_.jsx("span",{className:"font-medium hidden sm:inline",children:In(e.cliTool)})]}),_.jsx("span",{className:"text-xs text-muted-foreground font-mono truncate hidden lg:block",children:e.folderPath})]}),_.jsx(it,{}),_.jsx(st,{}),_.jsx(K,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>{document.fullscreenElement?document.exitFullscreen():document.documentElement.requestFullscreen()},title:c(E?"project_header.fullscreen_exit":"project_header.fullscreen_enter"),children:E?_.jsx(b,{className:"h-3.5 w-3.5"}):_.jsx(w,{className:"h-3.5 w-3.5"})}),_.jsx(Ln,{orientation:"vertical",className:"h-5 mx-0.5"}),p?_.jsxs(K,{variant:"outline",size:"sm",className:"flex-shrink-0",onClick:()=>{(async()=>{if(p&&!C){k(!0);try{(await nt(t)).cancelled?m.info(c("project_header.sync_cancelled")):m.error(c("project_header.sync_cancel_failed"))}catch(e){m.error(e instanceof Error?e.message:c("project_header.sync_cancel_failed")),k(!1)}}})()},disabled:C,title:c("project_header.sync_cancel_title"),children:[C?_.jsx(ie,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):_.jsx(S,{className:"h-3.5 w-3.5 mr-1.5"}),_.jsx("span",{className:"tabular-nums",children:y>0?c("project_header.sync_progress_label",{files:y}):c("project_header.sync_progress_label_empty")})]}):_.jsxs(K,{variant:"outline",size:"sm",className:"flex-shrink-0",onClick:()=>{(async()=>{if(!p){v(!0),x(0);try{const e=await ot(t);e.skipped?m.info(c("project_header.sync_skipped")):e.ok?m.success(c("project_header.sync_success",{files:e.filesTransferred,seconds:Math.round(e.durationMs/1e3)})):"cancelled"===e.reason||m.error(e.reason?c("project_header.sync_failed_with_reason",{reason:e.reason}):c("project_header.sync_failed"))}catch(e){m.error(e instanceof Error?e.message:c("project_header.sync_failed"))}finally{v(!1),x(0),k(!1)}}})()},title:c("project_header.sync_button_title"),children:[_.jsx(rt,{className:"h-3.5 w-3.5 mr-1.5"}),c("project_header.sync")]}),_.jsx(On,{open:M,onOpenChange:e=>{D||j(e)},currentCliTool:e.cliTool,loading:D,onConfirm:async(t,i)=>{R(!0);try{const s=await at(e.id,t,i);l(s),L(s),j(!1),m.success(c("switch_cli.switched_toast",{tool:In(t)}))}catch(s){const e=s instanceof Error?s.message:String(s);throw m.error(c("switch_cli.switch_failed",{reason:e})),s}finally{R(!1)}}}),P.pendingAskUser&&_.jsx(En,{projectId:e.id,open:!!P.pendingAskUser,request:P.pendingAskUser,onSubmitted:()=>P.refresh()}),"stopped"===e.status&&_.jsxs(K,{variant:"outline",size:"sm",className:"flex-shrink-0",onClick:()=>{(async()=>{f(!0);try{l(await lt(e.id))}catch(t){console.error(t)}finally{f(!1)}})()},disabled:u,children:[_.jsx(ki,{className:"h-3.5 w-3.5 mr-1.5"}),"Start"]})]})})}
15
15
  /**
16
16
  * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved.
17
17
  * @license MIT
@@ -23,4 +23,4 @@ var e,t,i,s,r,n,o=Object.defineProperty,a=(e,t,i)=>((e,t,i)=>t in e?o(e,t,{enume
23
23
  * Fabrice Bellard's javascript vt100 for jslinux:
24
24
  * http://bellard.org/jslinux/
25
25
  * Copyright (c) 2011 Fabrice Bellard
26
- */var $n=Object.defineProperty,Hn=Object.getOwnPropertyDescriptor,Wn=(e,t,i,s)=>{for(var r,n=s>1?void 0:s?Hn(t,i):t,o=e.length-1;o>=0;o--)(r=e[o])&&(n=(s?r(t,i,n):r(n))||n);return s&&n&&$n(t,i,n),n},Fn=(e,t)=>(i,s)=>t(i,s,e),Kn="Terminal input",Un=()=>Kn,Vn=e=>Kn=e,qn="Too much output to announce, navigate to rows manually to read",Yn=()=>qn,Xn=e=>qn=e;function Gn(e,t,i,s){e=function(e,t){return t?"[200~"+e+"[201~":e}(e=function(e){return e.replace(/\r?\n/g,"\r")}(e),i.decPrivateModes.bracketedPasteMode&&!0!==s.rawOptions.ignoreBracketedPasteMode),i.triggerDataEvent(e,!0),t.value=""}function Zn(e,t,i){let s=i.getBoundingClientRect(),r=e.clientX-s.left-10,n=e.clientY-s.top-10;t.style.width="20px",t.style.height="20px",t.style.left=`${r}px`,t.style.top=`${n}px`,t.style.zIndex="1000",t.focus()}function Jn(e,t,i,s,r){Zn(e,t,i),r&&s.rightClickSelect(e),t.value=s.selectionText,t.select()}function Qn(e){return e>65535?(e-=65536,String.fromCharCode(55296+(e>>10))+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function eo(e,t=0,i=e.length){let s="";for(let r=t;r<i;++r){let t=e[r];t>65535?(t-=65536,s+=String.fromCharCode(55296+(t>>10))+String.fromCharCode(t%1024+56320)):s+=String.fromCharCode(t)}return s}var to=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let i=e.length;if(!i)return 0;let s=0,r=0;if(this._interim){let i=e.charCodeAt(r++);56320<=i&&i<=57343?t[s++]=1024*(this._interim-55296)+i-56320+65536:(t[s++]=this._interim,t[s++]=i),this._interim=0}for(let n=r;n<i;++n){let r=e.charCodeAt(n);if(55296<=r&&r<=56319){if(++n>=i)return this._interim=r,s;let o=e.charCodeAt(n);56320<=o&&o<=57343?t[s++]=1024*(r-55296)+o-56320+65536:(t[s++]=r,t[s++]=o);continue}65279!==r&&(t[s++]=r)}return s}},io=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let i=e.length;if(!i)return 0;let s,r,n,o,a=0,l=0,c=0;if(this.interim[0]){let s=!1,r=this.interim[0];r&=192==(224&r)?31:224==(240&r)?15:7;let n,o=0;for(;(n=63&this.interim[++o])&&o<4;)r<<=6,r|=n;let l=192==(224&this.interim[0])?2:224==(240&this.interim[0])?3:4,h=l-o;for(;c<h;){if(c>=i)return 0;if(n=e[c++],128!=(192&n)){c--,s=!0;break}this.interim[o++]=n,r<<=6,r|=63&n}s||(2===l?r<128?c--:t[a++]=r:3===l?r<2048||r>=55296&&r<=57343||65279===r||(t[a++]=r):r<65536||r>1114111||(t[a++]=r)),this.interim.fill(0)}let h=i-4,d=c;for(;d<i;){for(;!(!(d<h)||128&(s=e[d])||128&(r=e[d+1])||128&(n=e[d+2])||128&(o=e[d+3]));)t[a++]=s,t[a++]=r,t[a++]=n,t[a++]=o,d+=4;if(s=e[d++],s<128)t[a++]=s;else if(192==(224&s)){if(d>=i)return this.interim[0]=s,a;if(r=e[d++],128!=(192&r)){d--;continue}if(l=(31&s)<<6|63&r,l<128){d--;continue}t[a++]=l}else if(224==(240&s)){if(d>=i)return this.interim[0]=s,a;if(r=e[d++],128!=(192&r)){d--;continue}if(d>=i)return this.interim[0]=s,this.interim[1]=r,a;if(n=e[d++],128!=(192&n)){d--;continue}if(l=(15&s)<<12|(63&r)<<6|63&n,l<2048||l>=55296&&l<=57343||65279===l)continue;t[a++]=l}else if(240==(248&s)){if(d>=i)return this.interim[0]=s,a;if(r=e[d++],128!=(192&r)){d--;continue}if(d>=i)return this.interim[0]=s,this.interim[1]=r,a;if(n=e[d++],128!=(192&n)){d--;continue}if(d>=i)return this.interim[0]=s,this.interim[1]=r,this.interim[2]=n,a;if(o=e[d++],128!=(192&o)){d--;continue}if(l=(7&s)<<18|(63&r)<<12|(63&n)<<6|63&o,l<65536||l>1114111)continue;t[a++]=l}}return a}},so=" ",ro=class e{constructor(){this.fg=0,this.bg=0,this.extended=new no}static toColorRGB(e){return[e>>>16&255,e>>>8&255,255&e]}static fromColorRGB(e){return(255&e[0])<<16|(255&e[1])<<8|255&e[2]}clone(){let t=new e;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return 67108864&this.fg}isBold(){return 134217728&this.fg}isUnderline(){return this.hasExtendedAttrs()&&0!==this.extended.underlineStyle?1:268435456&this.fg}isBlink(){return 536870912&this.fg}isInvisible(){return 1073741824&this.fg}isItalic(){return 67108864&this.bg}isDim(){return 134217728&this.bg}isStrikethrough(){return 2147483648&this.fg}isProtected(){return 536870912&this.bg}isOverline(){return 1073741824&this.bg}getFgColorMode(){return 50331648&this.fg}getBgColorMode(){return 50331648&this.bg}isFgRGB(){return!(50331648&~this.fg)}isBgRGB(){return!(50331648&~this.bg)}isFgPalette(){return 16777216==(50331648&this.fg)||33554432==(50331648&this.fg)}isBgPalette(){return 16777216==(50331648&this.bg)||33554432==(50331648&this.bg)}isFgDefault(){return!(50331648&this.fg)}isBgDefault(){return!(50331648&this.bg)}isAttributeDefault(){return 0===this.fg&&0===this.bg}getFgColor(){switch(50331648&this.fg){case 16777216:case 33554432:return 255&this.fg;case 50331648:return 16777215&this.fg;default:return-1}}getBgColor(){switch(50331648&this.bg){case 16777216:case 33554432:return 255&this.bg;case 50331648:return 16777215&this.bg;default:return-1}}hasExtendedAttrs(){return 268435456&this.bg}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(268435456&this.bg&&~this.extended.underlineColor)switch(50331648&this.extended.underlineColor){case 16777216:case 33554432:return 255&this.extended.underlineColor;case 50331648:return 16777215&this.extended.underlineColor;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return 268435456&this.bg&&~this.extended.underlineColor?50331648&this.extended.underlineColor:this.getFgColorMode()}isUnderlineColorRGB(){return 268435456&this.bg&&~this.extended.underlineColor?!(50331648&~this.extended.underlineColor):this.isFgRGB()}isUnderlineColorPalette(){return 268435456&this.bg&&~this.extended.underlineColor?16777216==(50331648&this.extended.underlineColor)||33554432==(50331648&this.extended.underlineColor):this.isFgPalette()}isUnderlineColorDefault(){return 268435456&this.bg&&~this.extended.underlineColor?!(50331648&this.extended.underlineColor):this.isFgDefault()}getUnderlineStyle(){return 268435456&this.fg?268435456&this.bg?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},no=class e{constructor(e=0,t=0){this._ext=0,this._urlId=0,this._ext=e,this._urlId=t}get ext(){return this._urlId?-469762049&this._ext|this.underlineStyle<<26:this._ext}set ext(e){this._ext=e}get underlineStyle(){return this._urlId?5:(469762048&this._ext)>>26}set underlineStyle(e){this._ext&=-469762049,this._ext|=e<<26&469762048}get underlineColor(){return 67108863&this._ext}set underlineColor(e){this._ext&=-67108864,this._ext|=67108863&e}get urlId(){return this._urlId}set urlId(e){this._urlId=e}get underlineVariantOffset(){let e=(3758096384&this._ext)>>29;return e<0?4294967288^e:e}set underlineVariantOffset(e){this._ext&=536870911,this._ext|=e<<29&3758096384}clone(){return new e(this._ext,this._urlId)}isEmpty(){return 0===this.underlineStyle&&0===this._urlId}},oo=class e extends ro{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new no,this.combinedData=""}static fromCharData(t){let i=new e;return i.setFromCharData(t),i}isCombined(){return 2097152&this.content}getWidth(){return this.content>>22}getChars(){return 2097152&this.content?this.combinedData:2097151&this.content?Qn(2097151&this.content):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):2097151&this.content}setFromCharData(e){this.fg=e[0],this.bg=0;let t=!1;if(e[1].length>2)t=!0;else if(2===e[1].length){let i=e[1].charCodeAt(0);if(55296<=i&&i<=56319){let s=e[1].charCodeAt(1);56320<=s&&s<=57343?this.content=1024*(i-55296)+s-56320+65536|e[2]<<22:t=!0}else t=!0}else this.content=e[1].charCodeAt(0)|e[2]<<22;t&&(this.combinedData=e[1],this.content=2097152|e[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},ao="di$target",lo="di$dependencies",co=new Map;function ho(e){if(co.has(e))return co.get(e);let t=function(e,i,s){if(3!==arguments.length)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");!function(e,t,i){t[ao]===t?t[lo].push({id:e,index:i}):(t[lo]=[{id:e,index:i}],t[ao]=t)}(t,e,s)};return t._id=e,co.set(e,t),t}var uo=ho("BufferService"),fo=ho("CoreMouseService"),po=ho("CoreService"),mo=ho("CharsetService"),_o=ho("InstantiationService"),go=ho("LogService"),vo=ho("OptionsService"),yo=ho("OscLinkService"),xo=ho("UnicodeService"),bo=ho("DecorationService"),wo=class{constructor(e,t,i){this._bufferService=e,this._optionsService=t,this._oscLinkService=i}provideLinks(e,t){var i;let s=this._bufferService.buffer.lines.get(e-1);if(!s)return void t(void 0);let r=[],n=this._optionsService.rawOptions.linkHandler,o=new oo,a=s.getTrimmedLength(),l=-1,c=-1,h=!1;for(let d=0;d<a;d++)if(-1!==c||s.hasContent(d)){if(s.loadCell(d,o),o.hasExtendedAttrs()&&o.extended.urlId){if(-1===c){c=d,l=o.extended.urlId;continue}h=o.extended.urlId!==l}else-1!==c&&(h=!0);if(h||-1!==c&&d===a-1){let t=null==(i=this._oscLinkService.getLinkData(l))?void 0:i.uri;if(t){let i={start:{x:c+1,y:e},end:{x:d+(h||d!==a-1?0:1),y:e}},s=!1;if(!(null==n?void 0:n.allowNonHttpProtocols))try{let e=new URL(t);["http:","https:"].includes(e.protocol)||(s=!0)}catch{s=!0}s||r.push({text:t,range:i,activate:(e,t)=>n?n.activate(e,t,i):So(e,t),hover:(e,t)=>{var s;return null==(s=null==n?void 0:n.hover)?void 0:s.call(n,e,t,i)},leave:(e,t)=>{var s;return null==(s=null==n?void 0:n.leave)?void 0:s.call(n,e,t,i)}})}h=!1,o.hasExtendedAttrs()&&o.extended.urlId?(c=d,l=o.extended.urlId):(c=-1,l=-1)}}t(r)}};function So(e,t){if(confirm(`Do you want to navigate to ${t}?\n\nWARNING: This link could potentially be dangerous`)){let e=window.open();if(e){try{e.opener=null}catch{}e.location.href=t}else console.warn("Opening link blocked as opener could not be cleared")}}wo=Wn([Fn(0,uo),Fn(1,vo),Fn(2,yo)],wo);var Co=ho("CharSizeService"),ko=ho("CoreBrowserService"),Eo=ho("MouseService"),No=ho("RenderService"),Mo=ho("SelectionService"),jo=ho("CharacterJoinerService"),Do=ho("ThemeService"),Ro=ho("LinkProviderService"),Po=new class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?zo.isErrorNoTelemetry(e)?new zo(e.message+"\n\n"+e.stack):new Error(e.message+"\n\n"+e.stack):e},0)}}addListener(e){return this.listeners.push(e),()=>{this._removeListener(e)}}emit(e){this.listeners.forEach(t=>{t(e)})}_removeListener(e){this.listeners.splice(this.listeners.indexOf(e),1)}setUnexpectedErrorHandler(e){this.unexpectedErrorHandler=e}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(e){this.unexpectedErrorHandler(e),this.emit(e)}onUnexpectedExternalError(e){this.unexpectedErrorHandler(e)}};function Lo(e){(function(e){return e instanceof To||e instanceof Error&&e.name===Io&&e.message===Io})(e)||Po.onUnexpectedError(e)}var Io="Canceled";var To=class extends Error{constructor(){super(Io),this.name=this.message}};var Bo,Oo,Ao,zo=class e extends Error{constructor(e){super(e),this.name="CodeExpectedError"}static fromError(t){if(t instanceof e)return t;let i=new e;return i.message=t.message,i.stack=t.stack,i}static isErrorNoTelemetry(e){return"CodeExpectedError"===e.name}},$o=class e extends Error{constructor(t){super(t||"An unexpected bug occurred."),Object.setPrototypeOf(this,e.prototype)}};function Ho(e,t=0){return e[e.length-(1+t)]}function Wo(e,t){let i,s=this,r=!1;return function(){return r||(r=!0,t||(i=e.apply(s,arguments))),i}}function Fo(e){if(Ao.is(e)){let t=[];for(let i of e)if(i)try{i.dispose()}catch(Pa){t.push(Pa)}if(1===t.length)throw t[0];if(t.length>1)throw new AggregateError(t,"Encountered errors while disposing of store");return Array.isArray(e)?[]:e}if(e)return e.dispose(),e}function Ko(e){return{dispose:Wo(()=>{e()})}}(Oo=Bo||(Bo={})).isLessThan=function(e){return e<0},Oo.isLessThanOrEqual=function(e){return e<=0},Oo.isGreaterThan=function(e){return e>0},Oo.isNeitherLessOrGreaterThan=function(e){return 0===e},Oo.greaterThan=1,Oo.lessThan=-1,Oo.neitherLessOrGreaterThan=0,(e=>{function t(e){return e&&"object"==typeof e&&"function"==typeof e[Symbol.iterator]}e.is=t;let i=Object.freeze([]);function*s(e){yield e}e.empty=function(){return i},e.single=s,e.wrap=function(e){return t(e)?e:s(e)},e.from=function(e){return e||i},e.reverse=function*(e){for(let t=e.length-1;t>=0;t--)yield e[t]},e.isEmpty=function(e){return!e||!0===e[Symbol.iterator]().next().done},e.first=function(e){return e[Symbol.iterator]().next().value},e.some=function(e,t){let i=0;for(let s of e)if(t(s,i++))return!0;return!1},e.find=function(e,t){for(let i of e)if(t(i))return i},e.filter=function*(e,t){for(let i of e)t(i)&&(yield i)},e.map=function*(e,t){let i=0;for(let s of e)yield t(s,i++)},e.flatMap=function*(e,t){let i=0;for(let s of e)yield*t(s,i++)},e.concat=function*(...e){for(let t of e)yield*t},e.reduce=function(e,t,i){let s=i;for(let r of e)s=t(s,r);return s},e.slice=function*(e,t,i=e.length){for(t<0&&(t+=e.length),i<0?i+=e.length:i>e.length&&(i=e.length);t<i;t++)yield e[t]},e.consume=function(t,i=Number.POSITIVE_INFINITY){let s=[];if(0===i)return[s,t];let r=t[Symbol.iterator]();for(let n=0;n<i;n++){let t=r.next();if(t.done)return[s,e.empty()];s.push(t.value)}return[s,{[Symbol.iterator]:()=>r}]},e.asyncToArray=async function(e){let t=[];for await(let i of e)t.push(i);return Promise.resolve(t)}})(Ao||(Ao={}));var Uo=class e{constructor(){this._toDispose=new Set,this._isDisposed=!1}dispose(){this._isDisposed||(this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(0!==this._toDispose.size)try{Fo(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw new Error("Cannot register a disposable on itself!");return this._isDisposed?e.DISABLE_DISPOSED_WARNING||console.warn(new Error("Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!").stack):this._toDispose.add(t),t}delete(e){if(e){if(e===this)throw new Error("Cannot dispose a disposable on itself!");this._toDispose.delete(e),e.dispose()}}deleteAndLeak(e){e&&this._toDispose.has(e)&&this._toDispose.delete(e)}};Uo.DISABLE_DISPOSED_WARNING=!1;var Vo=Uo,qo=class{constructor(){this._store=new Vo,this._store}dispose(){this._store.dispose()}_register(e){if(e===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(e)}};qo.None=Object.freeze({dispose(){}});var Yo=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(e){var t;this._isDisposed||e===this._value||(null==(t=this._value)||t.dispose(),this._value=e)}clear(){this.value=void 0}dispose(){var e;this._isDisposed=!0,null==(e=this._value)||e.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e}},Xo="object"==typeof window?window:globalThis,Go=class e{constructor(t){this.element=t,this.next=e.Undefined,this.prev=e.Undefined}};Go.Undefined=new Go(void 0);var Zo,Jo=Go,Qo=class{constructor(){this._first=Jo.Undefined,this._last=Jo.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===Jo.Undefined}clear(){let e=this._first;for(;e!==Jo.Undefined;){let t=e.next;e.prev=Jo.Undefined,e.next=Jo.Undefined,e=t}this._first=Jo.Undefined,this._last=Jo.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let i=new Jo(e);if(this._first===Jo.Undefined)this._first=i,this._last=i;else if(t){let e=this._last;this._last=i,i.prev=e,e.next=i}else{let e=this._first;this._first=i,i.next=e,e.prev=i}this._size+=1;let s=!1;return()=>{s||(s=!0,this._remove(i))}}shift(){if(this._first!==Jo.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==Jo.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==Jo.Undefined&&e.next!==Jo.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===Jo.Undefined&&e.next===Jo.Undefined?(this._first=Jo.Undefined,this._last=Jo.Undefined):e.next===Jo.Undefined?(this._last=this._last.prev,this._last.next=Jo.Undefined):e.prev===Jo.Undefined&&(this._first=this._first.next,this._first.prev=Jo.Undefined);this._size-=1}*[Symbol.iterator](){let e=this._first;for(;e!==Jo.Undefined;)yield e.element,e=e.next}},ea=globalThis.performance&&"function"==typeof globalThis.performance.now,ta=class e{static create(t){return new e(t)}constructor(e){this._now=ea&&!1===e?Date.now:globalThis.performance.now.bind(globalThis.performance),this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=this._now(),this._stopTime=-1}elapsed(){return-1!==this._stopTime?this._stopTime-this._startTime:this._now()-this._startTime}};(e=>{function t(e){return(t,i=null,s)=>{let r,n=!1;return r=e(e=>{if(!n)return r?r.dispose():n=!0,t.call(i,e)},null,s),n&&r.dispose(),r}}function i(e,t,i){return r((i,s=null,r)=>e(e=>i.call(s,t(e)),null,r),i)}function s(e,t,i){return r((i,s=null,r)=>e(e=>t(e)&&i.call(s,e),null,r),i)}function r(e,t){let i,s=new da({onWillAddFirstListener(){i=e(s.fire,s)},onDidRemoveLastListener(){null==i||i.dispose()}});return null==t||t.add(s),s.event}function n(e,t,i=100,s=!1,r=!1,n,o){let a,l,c,h,d=0,u=new da({leakWarningThreshold:n,onWillAddFirstListener(){a=e(e=>{d++,l=t(l,e),s&&!c&&(u.fire(l),l=void 0),h=()=>{let e=l;l=void 0,c=void 0,(!s||d>1)&&u.fire(e),d=0},"number"==typeof i?(clearTimeout(c),c=setTimeout(h,i)):void 0===c&&(c=0,queueMicrotask(h))})},onWillRemoveListener(){r&&d>0&&(null==h||h())},onDidRemoveLastListener(){h=void 0,a.dispose()}});return null==o||o.add(u),u.event}e.None=()=>qo.None,e.defer=function(e,t){return n(e,()=>{},0,void 0,!0,void 0,t)},e.once=t,e.map=i,e.forEach=function(e,t,i){return r((i,s=null,r)=>e(e=>{t(e),i.call(s,e)},null,r),i)},e.filter=s,e.signal=function(e){return e},e.any=function(...e){return(t,i=null,s)=>function(e,t){return t instanceof Array?t.push(e):t&&t.add(e),e}(function(...e){return Ko(()=>Fo(e))}(...e.map(e=>e(e=>t.call(i,e)))),s)},e.reduce=function(e,t,s,r){let n=s;return i(e,e=>(n=t(n,e),n),r)},e.debounce=n,e.accumulate=function(t,i=0,s){return e.debounce(t,(e,t)=>e?(e.push(t),e):[t],i,void 0,!0,void 0,s)},e.latch=function(e,t=(e,t)=>e===t,i){let r,n=!0;return s(e,e=>{let i=n||!t(e,r);return n=!1,r=e,i},i)},e.split=function(t,i,s){return[e.filter(t,i,s),e.filter(t,e=>!i(e),s)]},e.buffer=function(e,t=!1,i=[],s){let r=i.slice(),n=e(e=>{r?r.push(e):a.fire(e)});s&&s.add(n);let o=()=>{null==r||r.forEach(e=>a.fire(e)),r=null},a=new da({onWillAddFirstListener(){n||(n=e(e=>a.fire(e)),s&&s.add(n))},onDidAddFirstListener(){r&&(t?setTimeout(o):o())},onDidRemoveLastListener(){n&&n.dispose(),n=null}});return s&&s.add(a),a.event},e.chain=function(e,t){return(i,s,r)=>{let n=t(new a);return e(function(e){let t=n.evaluate(e);t!==o&&i.call(s,t)},void 0,r)}};let o=Symbol("HaltChainable");class a{constructor(){this.steps=[]}map(e){return this.steps.push(e),this}forEach(e){return this.steps.push(t=>(e(t),t)),this}filter(e){return this.steps.push(t=>e(t)?t:o),this}reduce(e,t){let i=t;return this.steps.push(t=>(i=e(i,t),i)),this}latch(e=(e,t)=>e===t){let t,i=!0;return this.steps.push(s=>{let r=i||!e(s,t);return i=!1,t=s,r?s:o}),this}evaluate(e){for(let t of this.steps)if((e=t(e))===o)break;return e}}e.fromNodeEventEmitter=function(e,t,i=e=>e){let s=(...e)=>r.fire(i(...e)),r=new da({onWillAddFirstListener:()=>e.on(t,s),onDidRemoveLastListener:()=>e.removeListener(t,s)});return r.event},e.fromDOMEventEmitter=function(e,t,i=e=>e){let s=(...e)=>r.fire(i(...e)),r=new da({onWillAddFirstListener:()=>e.addEventListener(t,s),onDidRemoveLastListener:()=>e.removeEventListener(t,s)});return r.event},e.toPromise=function(e){return new Promise(i=>t(e)(i))},e.fromPromise=function(e){let t=new da;return e.then(e=>{t.fire(e)},()=>{t.fire(void 0)}).finally(()=>{t.dispose()}),t.event},e.forward=function(e,t){return e(e=>t.fire(e))},e.runAndSubscribe=function(e,t,i){return t(i),e(e=>t(e))};class l{constructor(e,t){this._observable=e,this._counter=0,this._hasChanged=!1;let i={onWillAddFirstListener:()=>{e.addObserver(this)},onDidRemoveLastListener:()=>{e.removeObserver(this)}};this.emitter=new da(i),t&&t.add(this.emitter)}beginUpdate(e){this._counter++}handlePossibleChange(e){}handleChange(e,t){this._hasChanged=!0}endUpdate(e){this._counter--,0===this._counter&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}e.fromObservable=function(e,t){return new l(e,t).emitter.event},e.fromObservableLight=function(e){return(t,i,s)=>{let r=0,n=!1,o={beginUpdate(){r++},endUpdate(){r--,0===r&&(e.reportChanges(),n&&(n=!1,t.call(i)))},handlePossibleChange(){},handleChange(){n=!0}};e.addObserver(o),e.reportChanges();let a={dispose(){e.removeObserver(o)}};return s instanceof Vo?s.add(a):Array.isArray(s)&&s.push(a),a}}})(Zo||(Zo={}));var ia=class e{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${e._idPool++}`,e.all.add(this)}start(e){this._stopWatch=new ta,this.listenerCount=e}stop(){if(this._stopWatch){let e=this._stopWatch.elapsed();this.durations.push(e),this.elapsedOverall+=e,this.invocationCount+=1,this._stopWatch=void 0}}};ia.all=new Set,ia._idPool=0;var sa=ia,ra=class e{constructor(t,i,s=(e._idPool++).toString(16).padStart(3,"0")){this._errorHandler=t,this.threshold=i,this.name=s,this._warnCountdown=0}dispose(){var e;null==(e=this._stacks)||e.clear()}check(e,t){let i=this.threshold;if(i<=0||t<i)return;this._stacks||(this._stacks=new Map);let s=this._stacks.get(e.value)||0;if(this._stacks.set(e.value,s+1),this._warnCountdown-=1,this._warnCountdown<=0){this._warnCountdown=.5*i;let[e,s]=this.getMostFrequentStack(),r=`[${this.name}] potential listener LEAK detected, having ${t} listeners already. MOST frequent listener (${s}):`;console.warn(r),console.warn(e);let n=new aa(r,e);this._errorHandler(n)}return()=>{let t=this._stacks.get(e.value)||0;this._stacks.set(e.value,t-1)}}getMostFrequentStack(){if(!this._stacks)return;let e,t=0;for(let[i,s]of this._stacks)(!e||t<s)&&(e=[i,s],t=s);return e}};ra._idPool=1;var na=ra,oa=class e{constructor(e){this.value=e}static create(){let t=new Error;return new e(t.stack??"")}print(){console.warn(this.value.split("\n").slice(2).join("\n"))}},aa=class extends Error{constructor(e,t){super(e),this.name="ListenerLeakError",this.stack=t}},la=class extends Error{constructor(e,t){super(e),this.name="ListenerRefusalError",this.stack=t}},ca=0,ha=class{constructor(e){this.value=e,this.id=ca++}},da=class{constructor(e){var t,i,s,r;this._size=0,this._options=e,this._leakageMon=(null==(t=this._options)?void 0:t.leakWarningThreshold)?new na((null==e?void 0:e.onListenerError)??Lo,(null==(i=this._options)?void 0:i.leakWarningThreshold)??-1):void 0,this._perfMon=(null==(s=this._options)?void 0:s._profName)?new sa(this._options._profName):void 0,this._deliveryQueue=null==(r=this._options)?void 0:r.deliveryQueue}dispose(){var e,t,i,s;this._disposed||(this._disposed=!0,(null==(e=this._deliveryQueue)?void 0:e.current)===this&&this._deliveryQueue.reset(),this._listeners&&(this._listeners=void 0,this._size=0),null==(i=null==(t=this._options)?void 0:t.onDidRemoveLastListener)||i.call(t),null==(s=this._leakageMon)||s.dispose())}get event(){return this._event??(this._event=(e,t,i)=>{var s,r,n,o,a;if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let e=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(e);let t=this._leakageMon.getMostFrequentStack()??["UNKNOWN stack",-1],i=new la(`${e}. HINT: Stack shows most frequent listener (${t[1]}-times)`,t[0]);return((null==(s=this._options)?void 0:s.onListenerError)||Lo)(i),qo.None}if(this._disposed)return qo.None;t&&(e=e.bind(t));let l,c=new ha(e);this._leakageMon&&this._size>=Math.ceil(.2*this._leakageMon.threshold)&&(c.stack=oa.create(),l=this._leakageMon.check(c.stack,this._size+1)),this._listeners?this._listeners instanceof ha?(this._deliveryQueue??(this._deliveryQueue=new ua),this._listeners=[this._listeners,c]):this._listeners.push(c):(null==(n=null==(r=this._options)?void 0:r.onWillAddFirstListener)||n.call(r,this),this._listeners=c,null==(a=null==(o=this._options)?void 0:o.onDidAddFirstListener)||a.call(o,this)),this._size++;let h=Ko(()=>{null==l||l(),this._removeListener(c)});return i instanceof Vo?i.add(h):Array.isArray(i)&&i.push(h),h}),this._event}_removeListener(e){var t,i,s,r;if(null==(i=null==(t=this._options)?void 0:t.onWillRemoveListener)||i.call(t,this),!this._listeners)return;if(1===this._size)return this._listeners=void 0,null==(r=null==(s=this._options)?void 0:s.onDidRemoveLastListener)||r.call(s,this),void(this._size=0);let n=this._listeners,o=n.indexOf(e);if(-1===o)throw console.log("disposed?",this._disposed),console.log("size?",this._size),console.log("arr?",JSON.stringify(this._listeners)),new Error("Attempted to dispose unknown listener");this._size--,n[o]=void 0;let a=this._deliveryQueue.current===this;if(2*this._size<=n.length){let e=0;for(let t=0;t<n.length;t++)n[t]?n[e++]=n[t]:a&&(this._deliveryQueue.end--,e<this._deliveryQueue.i&&this._deliveryQueue.i--);n.length=e}}_deliver(e,t){var i;if(!e)return;let s=(null==(i=this._options)?void 0:i.onListenerError)||Lo;if(s)try{e.value(t)}catch(r){s(r)}else e.value(t)}_deliverQueue(e){let t=e.current._listeners;for(;e.i<e.end;)this._deliver(t[e.i++],e.value);e.reset()}fire(e){var t,i,s,r;if((null==(t=this._deliveryQueue)?void 0:t.current)&&(this._deliverQueue(this._deliveryQueue),null==(i=this._perfMon)||i.stop()),null==(s=this._perfMon)||s.start(this._size),this._listeners)if(this._listeners instanceof ha)this._deliver(this._listeners,e);else{let t=this._deliveryQueue;t.enqueue(this,e,this._listeners.length),this._deliverQueue(t)}null==(r=this._perfMon)||r.stop()}hasListeners(){return this._size>0}},ua=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,i){this.i=0,this.end=i,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},fa=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new da,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new da,this.onDidChangeFullscreen=this._onDidChangeFullscreen.event,this.mapWindowIdToFullScreen=new Map}getZoomLevel(e){return this.mapWindowIdToZoomLevel.get(this.getWindowId(e))??0}setZoomLevel(e,t){if(this.getZoomLevel(t)===e)return;let i=this.getWindowId(t);this.mapWindowIdToZoomLevel.set(i,e),this._onDidChangeZoomLevel.fire(i)}getZoomFactor(e){return this.mapWindowIdToZoomFactor.get(this.getWindowId(e))??1}setZoomFactor(e,t){this.mapWindowIdToZoomFactor.set(this.getWindowId(t),e)}setFullscreen(e,t){if(this.isFullscreen(t)===e)return;let i=this.getWindowId(t);this.mapWindowIdToFullScreen.set(i,e),this._onDidChangeFullscreen.fire(i)}isFullscreen(e){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(e))}getWindowId(e){return e.vscodeWindowId}};fa.INSTANCE=new fa;var pa=fa;pa.INSTANCE.onDidChangeZoomLevel,pa.INSTANCE.onDidChangeFullscreen;var ma="object"==typeof navigator?navigator.userAgent:"",_a=ma.indexOf("Firefox")>=0,ga=ma.indexOf("AppleWebKit")>=0,va=ma.indexOf("Chrome")>=0,ya=!va&&ma.indexOf("Safari")>=0;ma.indexOf("Electron/"),ma.indexOf("Android");var xa=!1;if("function"==typeof Xo.matchMedia){let e=Xo.matchMedia("(display-mode: standalone) or (display-mode: window-controls-overlay)"),t=Xo.matchMedia("(display-mode: fullscreen)");xa=e.matches,function(e,t,i){"string"==typeof t&&(t=e.matchMedia(t)),t.addEventListener("change",i)}(Xo,e,({matches:e})=>{xa&&t.matches||(xa=e)})}var ba,wa,Sa="en",Ca=!1,ka=!1,Ea=!1,Na=!1,Ma=Sa,ja=globalThis;typeof ja.vscode<"u"&&typeof ja.vscode.process<"u"?wa=ja.vscode.process:typeof process<"u"&&"string"==typeof(null==(e=null==process?void 0:process.versions)?void 0:e.node)&&(wa=process);var Da="string"==typeof(null==(t=null==wa?void 0:wa.versions)?void 0:t.electron)&&"renderer"===(null==wa?void 0:wa.type);if("object"==typeof wa){Ca="win32"===wa.platform,ka="darwin"===wa.platform,(Ea="linux"===wa.platform)&&!!wa.env.SNAP&&wa.env.SNAP_REVISION,!!wa.env.CI||wa.env.BUILD_ARTIFACTSTAGINGDIRECTORY,Ma=Sa;let e=wa.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);t.userLocale,t.osLocale,Ma=t.resolvedLanguage||Sa,null==(i=t.languagePack)?void 0:i.translationsConfigFile}catch{}Na=!0}else"object"!=typeof navigator||Da?console.error("Unable to resolve platform."):(Ca=(ba=navigator.userAgent).indexOf("Windows")>=0,ka=ba.indexOf("Macintosh")>=0,(ba.indexOf("Macintosh")>=0||ba.indexOf("iPad")>=0||ba.indexOf("iPhone")>=0)&&!!navigator.maxTouchPoints&&navigator.maxTouchPoints,Ea=ba.indexOf("Linux")>=0,null==ba||ba.indexOf("Mobi"),Ma=globalThis._VSCODE_NLS_LANGUAGE||Sa,navigator.language.toLowerCase());var Ra,Pa,La=Ca,Ia=ka,Ta=Ea,Ba=Na,Oa=ba,Aa=Ma;(Pa=Ra||(Ra={})).value=function(){return Aa},Pa.isDefaultVariant=function(){return 2===Aa.length?"en"===Aa:Aa.length>=3&&"e"===Aa[0]&&"n"===Aa[1]&&"-"===Aa[2]},Pa.isDefault=function(){return"en"===Aa};var za="function"==typeof ja.postMessage&&!ja.importScripts;(()=>{if(za){let e=[];ja.addEventListener("message",t=>{if(t.data&&t.data.vscodeScheduleAsyncWork)for(let i=0,s=e.length;i<s;i++){let s=e[i];if(s.id===t.data.vscodeScheduleAsyncWork)return e.splice(i,1),void s.callback()}});let t=0;return i=>{let s=++t;e.push({id:s,callback:i}),ja.postMessage({vscodeScheduleAsyncWork:s},"*")}}})();var $a=!!(Oa&&Oa.indexOf("Chrome")>=0);Oa&&Oa.indexOf("Firefox"),!$a&&Oa&&Oa.indexOf("Safari"),Oa&&Oa.indexOf("Edg/"),Oa&&Oa.indexOf("Android");var Ha="object"==typeof navigator?navigator:{};Ba||document.queryCommandSupported&&document.queryCommandSupported("copy")||Ha&&Ha.clipboard&&Ha.clipboard.writeText,Ba||Ha&&Ha.clipboard&&Ha.clipboard.readText;var Wa,Fa,Ka=class{constructor(){this._keyCodeToStr=[],this._strToKeyCode=Object.create(null)}define(e,t){this._keyCodeToStr[e]=t,this._strToKeyCode[t.toLowerCase()]=e}keyCodeToStr(e){return this._keyCodeToStr[e]}strToKeyCode(e){return this._strToKeyCode[e.toLowerCase()]||0}},Ua=new Ka,Va=new Ka,qa=new Ka,Ya=new Array(230);(Fa=Wa||(Wa={})).toString=function(e){return Ua.keyCodeToStr(e)},Fa.fromString=function(e){return Ua.strToKeyCode(e)},Fa.toUserSettingsUS=function(e){return Va.keyCodeToStr(e)},Fa.toUserSettingsGeneral=function(e){return qa.keyCodeToStr(e)},Fa.fromUserSettings=function(e){return Va.strToKeyCode(e)||qa.strToKeyCode(e)},Fa.toElectronAccelerator=function(e){if(e>=98&&e<=113)return null;switch(e){case 16:return"Up";case 18:return"Down";case 15:return"Left";case 17:return"Right"}return Ua.keyCodeToStr(e)};var Xa=class e{constructor(e,t,i,s,r){this.ctrlKey=e,this.shiftKey=t,this.altKey=i,this.metaKey=s,this.keyCode=r}equals(t){return t instanceof e&&this.ctrlKey===t.ctrlKey&&this.shiftKey===t.shiftKey&&this.altKey===t.altKey&&this.metaKey===t.metaKey&&this.keyCode===t.keyCode}getHashCode(){return`K${this.ctrlKey?"1":"0"}${this.shiftKey?"1":"0"}${this.altKey?"1":"0"}${this.metaKey?"1":"0"}${this.keyCode}`}isModifierKey(){return 0===this.keyCode||5===this.keyCode||57===this.keyCode||6===this.keyCode||4===this.keyCode}toKeybinding(){return new Ga([this])}isDuplicateModifierCase(){return this.ctrlKey&&5===this.keyCode||this.shiftKey&&4===this.keyCode||this.altKey&&6===this.keyCode||this.metaKey&&57===this.keyCode}},Ga=class{constructor(e){if(0===e.length)throw new Error(`Illegal argument: ${"chords"}`);this.chords=e}getHashCode(){let e="";for(let t=0,i=this.chords.length;t<i;t++)0!==t&&(e+=";"),e+=this.chords[t].getHashCode();return e}equals(e){if(null===e||this.chords.length!==e.chords.length)return!1;for(let t=0;t<this.chords.length;t++)if(!this.chords[t].equals(e.chords[t]))return!1;return!0}};var Za=Ia?256:2048,Ja=Ia?2048:256,Qa=class{constructor(e){var t;this._standardKeyboardEventBrand=!0;let i=e;this.browserEvent=i,this.target=i.target,this.ctrlKey=i.ctrlKey,this.shiftKey=i.shiftKey,this.altKey=i.altKey,this.metaKey=i.metaKey,this.altGraphKey=null==(t=i.getModifierState)?void 0:t.call(i,"AltGraph"),this.keyCode=function(e){if(e.charCode){let t=String.fromCharCode(e.charCode).toUpperCase();return Wa.fromString(t)}let t=e.keyCode;if(3===t)return 7;if(_a)switch(t){case 59:return 85;case 60:if(Ta)return 97;break;case 61:return 86;case 107:return 109;case 109:return 111;case 173:return 88;case 224:if(Ia)return 57}else if(ga){if(Ia&&93===t)return 57;if(!Ia&&92===t)return 57}return Ya[t]||0}(i),this.code=i.code,this.ctrlKey=this.ctrlKey||5===this.keyCode,this.altKey=this.altKey||6===this.keyCode,this.shiftKey=this.shiftKey||4===this.keyCode,this.metaKey=this.metaKey||57===this.keyCode,this._asKeybinding=this._computeKeybinding(),this._asKeyCodeChord=this._computeKeyCodeChord()}preventDefault(){this.browserEvent&&this.browserEvent.preventDefault&&this.browserEvent.preventDefault()}stopPropagation(){this.browserEvent&&this.browserEvent.stopPropagation&&this.browserEvent.stopPropagation()}toKeyCodeChord(){return this._asKeyCodeChord}equals(e){return this._asKeybinding===e}_computeKeybinding(){let e=0;5!==this.keyCode&&4!==this.keyCode&&6!==this.keyCode&&57!==this.keyCode&&(e=this.keyCode);let t=0;return this.ctrlKey&&(t|=Za),this.altKey&&(t|=512),this.shiftKey&&(t|=1024),this.metaKey&&(t|=Ja),t|=e,t}_computeKeyCodeChord(){let e=0;return 5!==this.keyCode&&4!==this.keyCode&&6!==this.keyCode&&57!==this.keyCode&&(e=this.keyCode),new Xa(this.ctrlKey,this.shiftKey,this.altKey,this.metaKey,e)}},el=new WeakMap;function tl(e){if(!e.parent||e.parent===e)return null;try{let t=e.location,i=e.parent.location;if("null"!==t.origin&&"null"!==i.origin&&t.origin!==i.origin)return null}catch{return null}return e.parent}var il,sl=class{static getSameOriginWindowChain(e){let t=el.get(e);if(!t){t=[],el.set(e,t);let i,s=e;do{i=tl(s),i?t.push({window:new WeakRef(s),iframeElement:s.frameElement||null}):t.push({window:new WeakRef(s),iframeElement:null}),s=i}while(s)}return t.slice(0)}static getPositionOfChildWindowRelativeToAncestorWindow(e,t){if(!t||e===t)return{top:0,left:0};let i=0,s=0,r=this.getSameOriginWindowChain(e);for(let n of r){let e=n.window.deref();if(i+=(null==e?void 0:e.scrollY)??0,s+=(null==e?void 0:e.scrollX)??0,e===t||!n.iframeElement)break;let r=n.iframeElement.getBoundingClientRect();i+=r.top,s+=r.left}return{top:i,left:s}}},rl=class{constructor(e,t){this.timestamp=Date.now(),this.browserEvent=t,this.leftButton=0===t.button,this.middleButton=1===t.button,this.rightButton=2===t.button,this.buttons=t.buttons,this.target=t.target,this.detail=t.detail||1,"dblclick"===t.type&&(this.detail=2),this.ctrlKey=t.ctrlKey,this.shiftKey=t.shiftKey,this.altKey=t.altKey,this.metaKey=t.metaKey,"number"==typeof t.pageX?(this.posx=t.pageX,this.posy=t.pageY):(this.posx=t.clientX+this.target.ownerDocument.body.scrollLeft+this.target.ownerDocument.documentElement.scrollLeft,this.posy=t.clientY+this.target.ownerDocument.body.scrollTop+this.target.ownerDocument.documentElement.scrollTop);let i=sl.getPositionOfChildWindowRelativeToAncestorWindow(e,t.view);this.posx-=i.left,this.posy-=i.top}preventDefault(){this.browserEvent.preventDefault()}stopPropagation(){this.browserEvent.stopPropagation()}},nl=class{constructor(e,t=0,i=0){var s;this.browserEvent=e||null,this.target=e?e.target||e.targetNode||e.srcElement:null,this.deltaY=i,this.deltaX=t;let r=!1;if(va){let e=navigator.userAgent.match(/Chrome\/(\d+)/);r=(e?parseInt(e[1]):123)<=122}if(e){let t=e,i=e,n=(null==(s=e.view)?void 0:s.devicePixelRatio)||1;if(typeof t.wheelDeltaY<"u")this.deltaY=r?t.wheelDeltaY/(120*n):t.wheelDeltaY/120;else if(typeof i.VERTICAL_AXIS<"u"&&i.axis===i.VERTICAL_AXIS)this.deltaY=-i.detail/3;else if("wheel"===e.type){let t=e;t.deltaMode===t.DOM_DELTA_LINE?this.deltaY=_a&&!Ia?-e.deltaY/3:-e.deltaY:this.deltaY=-e.deltaY/40}if(typeof t.wheelDeltaX<"u")this.deltaX=ya&&La?-t.wheelDeltaX/120:r?t.wheelDeltaX/(120*n):t.wheelDeltaX/120;else if(typeof i.HORIZONTAL_AXIS<"u"&&i.axis===i.HORIZONTAL_AXIS)this.deltaX=-e.detail/3;else if("wheel"===e.type){let t=e;t.deltaMode===t.DOM_DELTA_LINE?this.deltaX=_a&&!Ia?-e.deltaX/3:-e.deltaX:this.deltaX=-e.deltaX/40}0===this.deltaY&&0===this.deltaX&&e.wheelDelta&&(this.deltaY=r?e.wheelDelta/(120*n):e.wheelDelta/120)}}preventDefault(){var e;null==(e=this.browserEvent)||e.preventDefault()}stopPropagation(){var e;null==(e=this.browserEvent)||e.stopPropagation()}},ol=Object.freeze(function(e,t){let i=setTimeout(e.bind(t),0);return{dispose(){clearTimeout(i)}}});(e=>{e.isCancellationToken=function(t){return t===e.None||t===e.Cancelled||t instanceof cl||!(!t||"object"!=typeof t)&&("boolean"==typeof t.isCancellationRequested&&"function"==typeof t.onCancellationRequested)},e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:Zo.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:ol})})(il||(il={}));var al,ll,cl=class{constructor(){this._isCancelled=!1,this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?ol:(this._emitter||(this._emitter=new da),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}},hl=class{constructor(e,t){this._isDisposed=!1,this._token=-1,"function"==typeof e&&"number"==typeof t&&this.setIfNotSet(e,t)}dispose(){this.cancel(),this._isDisposed=!0}cancel(){-1!==this._token&&(clearTimeout(this._token),this._token=-1)}cancelAndSet(e,t){if(this._isDisposed)throw new $o("Calling 'cancelAndSet' on a disposed TimeoutTimer");this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){if(this._isDisposed)throw new $o("Calling 'setIfNotSet' on a disposed TimeoutTimer");-1===this._token&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}},dl=class{constructor(){this.disposable=void 0,this.isDisposed=!1}cancel(){var e;null==(e=this.disposable)||e.dispose(),this.disposable=void 0}cancelAndSet(e,t,i=globalThis){if(this.isDisposed)throw new $o("Calling 'cancelAndSet' on a disposed IntervalTimer");this.cancel();let s=i.setInterval(()=>{e()},t);this.disposable=Ko(()=>{i.clearInterval(s),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}};(ll=al||(al={})).settled=async function(e){let t,i=await Promise.all(e.map(e=>e.then(e=>e,e=>{t||(t=e)})));if(typeof t<"u")throw t;return i},ll.withAsyncBody=function(e){return new Promise(async(t,i)=>{try{await e(t,i)}catch(Fa){i(Fa)}})};var ul=class e{static fromArray(t){return new e(e=>{e.emitMany(t)})}static fromPromise(t){return new e(async e=>{e.emitMany(await t)})}static fromPromises(t){return new e(async e=>{await Promise.all(t.map(async t=>e.emitOne(await t)))})}static merge(t){return new e(async e=>{await Promise.all(t.map(async t=>{for await(let i of t)e.emitOne(i)}))})}constructor(e,t){this._state=0,this._results=[],this._error=null,this._onReturn=t,this._onStateChanged=new da,queueMicrotask(async()=>{let t={emitOne:e=>this.emitOne(e),emitMany:e=>this.emitMany(e),reject:e=>this.reject(e)};try{await Promise.resolve(e(t)),this.resolve()}catch(i){this.reject(i)}finally{t.emitOne=void 0,t.emitMany=void 0,t.reject=void 0}})}[Symbol.asyncIterator](){let e=0;return{next:async()=>{for(;;){if(2===this._state)throw this._error;if(e<this._results.length)return{done:!1,value:this._results[e++]};if(1===this._state)return{done:!0,value:void 0};await Zo.toPromise(this._onStateChanged.event)}},return:async()=>{var e;return null==(e=this._onReturn)||e.call(this),{done:!0,value:void 0}}}}static map(t,i){return new e(async e=>{for await(let s of t)e.emitOne(i(s))})}map(t){return e.map(this,t)}static filter(t,i){return new e(async e=>{for await(let s of t)i(s)&&e.emitOne(s)})}filter(t){return e.filter(this,t)}static coalesce(t){return e.filter(t,e=>!!e)}coalesce(){return e.coalesce(this)}static async toPromise(e){let t=[];for await(let i of e)t.push(i);return t}toPromise(){return e.toPromise(this)}emitOne(e){0===this._state&&(this._results.push(e),this._onStateChanged.fire())}emitMany(e){0===this._state&&(this._results=this._results.concat(e),this._onStateChanged.fire())}resolve(){0===this._state&&(this._state=1,this._onStateChanged.fire())}reject(e){0===this._state&&(this._state=2,this._error=e,this._onStateChanged.fire())}};ul.EMPTY=ul.fromArray([]);var{getWindow:fl,getWindowId:pl,onDidRegisterWindow:ml}=function(){let e=new Map,t={window:Xo,disposables:new Vo};e.set(Xo.vscodeWindowId,t);let i=new da,s=new da,r=new da;return{onDidRegisterWindow:i.event,onWillUnregisterWindow:r.event,onDidUnregisterWindow:s.event,registerWindow(t){if(e.has(t.vscodeWindowId))return qo.None;let n=new Vo,o={window:t,disposables:n.add(new Vo)};return e.set(t.vscodeWindowId,o),n.add(Ko(()=>{e.delete(t.vscodeWindowId),s.fire(t)})),n.add(gl(t,wl.BEFORE_UNLOAD,()=>{r.fire(t)})),i.fire(o),n},getWindows:()=>e.values(),getWindowsCount:()=>e.size,getWindowId:e=>e.vscodeWindowId,hasWindow:t=>e.has(t),getWindowById:function(i,s){return("number"==typeof i?e.get(i):void 0)??(s?t:void 0)},getWindow(e){var t;let i=e;if(null==(t=null==i?void 0:i.ownerDocument)?void 0:t.defaultView)return i.ownerDocument.defaultView.window;let s=e;return(null==s?void 0:s.view)?s.view.window:Xo},getDocument:e=>fl(e).document}}(),_l=class{constructor(e,t,i,s){this._node=e,this._type=t,this._handler=i,this._options=s||!1,this._node.addEventListener(this._type,this._handler,this._options)}dispose(){this._handler&&(this._node.removeEventListener(this._type,this._handler,this._options),this._node=null,this._handler=null)}};function gl(e,t,i,s){return new _l(e,t,i,s)}var vl,yl=function(e,t,i,s){return gl(e,t,i,s)},xl=class extends dl{constructor(e){super(),this.defaultTarget=e&&fl(e)}cancelAndSet(e,t,i){return super.cancelAndSet(e,t,i??this.defaultTarget)}},bl=class{constructor(e,t=0){this._runner=e,this.priority=t,this._canceled=!1}dispose(){this._canceled=!0}execute(){if(!this._canceled)try{this._runner()}catch(Qu){Lo(Qu)}}static sort(e,t){return t.priority-e.priority}};!function(){let e=new Map,t=new Map,i=new Map,s=new Map;vl=(r,n,o=0)=>{let a=pl(r),l=new bl(n,o),c=e.get(a);return c||(c=[],e.set(a,c)),c.push(l),i.get(a)||(i.set(a,!0),r.requestAnimationFrame(()=>(r=>{i.set(r,!1);let n=e.get(r)??[];for(t.set(r,n),e.set(r,[]),s.set(r,!0);n.length>0;)n.sort(bl.sort),n.shift().execute();s.set(r,!1)})(a))),l}}();var wl={CLICK:"click",MOUSE_DOWN:"mousedown",MOUSE_OVER:"mouseover",MOUSE_LEAVE:"mouseleave",MOUSE_WHEEL:"wheel",POINTER_UP:"pointerup",POINTER_DOWN:"pointerdown",POINTER_MOVE:"pointermove",KEY_DOWN:"keydown",KEY_UP:"keyup",BEFORE_UNLOAD:"beforeunload",CHANGE:"change",FOCUS:"focus",BLUR:"blur",INPUT:"input"},Sl=class{constructor(e){this.domNode=e,this._maxWidth="",this._width="",this._height="",this._top="",this._left="",this._bottom="",this._right="",this._paddingTop="",this._paddingLeft="",this._paddingBottom="",this._paddingRight="",this._fontFamily="",this._fontWeight="",this._fontSize="",this._fontStyle="",this._fontFeatureSettings="",this._fontVariationSettings="",this._textDecoration="",this._lineHeight="",this._letterSpacing="",this._className="",this._display="",this._position="",this._visibility="",this._color="",this._backgroundColor="",this._layerHint=!1,this._contain="none",this._boxShadow=""}setMaxWidth(e){let t=Cl(e);this._maxWidth!==t&&(this._maxWidth=t,this.domNode.style.maxWidth=this._maxWidth)}setWidth(e){let t=Cl(e);this._width!==t&&(this._width=t,this.domNode.style.width=this._width)}setHeight(e){let t=Cl(e);this._height!==t&&(this._height=t,this.domNode.style.height=this._height)}setTop(e){let t=Cl(e);this._top!==t&&(this._top=t,this.domNode.style.top=this._top)}setLeft(e){let t=Cl(e);this._left!==t&&(this._left=t,this.domNode.style.left=this._left)}setBottom(e){let t=Cl(e);this._bottom!==t&&(this._bottom=t,this.domNode.style.bottom=this._bottom)}setRight(e){let t=Cl(e);this._right!==t&&(this._right=t,this.domNode.style.right=this._right)}setPaddingTop(e){let t=Cl(e);this._paddingTop!==t&&(this._paddingTop=t,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(e){let t=Cl(e);this._paddingLeft!==t&&(this._paddingLeft=t,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(e){let t=Cl(e);this._paddingBottom!==t&&(this._paddingBottom=t,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(e){let t=Cl(e);this._paddingRight!==t&&(this._paddingRight=t,this.domNode.style.paddingRight=this._paddingRight)}setFontFamily(e){this._fontFamily!==e&&(this._fontFamily=e,this.domNode.style.fontFamily=this._fontFamily)}setFontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this.domNode.style.fontWeight=this._fontWeight)}setFontSize(e){let t=Cl(e);this._fontSize!==t&&(this._fontSize=t,this.domNode.style.fontSize=this._fontSize)}setFontStyle(e){this._fontStyle!==e&&(this._fontStyle=e,this.domNode.style.fontStyle=this._fontStyle)}setFontFeatureSettings(e){this._fontFeatureSettings!==e&&(this._fontFeatureSettings=e,this.domNode.style.fontFeatureSettings=this._fontFeatureSettings)}setFontVariationSettings(e){this._fontVariationSettings!==e&&(this._fontVariationSettings=e,this.domNode.style.fontVariationSettings=this._fontVariationSettings)}setTextDecoration(e){this._textDecoration!==e&&(this._textDecoration=e,this.domNode.style.textDecoration=this._textDecoration)}setLineHeight(e){let t=Cl(e);this._lineHeight!==t&&(this._lineHeight=t,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(e){let t=Cl(e);this._letterSpacing!==t&&(this._letterSpacing=t,this.domNode.style.letterSpacing=this._letterSpacing)}setClassName(e){this._className!==e&&(this._className=e,this.domNode.className=this._className)}toggleClassName(e,t){this.domNode.classList.toggle(e,t),this._className=this.domNode.className}setDisplay(e){this._display!==e&&(this._display=e,this.domNode.style.display=this._display)}setPosition(e){this._position!==e&&(this._position=e,this.domNode.style.position=this._position)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this.domNode.style.visibility=this._visibility)}setColor(e){this._color!==e&&(this._color=e,this.domNode.style.color=this._color)}setBackgroundColor(e){this._backgroundColor!==e&&(this._backgroundColor=e,this.domNode.style.backgroundColor=this._backgroundColor)}setLayerHinting(e){this._layerHint!==e&&(this._layerHint=e,this.domNode.style.transform=this._layerHint?"translate3d(0px, 0px, 0px)":"")}setBoxShadow(e){this._boxShadow!==e&&(this._boxShadow=e,this.domNode.style.boxShadow=e)}setContain(e){this._contain!==e&&(this._contain=e,this.domNode.style.contain=this._contain)}setAttribute(e,t){this.domNode.setAttribute(e,t)}removeAttribute(e){this.domNode.removeAttribute(e)}appendChild(e){this.domNode.appendChild(e.domNode)}removeChild(e){this.domNode.removeChild(e.domNode)}};function Cl(e){return"number"==typeof e?`${e}px`:e}function kl(e){return new Sl(e)}var El,Nl,Ml=class{constructor(){this._hooks=new Vo,this._pointerMoveCallback=null,this._onStopCallback=null}dispose(){this.stopMonitoring(!1),this._hooks.dispose()}stopMonitoring(e,t){if(!this.isMonitoring())return;this._hooks.clear(),this._pointerMoveCallback=null;let i=this._onStopCallback;this._onStopCallback=null,e&&i&&i(t)}isMonitoring(){return!!this._pointerMoveCallback}startMonitoring(e,t,i,s,r){this.isMonitoring()&&this.stopMonitoring(!1),this._pointerMoveCallback=s,this._onStopCallback=r;let n=e;try{e.setPointerCapture(t),this._hooks.add(Ko(()=>{try{e.releasePointerCapture(t)}catch{}}))}catch{n=fl(e)}this._hooks.add(gl(n,wl.POINTER_MOVE,e=>{e.buttons===i?(e.preventDefault(),this._pointerMoveCallback(e)):this.stopMonitoring(!0)})),this._hooks.add(gl(n,wl.POINTER_UP,e=>this.stopMonitoring(!0)))}};(Nl=El||(El={})).Tap="-xterm-gesturetap",Nl.Change="-xterm-gesturechange",Nl.Start="-xterm-gesturestart",Nl.End="-xterm-gesturesend",Nl.Contextmenu="-xterm-gesturecontextmenu";var jl=class e extends qo{constructor(){super(),this.dispatched=!1,this.targets=new Qo,this.ignoreTargets=new Qo,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(Zo.runAndSubscribe(ml,({window:e,disposables:t})=>{t.add(gl(e.document,"touchstart",e=>this.onTouchStart(e),{passive:!1})),t.add(gl(e.document,"touchend",t=>this.onTouchEnd(e,t))),t.add(gl(e.document,"touchmove",e=>this.onTouchMove(e),{passive:!1}))},{window:Xo,disposables:this._store}))}static addTarget(t){if(!e.isTouchDevice())return qo.None;return e.INSTANCE||(e.INSTANCE=new e),Ko(e.INSTANCE.targets.push(t))}static ignoreTarget(t){if(!e.isTouchDevice())return qo.None;return e.INSTANCE||(e.INSTANCE=new e),Ko(e.INSTANCE.ignoreTargets.push(t))}static isTouchDevice(){return"ontouchstart"in Xo||navigator.maxTouchPoints>0}dispose(){this.handle&&(this.handle.dispose(),this.handle=null),super.dispose()}onTouchStart(e){let t=Date.now();this.handle&&(this.handle.dispose(),this.handle=null);for(let i=0,s=e.targetTouches.length;i<s;i++){let s=e.targetTouches.item(i);this.activeTouches[s.identifier]={id:s.identifier,initialTarget:s.target,initialTimeStamp:t,initialPageX:s.pageX,initialPageY:s.pageY,rollingTimestamps:[t],rollingPageX:[s.pageX],rollingPageY:[s.pageY]};let r=this.newGestureEvent(El.Start,s.target);r.pageX=s.pageX,r.pageY=s.pageY,this.dispatchEvent(r)}this.dispatched&&(e.preventDefault(),e.stopPropagation(),this.dispatched=!1)}onTouchEnd(t,i){let s=Date.now(),r=Object.keys(this.activeTouches).length;for(let n=0,o=i.changedTouches.length;n<o;n++){let o=i.changedTouches.item(n);if(!this.activeTouches.hasOwnProperty(String(o.identifier))){console.warn("move of an UNKNOWN touch",o);continue}let a=this.activeTouches[o.identifier],l=Date.now()-a.initialTimeStamp;if(l<e.HOLD_DELAY&&Math.abs(a.initialPageX-Ho(a.rollingPageX))<30&&Math.abs(a.initialPageY-Ho(a.rollingPageY))<30){let e=this.newGestureEvent(El.Tap,a.initialTarget);e.pageX=Ho(a.rollingPageX),e.pageY=Ho(a.rollingPageY),this.dispatchEvent(e)}else if(l>=e.HOLD_DELAY&&Math.abs(a.initialPageX-Ho(a.rollingPageX))<30&&Math.abs(a.initialPageY-Ho(a.rollingPageY))<30){let e=this.newGestureEvent(El.Contextmenu,a.initialTarget);e.pageX=Ho(a.rollingPageX),e.pageY=Ho(a.rollingPageY),this.dispatchEvent(e)}else if(1===r){let e=Ho(a.rollingPageX),i=Ho(a.rollingPageY),r=Ho(a.rollingTimestamps)-a.rollingTimestamps[0],n=e-a.rollingPageX[0],o=i-a.rollingPageY[0],l=[...this.targets].filter(e=>a.initialTarget instanceof Node&&e.contains(a.initialTarget));this.inertia(t,l,s,Math.abs(n)/r,n>0?1:-1,e,Math.abs(o)/r,o>0?1:-1,i)}this.dispatchEvent(this.newGestureEvent(El.End,a.initialTarget)),delete this.activeTouches[o.identifier]}this.dispatched&&(i.preventDefault(),i.stopPropagation(),this.dispatched=!1)}newGestureEvent(e,t){let i=document.createEvent("CustomEvent");return i.initEvent(e,!1,!0),i.initialTarget=t,i.tapCount=0,i}dispatchEvent(t){if(t.type===El.Tap){let i=(new Date).getTime(),s=0;s=i-this._lastSetTapCountTime>e.CLEAR_TAP_COUNT_TIME?1:2,this._lastSetTapCountTime=i,t.tapCount=s}else(t.type===El.Change||t.type===El.Contextmenu)&&(this._lastSetTapCountTime=0);if(t.initialTarget instanceof Node){for(let i of this.ignoreTargets)if(i.contains(t.initialTarget))return;let e=[];for(let i of this.targets)if(i.contains(t.initialTarget)){let s=0,r=t.initialTarget;for(;r&&r!==i;)s++,r=r.parentElement;e.push([s,i])}e.sort((e,t)=>e[0]-t[0]);for(let[i,s]of e)s.dispatchEvent(t),this.dispatched=!0}}inertia(t,i,s,r,n,o,a,l,c){this.handle=vl(t,()=>{let h=Date.now(),d=h-s,u=0,f=0,p=!0;r+=e.SCROLL_FRICTION*d,a+=e.SCROLL_FRICTION*d,r>0&&(p=!1,u=n*r*d),a>0&&(p=!1,f=l*a*d);let m=this.newGestureEvent(El.Change);m.translationX=u,m.translationY=f,i.forEach(e=>e.dispatchEvent(m)),p||this.inertia(t,i,h,r,n,o+u,a,l,c+f)})}onTouchMove(e){let t=Date.now();for(let i=0,s=e.changedTouches.length;i<s;i++){let s=e.changedTouches.item(i);if(!this.activeTouches.hasOwnProperty(String(s.identifier))){console.warn("end of an UNKNOWN touch",s);continue}let r=this.activeTouches[s.identifier],n=this.newGestureEvent(El.Change,r.initialTarget);n.translationX=s.pageX-Ho(r.rollingPageX),n.translationY=s.pageY-Ho(r.rollingPageY),n.pageX=s.pageX,n.pageY=s.pageY,this.dispatchEvent(n),r.rollingPageX.length>3&&(r.rollingPageX.shift(),r.rollingPageY.shift(),r.rollingTimestamps.shift()),r.rollingPageX.push(s.pageX),r.rollingPageY.push(s.pageY),r.rollingTimestamps.push(t)}this.dispatched&&(e.preventDefault(),e.stopPropagation(),this.dispatched=!1)}};jl.SCROLL_FRICTION=-.005,jl.HOLD_DELAY=700,jl.CLEAR_TAP_COUNT_TIME=400,Wn([function(e,t,i){let s=null,r=null;if("function"==typeof i.value?(s="value",r=i.value,0!==r.length&&console.warn("Memoize should only be used in functions with zero parameters")):"function"==typeof i.get&&(s="get",r=i.get),!r)throw new Error("not supported");let n=`$memoize$${t}`;i[s]=function(...e){return this.hasOwnProperty(n)||Object.defineProperty(this,n,{configurable:!1,enumerable:!1,writable:!1,value:r.apply(this,e)}),this[n]}}],jl,"isTouchDevice",1);var Dl=jl,Rl=class extends qo{onclick(e,t){this._register(gl(e,wl.CLICK,i=>t(new rl(fl(e),i))))}onmousedown(e,t){this._register(gl(e,wl.MOUSE_DOWN,i=>t(new rl(fl(e),i))))}onmouseover(e,t){this._register(gl(e,wl.MOUSE_OVER,i=>t(new rl(fl(e),i))))}onmouseleave(e,t){this._register(gl(e,wl.MOUSE_LEAVE,i=>t(new rl(fl(e),i))))}onkeydown(e,t){this._register(gl(e,wl.KEY_DOWN,e=>t(new Qa(e))))}onkeyup(e,t){this._register(gl(e,wl.KEY_UP,e=>t(new Qa(e))))}oninput(e,t){this._register(gl(e,wl.INPUT,t))}onblur(e,t){this._register(gl(e,wl.BLUR,t))}onfocus(e,t){this._register(gl(e,wl.FOCUS,t))}onchange(e,t){this._register(gl(e,wl.CHANGE,t))}ignoreGesture(e){return Dl.ignoreTarget(e)}},Pl=class extends Rl{constructor(e){super(),this._onActivate=e.onActivate,this.bgDomNode=document.createElement("div"),this.bgDomNode.className="arrow-background",this.bgDomNode.style.position="absolute",this.bgDomNode.style.width=e.bgWidth+"px",this.bgDomNode.style.height=e.bgHeight+"px",typeof e.top<"u"&&(this.bgDomNode.style.top="0px"),typeof e.left<"u"&&(this.bgDomNode.style.left="0px"),typeof e.bottom<"u"&&(this.bgDomNode.style.bottom="0px"),typeof e.right<"u"&&(this.bgDomNode.style.right="0px"),this.domNode=document.createElement("div"),this.domNode.className=e.className,this.domNode.style.position="absolute",this.domNode.style.width="11px",this.domNode.style.height="11px",typeof e.top<"u"&&(this.domNode.style.top=e.top+"px"),typeof e.left<"u"&&(this.domNode.style.left=e.left+"px"),typeof e.bottom<"u"&&(this.domNode.style.bottom=e.bottom+"px"),typeof e.right<"u"&&(this.domNode.style.right=e.right+"px"),this._pointerMoveMonitor=this._register(new Ml),this._register(yl(this.bgDomNode,wl.POINTER_DOWN,e=>this._arrowPointerDown(e))),this._register(yl(this.domNode,wl.POINTER_DOWN,e=>this._arrowPointerDown(e))),this._pointerdownRepeatTimer=this._register(new xl),this._pointerdownScheduleRepeatTimer=this._register(new hl)}_arrowPointerDown(e){if(!(e.target&&e.target instanceof Element))return;this._onActivate(),this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancelAndSet(()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,fl(e))},200),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,e=>{},()=>{this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancel()}),e.preventDefault()}},Ll=class e{constructor(e,t,i,s,r,n,o){this._forceIntegerValues=e,this._scrollStateBrand=void 0,this._forceIntegerValues&&(t|=0,i|=0,s|=0,r|=0,n|=0,o|=0),this.rawScrollLeft=s,this.rawScrollTop=o,t<0&&(t=0),s+t>i&&(s=i-t),s<0&&(s=0),r<0&&(r=0),o+r>n&&(o=n-r),o<0&&(o=0),this.width=t,this.scrollWidth=i,this.scrollLeft=s,this.height=r,this.scrollHeight=n,this.scrollTop=o}equals(e){return this.rawScrollLeft===e.rawScrollLeft&&this.rawScrollTop===e.rawScrollTop&&this.width===e.width&&this.scrollWidth===e.scrollWidth&&this.scrollLeft===e.scrollLeft&&this.height===e.height&&this.scrollHeight===e.scrollHeight&&this.scrollTop===e.scrollTop}withScrollDimensions(t,i){return new e(this._forceIntegerValues,typeof t.width<"u"?t.width:this.width,typeof t.scrollWidth<"u"?t.scrollWidth:this.scrollWidth,i?this.rawScrollLeft:this.scrollLeft,typeof t.height<"u"?t.height:this.height,typeof t.scrollHeight<"u"?t.scrollHeight:this.scrollHeight,i?this.rawScrollTop:this.scrollTop)}withScrollPosition(t){return new e(this._forceIntegerValues,this.width,this.scrollWidth,typeof t.scrollLeft<"u"?t.scrollLeft:this.rawScrollLeft,this.height,this.scrollHeight,typeof t.scrollTop<"u"?t.scrollTop:this.rawScrollTop)}createScrollEvent(e,t){let i=this.width!==e.width,s=this.scrollWidth!==e.scrollWidth,r=this.scrollLeft!==e.scrollLeft,n=this.height!==e.height,o=this.scrollHeight!==e.scrollHeight,a=this.scrollTop!==e.scrollTop;return{inSmoothScrolling:t,oldWidth:e.width,oldScrollWidth:e.scrollWidth,oldScrollLeft:e.scrollLeft,width:this.width,scrollWidth:this.scrollWidth,scrollLeft:this.scrollLeft,oldHeight:e.height,oldScrollHeight:e.scrollHeight,oldScrollTop:e.scrollTop,height:this.height,scrollHeight:this.scrollHeight,scrollTop:this.scrollTop,widthChanged:i,scrollWidthChanged:s,scrollLeftChanged:r,heightChanged:n,scrollHeightChanged:o,scrollTopChanged:a}}},Il=class extends qo{constructor(e){super(),this._scrollableBrand=void 0,this._onScroll=this._register(new da),this.onScroll=this._onScroll.event,this._smoothScrollDuration=e.smoothScrollDuration,this._scheduleAtNextAnimationFrame=e.scheduleAtNextAnimationFrame,this._state=new Ll(e.forceIntegerValues,0,0,0,0,0,0),this._smoothScrolling=null}dispose(){this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),super.dispose()}setSmoothScrollDuration(e){this._smoothScrollDuration=e}validateScrollPosition(e){return this._state.withScrollPosition(e)}getScrollDimensions(){return this._state}setScrollDimensions(e,t){var i;let s=this._state.withScrollDimensions(e,t);this._setState(s,!!this._smoothScrolling),null==(i=this._smoothScrolling)||i.acceptScrollDimensions(this._state)}getFutureScrollPosition(){return this._smoothScrolling?this._smoothScrolling.to:this._state}getCurrentScrollPosition(){return this._state}setScrollPositionNow(e){let t=this._state.withScrollPosition(e);this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),this._setState(t,!1)}setScrollPositionSmooth(e,t){if(0===this._smoothScrollDuration)return this.setScrollPositionNow(e);if(this._smoothScrolling){e={scrollLeft:typeof e.scrollLeft>"u"?this._smoothScrolling.to.scrollLeft:e.scrollLeft,scrollTop:typeof e.scrollTop>"u"?this._smoothScrolling.to.scrollTop:e.scrollTop};let i,s=this._state.withScrollPosition(e);if(this._smoothScrolling.to.scrollLeft===s.scrollLeft&&this._smoothScrolling.to.scrollTop===s.scrollTop)return;i=t?new Ol(this._smoothScrolling.from,s,this._smoothScrolling.startTime,this._smoothScrolling.duration):this._smoothScrolling.combine(this._state,s,this._smoothScrollDuration),this._smoothScrolling.dispose(),this._smoothScrolling=i}else{let t=this._state.withScrollPosition(e);this._smoothScrolling=Ol.start(this._state,t,this._smoothScrollDuration)}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}hasPendingScrollAnimation(){return!!this._smoothScrolling}_performSmoothScrolling(){if(!this._smoothScrolling)return;let e=this._smoothScrolling.tick(),t=this._state.withScrollPosition(e);if(this._setState(t,!0),this._smoothScrolling){if(e.isDone)return this._smoothScrolling.dispose(),void(this._smoothScrolling=null);this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}}_setState(e,t){let i=this._state;i.equals(e)||(this._state=e,this._onScroll.fire(this._state.createScrollEvent(i,t)))}},Tl=class{constructor(e,t,i){this.scrollLeft=e,this.scrollTop=t,this.isDone=i}};function Bl(e,t){let i=t-e;return function(t){return e+i*function(e){return 1-function(e){return Math.pow(e,3)}(1-e)}(t)}}var Ol=class e{constructor(e,t,i,s){this.from=e,this.to=t,this.duration=s,this.startTime=i,this.animationFrameDisposable=null,this._initAnimations()}_initAnimations(){this.scrollLeft=this._initAnimation(this.from.scrollLeft,this.to.scrollLeft,this.to.width),this.scrollTop=this._initAnimation(this.from.scrollTop,this.to.scrollTop,this.to.height)}_initAnimation(e,t,i){if(Math.abs(e-t)>2.5*i){let s,r;return e<t?(s=e+.75*i,r=t-.75*i):(s=e-.75*i,r=t+.75*i),function(e,t,i){return function(s){return s<i?e(s/i):t((s-i)/(1-i))}}(Bl(e,s),Bl(r,t),.33)}return Bl(e,t)}dispose(){null!==this.animationFrameDisposable&&(this.animationFrameDisposable.dispose(),this.animationFrameDisposable=null)}acceptScrollDimensions(e){this.to=e.withScrollPosition(this.to),this._initAnimations()}tick(){return this._tick(Date.now())}_tick(e){let t=(e-this.startTime)/this.duration;if(t<1){let e=this.scrollLeft(t),i=this.scrollTop(t);return new Tl(e,i,!1)}return new Tl(this.to.scrollLeft,this.to.scrollTop,!0)}combine(t,i,s){return e.start(t,i,s)}static start(t,i,s){s+=10;let r=Date.now()-10;return new e(t,i,r,s)}};var Al=class extends qo{constructor(e,t,i){super(),this._visibility=e,this._visibleClassName=t,this._invisibleClassName=i,this._domNode=null,this._isVisible=!1,this._isNeeded=!1,this._rawShouldBeVisible=!1,this._shouldBeVisible=!1,this._revealTimer=this._register(new hl)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this._updateShouldBeVisible())}setShouldBeVisible(e){this._rawShouldBeVisible=e,this._updateShouldBeVisible()}_applyVisibilitySetting(){return 2!==this._visibility&&(3===this._visibility||this._rawShouldBeVisible)}_updateShouldBeVisible(){let e=this._applyVisibilitySetting();this._shouldBeVisible!==e&&(this._shouldBeVisible=e,this.ensureVisibility())}setIsNeeded(e){this._isNeeded!==e&&(this._isNeeded=e,this.ensureVisibility())}setDomNode(e){this._domNode=e,this._domNode.setClassName(this._invisibleClassName),this.setShouldBeVisible(!1)}ensureVisibility(){this._isNeeded?this._shouldBeVisible?this._reveal():this._hide(!0):this._hide(!1)}_reveal(){this._isVisible||(this._isVisible=!0,this._revealTimer.setIfNotSet(()=>{var e;null==(e=this._domNode)||e.setClassName(this._visibleClassName)},0))}_hide(e){var t;this._revealTimer.cancel(),this._isVisible&&(this._isVisible=!1,null==(t=this._domNode)||t.setClassName(this._invisibleClassName+(e?" fade":"")))}},zl=class extends Rl{constructor(e){super(),this._lazyRender=e.lazyRender,this._host=e.host,this._scrollable=e.scrollable,this._scrollByPage=e.scrollByPage,this._scrollbarState=e.scrollbarState,this._visibilityController=this._register(new Al(e.visibility,"visible scrollbar "+e.extraScrollbarClassName,"invisible scrollbar "+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new Ml),this._shouldRender=!0,this.domNode=kl(document.createElement("div")),this.domNode.setAttribute("role","presentation"),this.domNode.setAttribute("aria-hidden","true"),this._visibilityController.setDomNode(this.domNode),this.domNode.setPosition("absolute"),this._register(gl(this.domNode.domNode,wl.POINTER_DOWN,e=>this._domNodePointerDown(e)))}_createArrow(e){let t=this._register(new Pl(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,i,s){this.slider=kl(document.createElement("div")),this.slider.setClassName("slider"),this.slider.setPosition("absolute"),this.slider.setTop(e),this.slider.setLeft(t),"number"==typeof i&&this.slider.setWidth(i),"number"==typeof s&&this.slider.setHeight(s),this.slider.setLayerHinting(!0),this.slider.setContain("strict"),this.domNode.domNode.appendChild(this.slider.domNode),this._register(gl(this.slider.domNode,wl.POINTER_DOWN,e=>{0===e.button&&(e.preventDefault(),this._sliderPointerDown(e))})),this.onclick(this.slider.domNode,e=>{e.leftButton&&e.stopPropagation()})}_onElementSize(e){return this._scrollbarState.setVisibleSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollSize(e){return this._scrollbarState.setScrollSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollPosition(e){return this._scrollbarState.setScrollPosition(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}beginReveal(){this._visibilityController.setShouldBeVisible(!0)}beginHide(){this._visibilityController.setShouldBeVisible(!1)}render(){this._shouldRender&&(this._shouldRender=!1,this._renderDomNode(this._scrollbarState.getRectangleLargeSize(),this._scrollbarState.getRectangleSmallSize()),this._updateSlider(this._scrollbarState.getSliderSize(),this._scrollbarState.getArrowSize()+this._scrollbarState.getSliderPosition()))}_domNodePointerDown(e){e.target===this.domNode.domNode&&this._onPointerDown(e)}delegatePointerDown(e){let t=this.domNode.domNode.getClientRects()[0].top,i=t+this._scrollbarState.getSliderPosition(),s=t+this._scrollbarState.getSliderPosition()+this._scrollbarState.getSliderSize(),r=this._sliderPointerPosition(e);i<=r&&r<=s?0===e.button&&(e.preventDefault(),this._sliderPointerDown(e)):this._onPointerDown(e)}_onPointerDown(e){let t,i;if(e.target===this.domNode.domNode&&"number"==typeof e.offsetX&&"number"==typeof e.offsetY)t=e.offsetX,i=e.offsetY;else{let s=function(e){let t=e.getBoundingClientRect(),i=fl(e);return{left:t.left+i.scrollX,top:t.top+i.scrollY,width:t.width,height:t.height}}(this.domNode.domNode);t=e.pageX-s.left,i=e.pageY-s.top}let s=this._pointerDownRelativePosition(t,i);this._setDesiredScrollPositionNow(this._scrollByPage?this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(s):this._scrollbarState.getDesiredScrollPositionFromOffset(s)),0===e.button&&(e.preventDefault(),this._sliderPointerDown(e))}_sliderPointerDown(e){if(!(e.target&&e.target instanceof Element))return;let t=this._sliderPointerPosition(e),i=this._sliderOrthogonalPointerPosition(e),s=this._scrollbarState.clone();this.slider.toggleClassName("active",!0),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,e=>{let r=this._sliderOrthogonalPointerPosition(e),n=Math.abs(r-i);if(La&&n>140)return void this._setDesiredScrollPositionNow(s.getScrollPosition());let o=this._sliderPointerPosition(e)-t;this._setDesiredScrollPositionNow(s.getDesiredScrollPositionFromDelta(o))},()=>{this.slider.toggleClassName("active",!1),this._host.onDragEnd()}),this._host.onDragStart()}_setDesiredScrollPositionNow(e){let t={};this.writeScrollPosition(t,e),this._scrollable.setScrollPositionNow(t)}updateScrollbarSize(e){this._updateScrollbarSize(e),this._scrollbarState.setScrollbarSize(e),this._shouldRender=!0,this._lazyRender||this.render()}isNeeded(){return this._scrollbarState.isNeeded()}},$l=class e{constructor(e,t,i,s,r,n){this._scrollbarSize=Math.round(t),this._oppositeScrollbarSize=Math.round(i),this._arrowSize=Math.round(e),this._visibleSize=s,this._scrollSize=r,this._scrollPosition=n,this._computedAvailableSize=0,this._computedIsNeeded=!1,this._computedSliderSize=0,this._computedSliderRatio=0,this._computedSliderPosition=0,this._refreshComputedValues()}clone(){return new e(this._arrowSize,this._scrollbarSize,this._oppositeScrollbarSize,this._visibleSize,this._scrollSize,this._scrollPosition)}setVisibleSize(e){let t=Math.round(e);return this._visibleSize!==t&&(this._visibleSize=t,this._refreshComputedValues(),!0)}setScrollSize(e){let t=Math.round(e);return this._scrollSize!==t&&(this._scrollSize=t,this._refreshComputedValues(),!0)}setScrollPosition(e){let t=Math.round(e);return this._scrollPosition!==t&&(this._scrollPosition=t,this._refreshComputedValues(),!0)}setScrollbarSize(e){this._scrollbarSize=Math.round(e)}setOppositeScrollbarSize(e){this._oppositeScrollbarSize=Math.round(e)}static _computeValues(e,t,i,s,r){let n=Math.max(0,i-e),o=Math.max(0,n-2*t),a=s>0&&s>i;if(!a)return{computedAvailableSize:Math.round(n),computedIsNeeded:a,computedSliderSize:Math.round(o),computedSliderRatio:0,computedSliderPosition:0};let l=Math.round(Math.max(20,Math.floor(i*o/s))),c=(o-l)/(s-i),h=r*c;return{computedAvailableSize:Math.round(n),computedIsNeeded:a,computedSliderSize:Math.round(l),computedSliderRatio:c,computedSliderPosition:Math.round(h)}}_refreshComputedValues(){let t=e._computeValues(this._oppositeScrollbarSize,this._arrowSize,this._visibleSize,this._scrollSize,this._scrollPosition);this._computedAvailableSize=t.computedAvailableSize,this._computedIsNeeded=t.computedIsNeeded,this._computedSliderSize=t.computedSliderSize,this._computedSliderRatio=t.computedSliderRatio,this._computedSliderPosition=t.computedSliderPosition}getArrowSize(){return this._arrowSize}getScrollPosition(){return this._scrollPosition}getRectangleLargeSize(){return this._computedAvailableSize}getRectangleSmallSize(){return this._scrollbarSize}isNeeded(){return this._computedIsNeeded}getSliderSize(){return this._computedSliderSize}getSliderPosition(){return this._computedSliderPosition}getDesiredScrollPositionFromOffset(e){if(!this._computedIsNeeded)return 0;let t=e-this._arrowSize-this._computedSliderSize/2;return Math.round(t/this._computedSliderRatio)}getDesiredScrollPositionFromOffsetPaged(e){if(!this._computedIsNeeded)return 0;let t=e-this._arrowSize,i=this._scrollPosition;return t<this._computedSliderPosition?i-=this._visibleSize:i+=this._visibleSize,i}getDesiredScrollPositionFromDelta(e){if(!this._computedIsNeeded)return 0;let t=this._computedSliderPosition+e;return Math.round(t/this._computedSliderRatio)}},Hl=class extends zl{constructor(e,t,i){let s=e.getScrollDimensions(),r=e.getCurrentScrollPosition();if(super({lazyRender:t.lazyRender,host:i,scrollbarState:new $l(t.horizontalHasArrows?t.arrowSize:0,2===t.horizontal?0:t.horizontalScrollbarSize,2===t.vertical?0:t.verticalScrollbarSize,s.width,s.scrollWidth,r.scrollLeft),visibility:t.horizontal,extraScrollbarClassName:"horizontal",scrollable:e,scrollByPage:t.scrollByPage}),t.horizontalHasArrows)throw new Error("horizontalHasArrows is not supported in xterm.js");this._createSlider(Math.floor((t.horizontalScrollbarSize-t.horizontalSliderSize)/2),0,void 0,t.horizontalSliderSize)}_updateSlider(e,t){this.slider.setWidth(e),this.slider.setLeft(t)}_renderDomNode(e,t){this.domNode.setWidth(e),this.domNode.setHeight(t),this.domNode.setLeft(0),this.domNode.setBottom(0)}onDidScroll(e){return this._shouldRender=this._onElementScrollSize(e.scrollWidth)||this._shouldRender,this._shouldRender=this._onElementScrollPosition(e.scrollLeft)||this._shouldRender,this._shouldRender=this._onElementSize(e.width)||this._shouldRender,this._shouldRender}_pointerDownRelativePosition(e,t){return e}_sliderPointerPosition(e){return e.pageX}_sliderOrthogonalPointerPosition(e){return e.pageY}_updateScrollbarSize(e){this.slider.setHeight(e)}writeScrollPosition(e,t){e.scrollLeft=t}updateOptions(e){this.updateScrollbarSize(2===e.horizontal?0:e.horizontalScrollbarSize),this._scrollbarState.setOppositeScrollbarSize(2===e.vertical?0:e.verticalScrollbarSize),this._visibilityController.setVisibility(e.horizontal),this._scrollByPage=e.scrollByPage}},Wl=class extends zl{constructor(e,t,i){let s=e.getScrollDimensions(),r=e.getCurrentScrollPosition();if(super({lazyRender:t.lazyRender,host:i,scrollbarState:new $l(t.verticalHasArrows?t.arrowSize:0,2===t.vertical?0:t.verticalScrollbarSize,0,s.height,s.scrollHeight,r.scrollTop),visibility:t.vertical,extraScrollbarClassName:"vertical",scrollable:e,scrollByPage:t.scrollByPage}),t.verticalHasArrows)throw new Error("horizontalHasArrows is not supported in xterm.js");this._createSlider(0,Math.floor((t.verticalScrollbarSize-t.verticalSliderSize)/2),t.verticalSliderSize,void 0)}_updateSlider(e,t){this.slider.setHeight(e),this.slider.setTop(t)}_renderDomNode(e,t){this.domNode.setWidth(t),this.domNode.setHeight(e),this.domNode.setRight(0),this.domNode.setTop(0)}onDidScroll(e){return this._shouldRender=this._onElementScrollSize(e.scrollHeight)||this._shouldRender,this._shouldRender=this._onElementScrollPosition(e.scrollTop)||this._shouldRender,this._shouldRender=this._onElementSize(e.height)||this._shouldRender,this._shouldRender}_pointerDownRelativePosition(e,t){return t}_sliderPointerPosition(e){return e.pageY}_sliderOrthogonalPointerPosition(e){return e.pageX}_updateScrollbarSize(e){this.slider.setWidth(e)}writeScrollPosition(e,t){e.scrollTop=t}updateOptions(e){this.updateScrollbarSize(2===e.vertical?0:e.verticalScrollbarSize),this._scrollbarState.setOppositeScrollbarSize(0),this._visibilityController.setVisibility(e.vertical),this._scrollByPage=e.scrollByPage}},Fl=class{constructor(e,t,i){this.timestamp=e,this.deltaX=t,this.deltaY=i,this.score=0}},Kl=class{constructor(){this._capacity=5,this._memory=[],this._front=-1,this._rear=-1}isPhysicalMouseWheel(){if(-1===this._front&&-1===this._rear)return!1;let e=1,t=0,i=1,s=this._rear;for(;;){let r=s===this._front?e:Math.pow(2,-i);if(e-=r,t+=this._memory[s].score*r,s===this._front)break;s=(this._capacity+s-1)%this._capacity,i++}return t<=.5}acceptStandardWheelEvent(e){if(va){let i=fl(e.browserEvent),s=(t=i,pa.INSTANCE.getZoomFactor(t));this.accept(Date.now(),e.deltaX*s,e.deltaY*s)}else this.accept(Date.now(),e.deltaX,e.deltaY);var t}accept(e,t,i){let s=null,r=new Fl(e,t,i);-1===this._front&&-1===this._rear?(this._memory[0]=r,this._front=0,this._rear=0):(s=this._memory[this._rear],this._rear=(this._rear+1)%this._capacity,this._rear===this._front&&(this._front=(this._front+1)%this._capacity),this._memory[this._rear]=r),r.score=this._computeScore(r,s)}_computeScore(e,t){if(Math.abs(e.deltaX)>0&&Math.abs(e.deltaY)>0)return 1;let i=.5;if((!this._isAlmostInt(e.deltaX)||!this._isAlmostInt(e.deltaY))&&(i+=.25),t){let s=Math.abs(e.deltaX),r=Math.abs(e.deltaY),n=Math.abs(t.deltaX),o=Math.abs(t.deltaY),a=Math.max(Math.min(s,n),1),l=Math.max(Math.min(r,o),1),c=Math.max(s,n),h=Math.max(r,o);c%a===0&&h%l===0&&(i-=.5)}return Math.min(Math.max(i,0),1)}_isAlmostInt(e){return Math.abs(Math.round(e)-e)<.01}};Kl.INSTANCE=new Kl;var Ul=Kl,Vl=class extends Rl{constructor(e,t,i){super(),this._onScroll=this._register(new da),this.onScroll=this._onScroll.event,this._onWillScroll=this._register(new da),this.onWillScroll=this._onWillScroll.event,this._options=function(e){let t={lazyRender:typeof e.lazyRender<"u"&&e.lazyRender,className:typeof e.className<"u"?e.className:"",useShadows:!(typeof e.useShadows<"u")||e.useShadows,handleMouseWheel:!(typeof e.handleMouseWheel<"u")||e.handleMouseWheel,flipAxes:typeof e.flipAxes<"u"&&e.flipAxes,consumeMouseWheelIfScrollbarIsNeeded:typeof e.consumeMouseWheelIfScrollbarIsNeeded<"u"&&e.consumeMouseWheelIfScrollbarIsNeeded,alwaysConsumeMouseWheel:typeof e.alwaysConsumeMouseWheel<"u"&&e.alwaysConsumeMouseWheel,scrollYToX:typeof e.scrollYToX<"u"&&e.scrollYToX,mouseWheelScrollSensitivity:typeof e.mouseWheelScrollSensitivity<"u"?e.mouseWheelScrollSensitivity:1,fastScrollSensitivity:typeof e.fastScrollSensitivity<"u"?e.fastScrollSensitivity:5,scrollPredominantAxis:!(typeof e.scrollPredominantAxis<"u")||e.scrollPredominantAxis,mouseWheelSmoothScroll:!(typeof e.mouseWheelSmoothScroll<"u")||e.mouseWheelSmoothScroll,arrowSize:typeof e.arrowSize<"u"?e.arrowSize:11,listenOnDomNode:typeof e.listenOnDomNode<"u"?e.listenOnDomNode:null,horizontal:typeof e.horizontal<"u"?e.horizontal:1,horizontalScrollbarSize:typeof e.horizontalScrollbarSize<"u"?e.horizontalScrollbarSize:10,horizontalSliderSize:typeof e.horizontalSliderSize<"u"?e.horizontalSliderSize:0,horizontalHasArrows:typeof e.horizontalHasArrows<"u"&&e.horizontalHasArrows,vertical:typeof e.vertical<"u"?e.vertical:1,verticalScrollbarSize:typeof e.verticalScrollbarSize<"u"?e.verticalScrollbarSize:10,verticalHasArrows:typeof e.verticalHasArrows<"u"&&e.verticalHasArrows,verticalSliderSize:typeof e.verticalSliderSize<"u"?e.verticalSliderSize:0,scrollByPage:typeof e.scrollByPage<"u"&&e.scrollByPage};return t.horizontalSliderSize=typeof e.horizontalSliderSize<"u"?e.horizontalSliderSize:t.horizontalScrollbarSize,t.verticalSliderSize=typeof e.verticalSliderSize<"u"?e.verticalSliderSize:t.verticalScrollbarSize,Ia&&(t.className+=" mac"),t}(t),this._scrollable=i,this._register(this._scrollable.onScroll(e=>{this._onWillScroll.fire(e),this._onDidScroll(e),this._onScroll.fire(e)}));let s={onMouseWheel:e=>this._onMouseWheel(e),onDragStart:()=>this._onDragStart(),onDragEnd:()=>this._onDragEnd()};this._verticalScrollbar=this._register(new Wl(this._scrollable,this._options,s)),this._horizontalScrollbar=this._register(new Hl(this._scrollable,this._options,s)),this._domNode=document.createElement("div"),this._domNode.className="xterm-scrollable-element "+this._options.className,this._domNode.setAttribute("role","presentation"),this._domNode.style.position="relative",this._domNode.appendChild(e),this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode),this._domNode.appendChild(this._verticalScrollbar.domNode.domNode),this._options.useShadows?(this._leftShadowDomNode=kl(document.createElement("div")),this._leftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=kl(document.createElement("div")),this._topShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=kl(document.createElement("div")),this._topLeftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topLeftShadowDomNode.domNode)):(this._leftShadowDomNode=null,this._topShadowDomNode=null,this._topLeftShadowDomNode=null),this._listenOnDomNode=this._options.listenOnDomNode||this._domNode,this._mouseWheelToDispose=[],this._setListeningToMouseWheel(this._options.handleMouseWheel),this.onmouseover(this._listenOnDomNode,e=>this._onMouseOver(e)),this.onmouseleave(this._listenOnDomNode,e=>this._onMouseLeave(e)),this._hideTimeout=this._register(new hl),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=Fo(this._mouseWheelToDispose),super.dispose()}getDomNode(){return this._domNode}getOverviewRulerLayoutInfo(){return{parent:this._domNode,insertBefore:this._verticalScrollbar.domNode.domNode}}delegateVerticalScrollbarPointerDown(e){this._verticalScrollbar.delegatePointerDown(e)}getScrollDimensions(){return this._scrollable.getScrollDimensions()}setScrollDimensions(e){this._scrollable.setScrollDimensions(e,!1)}updateClassName(e){this._options.className=e,Ia&&(this._options.className+=" mac"),this._domNode.className="xterm-scrollable-element "+this._options.className}updateOptions(e){typeof e.handleMouseWheel<"u"&&(this._options.handleMouseWheel=e.handleMouseWheel,this._setListeningToMouseWheel(this._options.handleMouseWheel)),typeof e.mouseWheelScrollSensitivity<"u"&&(this._options.mouseWheelScrollSensitivity=e.mouseWheelScrollSensitivity),typeof e.fastScrollSensitivity<"u"&&(this._options.fastScrollSensitivity=e.fastScrollSensitivity),typeof e.scrollPredominantAxis<"u"&&(this._options.scrollPredominantAxis=e.scrollPredominantAxis),typeof e.horizontal<"u"&&(this._options.horizontal=e.horizontal),typeof e.vertical<"u"&&(this._options.vertical=e.vertical),typeof e.horizontalScrollbarSize<"u"&&(this._options.horizontalScrollbarSize=e.horizontalScrollbarSize),typeof e.verticalScrollbarSize<"u"&&(this._options.verticalScrollbarSize=e.verticalScrollbarSize),typeof e.scrollByPage<"u"&&(this._options.scrollByPage=e.scrollByPage),this._horizontalScrollbar.updateOptions(this._options),this._verticalScrollbar.updateOptions(this._options),this._options.lazyRender||this._render()}setRevealOnScroll(e){this._revealOnScroll=e}delegateScrollFromMouseWheelEvent(e){this._onMouseWheel(new nl(e))}_setListeningToMouseWheel(e){if(this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=Fo(this._mouseWheelToDispose),e)){let e=e=>{this._onMouseWheel(new nl(e))};this._mouseWheelToDispose.push(gl(this._listenOnDomNode,wl.MOUSE_WHEEL,e,{passive:!1}))}}_onMouseWheel(e){var t;if(null==(t=e.browserEvent)?void 0:t.defaultPrevented)return;let i=Ul.INSTANCE;i.acceptStandardWheelEvent(e);let s=!1;if(e.deltaY||e.deltaX){let t=e.deltaY*this._options.mouseWheelScrollSensitivity,r=e.deltaX*this._options.mouseWheelScrollSensitivity;this._options.scrollPredominantAxis&&(this._options.scrollYToX&&r+t===0?r=t=0:Math.abs(t)>=Math.abs(r)?r=0:t=0),this._options.flipAxes&&([t,r]=[r,t]);let n=!Ia&&e.browserEvent&&e.browserEvent.shiftKey;(this._options.scrollYToX||n)&&!r&&(r=t,t=0),e.browserEvent&&e.browserEvent.altKey&&(r*=this._options.fastScrollSensitivity,t*=this._options.fastScrollSensitivity);let o=this._scrollable.getFutureScrollPosition(),a={};if(t){let e=50*t,i=o.scrollTop-(e<0?Math.floor(e):Math.ceil(e));this._verticalScrollbar.writeScrollPosition(a,i)}if(r){let e=50*r,t=o.scrollLeft-(e<0?Math.floor(e):Math.ceil(e));this._horizontalScrollbar.writeScrollPosition(a,t)}a=this._scrollable.validateScrollPosition(a),(o.scrollLeft!==a.scrollLeft||o.scrollTop!==a.scrollTop)&&(this._options.mouseWheelSmoothScroll&&i.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(a):this._scrollable.setScrollPositionNow(a),s=!0)}let r=s;!r&&this._options.alwaysConsumeMouseWheel&&(r=!0),!r&&this._options.consumeMouseWheelIfScrollbarIsNeeded&&(this._verticalScrollbar.isNeeded()||this._horizontalScrollbar.isNeeded())&&(r=!0),r&&(e.preventDefault(),e.stopPropagation())}_onDidScroll(e){this._shouldRender=this._horizontalScrollbar.onDidScroll(e)||this._shouldRender,this._shouldRender=this._verticalScrollbar.onDidScroll(e)||this._shouldRender,this._options.useShadows&&(this._shouldRender=!0),this._revealOnScroll&&this._reveal(),this._options.lazyRender||this._render()}renderNow(){if(!this._options.lazyRender)throw new Error("Please use `lazyRender` together with `renderNow`!");this._render()}_render(){if(this._shouldRender&&(this._shouldRender=!1,this._horizontalScrollbar.render(),this._verticalScrollbar.render(),this._options.useShadows)){let e=this._scrollable.getCurrentScrollPosition(),t=e.scrollTop>0,i=e.scrollLeft>0,s=i?" left":"",r=t?" top":"",n=i||t?" top-left-corner":"";this._leftShadowDomNode.setClassName(`shadow${s}`),this._topShadowDomNode.setClassName(`shadow${r}`),this._topLeftShadowDomNode.setClassName(`shadow${n}${r}${s}`)}}_onDragStart(){this._isDragging=!0,this._reveal()}_onDragEnd(){this._isDragging=!1,this._hide()}_onMouseLeave(e){this._mouseIsOver=!1,this._hide()}_onMouseOver(e){this._mouseIsOver=!0,this._reveal()}_reveal(){this._verticalScrollbar.beginReveal(),this._horizontalScrollbar.beginReveal(),this._scheduleHide()}_hide(){!this._mouseIsOver&&!this._isDragging&&(this._verticalScrollbar.beginHide(),this._horizontalScrollbar.beginHide())}_scheduleHide(){!this._mouseIsOver&&!this._isDragging&&this._hideTimeout.cancelAndSet(()=>this._hide(),500)}},ql=class extends Vl{constructor(e,t,i){super(e,t,i)}setScrollPosition(e){e.reuseAnimation?this._scrollable.setScrollPositionSmooth(e,e.reuseAnimation):this._scrollable.setScrollPositionNow(e)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}};var Yl=class extends qo{constructor(e,t,i,s,r,n,o,a){super(),this._bufferService=i,this._optionsService=o,this._renderService=a,this._onRequestScrollLines=this._register(new da),this.onRequestScrollLines=this._onRequestScrollLines.event,this._isSyncing=!1,this._isHandlingScroll=!1,this._suppressOnScrollHandler=!1;let l=this._register(new Il({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:e=>vl(s.window,e)}));this._register(this._optionsService.onSpecificOptionChange("smoothScrollDuration",()=>{l.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new ql(t,{vertical:1,horizontal:2,useShadows:!1,mouseWheelSmoothScroll:!0,...this._getChangeOptions()},l)),this._register(this._optionsService.onMultipleOptionChange(["scrollSensitivity","fastScrollSensitivity","overviewRuler"],()=>this._scrollableElement.updateOptions(this._getChangeOptions()))),this._register(r.onProtocolChange(e=>{this._scrollableElement.updateOptions({handleMouseWheel:!(16&e)})})),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(Zo.runAndSubscribe(n.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=n.colors.background.css})),e.appendChild(this._scrollableElement.getDomNode()),this._register(Ko(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=s.mainDocument.createElement("style"),t.appendChild(this._styleElement),this._register(Ko(()=>this._styleElement.remove())),this._register(Zo.runAndSubscribe(n.onChangeColors,()=>{this._styleElement.textContent=[".xterm .xterm-scrollable-element > .scrollbar > .slider {",` background: ${n.colors.scrollbarSliderBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider:hover {",` background: ${n.colors.scrollbarSliderHoverBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider.active {",` background: ${n.colors.scrollbarSliderActiveBackground.css};`,"}"].join("\n")})),this._register(this._bufferService.onResize(()=>this.queueSync())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._latestYDisp=void 0,this.queueSync()})),this._register(this._bufferService.onScroll(()=>this._sync())),this._register(this._scrollableElement.onScroll(e=>this._handleScroll(e)))}scrollLines(e){let t=this._scrollableElement.getScrollPosition();this._scrollableElement.setScrollPosition({reuseAnimation:!0,scrollTop:t.scrollTop+e*this._renderService.dimensions.css.cell.height})}scrollToLine(e,t){t&&(this._latestYDisp=e),this._scrollableElement.setScrollPosition({reuseAnimation:!t,scrollTop:e*this._renderService.dimensions.css.cell.height})}_getChangeOptions(){var e;return{mouseWheelScrollSensitivity:this._optionsService.rawOptions.scrollSensitivity,fastScrollSensitivity:this._optionsService.rawOptions.fastScrollSensitivity,verticalScrollbarSize:(null==(e=this._optionsService.rawOptions.overviewRuler)?void 0:e.width)||14}}queueSync(e){void 0!==e&&(this._latestYDisp=e),void 0===this._queuedAnimationFrame&&(this._queuedAnimationFrame=this._renderService.addRefreshCallback(()=>{this._queuedAnimationFrame=void 0,this._sync(this._latestYDisp)}))}_sync(e=this._bufferService.buffer.ydisp){!this._renderService||this._isSyncing||(this._isSyncing=!0,this._suppressOnScrollHandler=!0,this._scrollableElement.setScrollDimensions({height:this._renderService.dimensions.css.canvas.height,scrollHeight:this._renderService.dimensions.css.cell.height*this._bufferService.buffer.lines.length}),this._suppressOnScrollHandler=!1,e!==this._latestYDisp&&this._scrollableElement.setScrollPosition({scrollTop:e*this._renderService.dimensions.css.cell.height}),this._isSyncing=!1)}_handleScroll(e){if(!this._renderService||this._isHandlingScroll||this._suppressOnScrollHandler)return;this._isHandlingScroll=!0;let t=Math.round(e.scrollTop/this._renderService.dimensions.css.cell.height),i=t-this._bufferService.buffer.ydisp;0!==i&&(this._latestYDisp=t,this._onRequestScrollLines.fire(i)),this._isHandlingScroll=!1}};Yl=Wn([Fn(2,uo),Fn(3,ko),Fn(4,fo),Fn(5,Do),Fn(6,vo),Fn(7,No)],Yl);var Xl=class extends qo{constructor(e,t,i,s,r){super(),this._screenElement=e,this._bufferService=t,this._coreBrowserService=i,this._decorationService=s,this._renderService=r,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement("div"),this._container.classList.add("xterm-decoration-container"),this._screenElement.appendChild(this._container),this._register(this._renderService.onRenderedViewportChange(()=>this._doRefreshDecorations())),this._register(this._renderService.onDimensionsChange(()=>{this._dimensionsChanged=!0,this._queueRefresh()})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt})),this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh())),this._register(this._decorationService.onDecorationRemoved(e=>this._removeDecoration(e))),this._register(Ko(()=>{this._container.remove(),this._decorationElements.clear()}))}_queueRefresh(){void 0===this._animationFrame&&(this._animationFrame=this._renderService.addRefreshCallback(()=>{this._doRefreshDecorations(),this._animationFrame=void 0}))}_doRefreshDecorations(){for(let e of this._decorationService.decorations)this._renderDecoration(e);this._dimensionsChanged=!1}_renderDecoration(e){this._refreshStyle(e),this._dimensionsChanged&&this._refreshXPosition(e)}_createElement(e){var t;let i=this._coreBrowserService.mainDocument.createElement("div");i.classList.add("xterm-decoration"),i.classList.toggle("xterm-decoration-top-layer","top"===(null==(t=null==e?void 0:e.options)?void 0:t.layer)),i.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,i.style.height=(e.options.height||1)*this._renderService.dimensions.css.cell.height+"px",i.style.top=(e.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height+"px",i.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;let s=e.options.x??0;return s&&s>this._bufferService.cols&&(i.style.display="none"),this._refreshXPosition(e,i),i}_refreshStyle(e){let t=e.marker.line-this._bufferService.buffers.active.ydisp;if(t<0||t>=this._bufferService.rows)e.element&&(e.element.style.display="none",e.onRenderEmitter.fire(e.element));else{let i=this._decorationElements.get(e);i||(i=this._createElement(e),e.element=i,this._decorationElements.set(e,i),this._container.appendChild(i),e.onDispose(()=>{this._decorationElements.delete(e),i.remove()})),i.style.display=this._altBufferIsActive?"none":"block",this._altBufferIsActive||(i.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,i.style.height=(e.options.height||1)*this._renderService.dimensions.css.cell.height+"px",i.style.top=t*this._renderService.dimensions.css.cell.height+"px",i.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`),e.onRenderEmitter.fire(i)}}_refreshXPosition(e,t=e.element){if(!t)return;let i=e.options.x??0;"right"===(e.options.anchor||"left")?t.style.right=i?i*this._renderService.dimensions.css.cell.width+"px":"":t.style.left=i?i*this._renderService.dimensions.css.cell.width+"px":""}_removeDecoration(e){var t;null==(t=this._decorationElements.get(e))||t.remove(),this._decorationElements.delete(e),e.dispose()}};Xl=Wn([Fn(1,uo),Fn(2,ko),Fn(3,bo),Fn(4,No)],Xl);var Gl,Zl,Jl,Ql,ec,tc=class{constructor(){this._zones=[],this._zonePool=[],this._zonePoolIndex=0,this._linePadding={full:0,left:0,center:0,right:0}}get zones(){return this._zonePool.length=Math.min(this._zonePool.length,this._zones.length),this._zones}clear(){this._zones.length=0,this._zonePoolIndex=0}addDecoration(e){if(e.options.overviewRulerOptions){for(let t of this._zones)if(t.color===e.options.overviewRulerOptions.color&&t.position===e.options.overviewRulerOptions.position){if(this._lineIntersectsZone(t,e.marker.line))return;if(this._lineAdjacentToZone(t,e.marker.line,e.options.overviewRulerOptions.position))return void this._addLineToZone(t,e.marker.line)}if(this._zonePoolIndex<this._zonePool.length)return this._zonePool[this._zonePoolIndex].color=e.options.overviewRulerOptions.color,this._zonePool[this._zonePoolIndex].position=e.options.overviewRulerOptions.position,this._zonePool[this._zonePoolIndex].startBufferLine=e.marker.line,this._zonePool[this._zonePoolIndex].endBufferLine=e.marker.line,void this._zones.push(this._zonePool[this._zonePoolIndex++]);this._zones.push({color:e.options.overviewRulerOptions.color,position:e.options.overviewRulerOptions.position,startBufferLine:e.marker.line,endBufferLine:e.marker.line}),this._zonePool.push(this._zones[this._zones.length-1]),this._zonePoolIndex++}}setPadding(e){this._linePadding=e}_lineIntersectsZone(e,t){return t>=e.startBufferLine&&t<=e.endBufferLine}_lineAdjacentToZone(e,t,i){return t>=e.startBufferLine-this._linePadding[i||"full"]&&t<=e.endBufferLine+this._linePadding[i||"full"]}_addLineToZone(e,t){e.startBufferLine=Math.min(e.startBufferLine,t),e.endBufferLine=Math.max(e.endBufferLine,t)}},ic={full:0,left:0,center:0,right:0},sc={full:0,left:0,center:0,right:0},rc={full:0,left:0,center:0,right:0},nc=class extends qo{constructor(e,t,i,s,r,n,o,a){var l;super(),this._viewportElement=e,this._screenElement=t,this._bufferService=i,this._decorationService=s,this._renderService=r,this._optionsService=n,this._themeService=o,this._coreBrowserService=a,this._colorZoneStore=new tc,this._shouldUpdateDimensions=!0,this._shouldUpdateAnchor=!0,this._lastKnownBufferLength=0,this._canvas=this._coreBrowserService.mainDocument.createElement("canvas"),this._canvas.classList.add("xterm-decoration-overview-ruler"),this._refreshCanvasDimensions(),null==(l=this._viewportElement.parentElement)||l.insertBefore(this._canvas,this._viewportElement),this._register(Ko(()=>{var e;return null==(e=this._canvas)?void 0:e.remove()}));let c=this._canvas.getContext("2d");if(!c)throw new Error("Ctx cannot be null");this._ctx=c,this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh(void 0,!0))),this._register(this._decorationService.onDecorationRemoved(()=>this._queueRefresh(void 0,!0))),this._register(this._renderService.onRenderedViewportChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?"none":"block"})),this._register(this._bufferService.onScroll(()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())})),this._register(this._renderService.onRender(()=>{(!this._containerHeight||this._containerHeight!==this._screenElement.clientHeight)&&(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh(!0))),this._register(this._optionsService.onSpecificOptionChange("overviewRuler",()=>this._queueRefresh(!0))),this._register(this._themeService.onChangeColors(()=>this._queueRefresh())),this._queueRefresh(!0)}get _width(){var e;return(null==(e=this._optionsService.options.overviewRuler)?void 0:e.width)||0}_refreshDrawConstants(){let e=Math.floor((this._canvas.width-1)/3),t=Math.ceil((this._canvas.width-1)/3);sc.full=this._canvas.width,sc.left=e,sc.center=t,sc.right=e,this._refreshDrawHeightConstants(),rc.full=1,rc.left=1,rc.center=1+sc.left,rc.right=1+sc.left+sc.center}_refreshDrawHeightConstants(){ic.full=Math.round(2*this._coreBrowserService.dpr);let e=this._canvas.height/this._bufferService.buffer.lines.length,t=Math.round(Math.max(Math.min(e,12),6)*this._coreBrowserService.dpr);ic.left=t,ic.center=t,ic.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*ic.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*ic.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*ic.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*ic.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowserService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowserService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(let t of this._decorationService.decorations)this._colorZoneStore.addDecoration(t);this._ctx.lineWidth=1,this._renderRulerOutline();let e=this._colorZoneStore.zones;for(let t of e)"full"!==t.position&&this._renderColorZone(t);for(let t of e)"full"===t.position&&this._renderColorZone(t);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderRulerOutline(){this._ctx.fillStyle=this._themeService.colors.overviewRulerBorder.css,this._ctx.fillRect(0,0,1,this._canvas.height),this._optionsService.rawOptions.overviewRuler.showTopBorder&&this._ctx.fillRect(1,0,this._canvas.width-1,1),this._optionsService.rawOptions.overviewRuler.showBottomBorder&&this._ctx.fillRect(1,this._canvas.height-1,this._canvas.width-1,this._canvas.height)}_renderColorZone(e){this._ctx.fillStyle=e.color,this._ctx.fillRect(rc[e.position||"full"],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-ic[e.position||"full"]/2),sc[e.position||"full"],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+ic[e.position||"full"]))}_queueRefresh(e,t){this._shouldUpdateDimensions=e||this._shouldUpdateDimensions,this._shouldUpdateAnchor=t||this._shouldUpdateAnchor,void 0===this._animationFrame&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._refreshDecorations(),this._animationFrame=void 0}))}};nc=Wn([Fn(2,uo),Fn(3,bo),Fn(4,No),Fn(5,vo),Fn(6,Do),Fn(7,ko)],nc),(Zl=Gl||(Gl={})).NUL="\0",Zl.SOH="",Zl.STX="",Zl.ETX="",Zl.EOT="",Zl.ENQ="",Zl.ACK="",Zl.BEL="",Zl.BS="\b",Zl.HT="\t",Zl.LF="\n",Zl.VT="\v",Zl.FF="\f",Zl.CR="\r",Zl.SO="",Zl.SI="",Zl.DLE="",Zl.DC1="",Zl.DC2="",Zl.DC3="",Zl.DC4="",Zl.NAK="",Zl.SYN="",Zl.ETB="",Zl.CAN="",Zl.EM="",Zl.SUB="",Zl.ESC="",Zl.FS="",Zl.GS="",Zl.RS="",Zl.US="",Zl.SP=" ",Zl.DEL="",(Ql=Jl||(Jl={})).PAD="€",Ql.HOP="",Ql.BPH="‚",Ql.NBH="ƒ",Ql.IND="„",Ql.NEL="…",Ql.SSA="†",Ql.ESA="‡",Ql.HTS="ˆ",Ql.HTJ="‰",Ql.VTS="Š",Ql.PLD="‹",Ql.PLU="Œ",Ql.RI="",Ql.SS2="Ž",Ql.SS3="",Ql.DCS="",Ql.PU1="‘",Ql.PU2="’",Ql.STS="“",Ql.CCH="”",Ql.MW="•",Ql.SPA="–",Ql.EPA="—",Ql.SOS="˜",Ql.SGCI="™",Ql.SCI="š",Ql.CSI="›",Ql.ST="œ",Ql.OSC="",Ql.PM="ž",Ql.APC="Ÿ",(ec||(ec={})).ST=`${Gl.ESC}\\`;var oc=class{constructor(e,t,i,s,r,n){this._textarea=e,this._compositionView=t,this._bufferService=i,this._optionsService=s,this._coreService=r,this._renderService=n,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=""}get isComposing(){return this._isComposing}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent="",this._dataAlreadySent="",this._compositionView.classList.add("active")}compositionupdate(e){this._compositionView.textContent=e.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(e){if(this._isComposing||this._isSendingComposition){if(20===e.keyCode||229===e.keyCode||16===e.keyCode||17===e.keyCode||18===e.keyCode)return!1;this._finalizeComposition(!1)}return 229!==e.keyCode||(this._handleAnyTextareaChanges(),!1)}_finalizeComposition(e){if(this._compositionView.classList.remove("active"),this._isComposing=!1,e){let e={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){let t;this._isSendingComposition=!1,e.start+=this._dataAlreadySent.length,t=this._isComposing?this._textarea.value.substring(e.start,this._compositionPosition.start):this._textarea.value.substring(e.start),t.length>0&&this._coreService.triggerDataEvent(t,!0)}},0)}else{this._isSendingComposition=!1;let e=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(e,!0)}}_handleAnyTextareaChanges(){let e=this._textarea.value;setTimeout(()=>{if(!this._isComposing){let t=this._textarea.value,i=t.replace(e,"");this._dataAlreadySent=i,t.length>e.length?this._coreService.triggerDataEvent(i,!0):t.length<e.length?this._coreService.triggerDataEvent(`${Gl.DEL}`,!0):t.length===e.length&&t!==e&&this._coreService.triggerDataEvent(t,!0)}},0)}updateCompositionElements(e){if(this._isComposing){if(this._bufferService.buffer.isCursorInViewport){let e=Math.min(this._bufferService.buffer.x,this._bufferService.cols-1),t=this._renderService.dimensions.css.cell.height,i=this._bufferService.buffer.y*this._renderService.dimensions.css.cell.height,s=e*this._renderService.dimensions.css.cell.width;this._compositionView.style.left=s+"px",this._compositionView.style.top=i+"px",this._compositionView.style.height=t+"px",this._compositionView.style.lineHeight=t+"px",this._compositionView.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._compositionView.style.fontSize=this._optionsService.rawOptions.fontSize+"px";let r=this._compositionView.getBoundingClientRect();this._textarea.style.left=s+"px",this._textarea.style.top=i+"px",this._textarea.style.width=Math.max(r.width,1)+"px",this._textarea.style.height=Math.max(r.height,1)+"px",this._textarea.style.lineHeight=r.height+"px"}e||setTimeout(()=>this.updateCompositionElements(!0),0)}}};oc=Wn([Fn(2,uo),Fn(3,vo),Fn(4,po),Fn(5,No)],oc);var ac,lc,cc,hc,dc,uc=0,fc=0,pc=0,mc=0,_c={css:"#00000000",rgba:0};function gc(e){let t=e.toString(16);return t.length<2?"0"+t:t}function vc(e,t){return e<t?(t+.05)/(e+.05):(e+.05)/(t+.05)}(e=>{e.toCss=function(e,t,i,s){return void 0!==s?`#${gc(e)}${gc(t)}${gc(i)}${gc(s)}`:`#${gc(e)}${gc(t)}${gc(i)}`},e.toRgba=function(e,t,i,s=255){return(e<<24|t<<16|i<<8|s)>>>0},e.toColor=function(t,i,s,r){return{css:e.toCss(t,i,s,r),rgba:e.toRgba(t,i,s,r)}}})(ac||(ac={})),(e=>{function t(e,t){return mc=Math.round(255*t),[uc,fc,pc]=dc.toChannels(e.rgba),{css:ac.toCss(uc,fc,pc,mc),rgba:ac.toRgba(uc,fc,pc,mc)}}e.blend=function(e,t){if(1===(mc=(255&t.rgba)/255))return{css:t.css,rgba:t.rgba};let i=t.rgba>>24&255,s=t.rgba>>16&255,r=t.rgba>>8&255,n=e.rgba>>24&255,o=e.rgba>>16&255,a=e.rgba>>8&255;return uc=n+Math.round((i-n)*mc),fc=o+Math.round((s-o)*mc),pc=a+Math.round((r-a)*mc),{css:ac.toCss(uc,fc,pc),rgba:ac.toRgba(uc,fc,pc)}},e.isOpaque=function(e){return!(255&~e.rgba)},e.ensureContrastRatio=function(e,t,i){let s=dc.ensureContrastRatio(e.rgba,t.rgba,i);if(s)return ac.toColor(s>>24&255,s>>16&255,s>>8&255)},e.opaque=function(e){let t=(255|e.rgba)>>>0;return[uc,fc,pc]=dc.toChannels(t),{css:ac.toCss(uc,fc,pc),rgba:t}},e.opacity=t,e.multiplyOpacity=function(e,i){return t(e,(mc=255&e.rgba)*i/255)},e.toColorRGB=function(e){return[e.rgba>>24&255,e.rgba>>16&255,e.rgba>>8&255]}})(lc||(lc={})),(e=>{let t,i;try{let e=document.createElement("canvas");e.width=1,e.height=1;let s=e.getContext("2d",{willReadFrequently:!0});s&&(t=s,t.globalCompositeOperation="copy",i=t.createLinearGradient(0,0,1,1))}catch{}e.toColor=function(e){if(e.match(/#[\da-f]{3,8}/i))switch(e.length){case 4:return uc=parseInt(e.slice(1,2).repeat(2),16),fc=parseInt(e.slice(2,3).repeat(2),16),pc=parseInt(e.slice(3,4).repeat(2),16),ac.toColor(uc,fc,pc);case 5:return uc=parseInt(e.slice(1,2).repeat(2),16),fc=parseInt(e.slice(2,3).repeat(2),16),pc=parseInt(e.slice(3,4).repeat(2),16),mc=parseInt(e.slice(4,5).repeat(2),16),ac.toColor(uc,fc,pc,mc);case 7:return{css:e,rgba:(parseInt(e.slice(1),16)<<8|255)>>>0};case 9:return{css:e,rgba:parseInt(e.slice(1),16)>>>0}}let s=e.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(s)return uc=parseInt(s[1]),fc=parseInt(s[2]),pc=parseInt(s[3]),mc=Math.round(255*(void 0===s[5]?1:parseFloat(s[5]))),ac.toColor(uc,fc,pc,mc);if(!t||!i)throw new Error("css.toColor: Unsupported css format");if(t.fillStyle=i,t.fillStyle=e,"string"!=typeof t.fillStyle)throw new Error("css.toColor: Unsupported css format");if(t.fillRect(0,0,1,1),[uc,fc,pc,mc]=t.getImageData(0,0,1,1).data,255!==mc)throw new Error("css.toColor: Unsupported css format");return{rgba:ac.toRgba(uc,fc,pc,mc),css:e}}})(cc||(cc={})),(e=>{function t(e,t,i){let s=e/255,r=t/255,n=i/255;return.2126*(s<=.03928?s/12.92:Math.pow((s+.055)/1.055,2.4))+.7152*(r<=.03928?r/12.92:Math.pow((r+.055)/1.055,2.4))+.0722*(n<=.03928?n/12.92:Math.pow((n+.055)/1.055,2.4))}e.relativeLuminance=function(e){return t(e>>16&255,e>>8&255,255&e)},e.relativeLuminance2=t})(hc||(hc={})),(e=>{function t(e,t,i){let s=e>>24&255,r=e>>16&255,n=e>>8&255,o=t>>24&255,a=t>>16&255,l=t>>8&255,c=vc(hc.relativeLuminance2(o,a,l),hc.relativeLuminance2(s,r,n));for(;c<i&&(o>0||a>0||l>0);)o-=Math.max(0,Math.ceil(.1*o)),a-=Math.max(0,Math.ceil(.1*a)),l-=Math.max(0,Math.ceil(.1*l)),c=vc(hc.relativeLuminance2(o,a,l),hc.relativeLuminance2(s,r,n));return(o<<24|a<<16|l<<8|255)>>>0}function i(e,t,i){let s=e>>24&255,r=e>>16&255,n=e>>8&255,o=t>>24&255,a=t>>16&255,l=t>>8&255,c=vc(hc.relativeLuminance2(o,a,l),hc.relativeLuminance2(s,r,n));for(;c<i&&(o<255||a<255||l<255);)o=Math.min(255,o+Math.ceil(.1*(255-o))),a=Math.min(255,a+Math.ceil(.1*(255-a))),l=Math.min(255,l+Math.ceil(.1*(255-l))),c=vc(hc.relativeLuminance2(o,a,l),hc.relativeLuminance2(s,r,n));return(o<<24|a<<16|l<<8|255)>>>0}e.blend=function(e,t){if(1===(mc=(255&t)/255))return t;let i=t>>24&255,s=t>>16&255,r=t>>8&255,n=e>>24&255,o=e>>16&255,a=e>>8&255;return uc=n+Math.round((i-n)*mc),fc=o+Math.round((s-o)*mc),pc=a+Math.round((r-a)*mc),ac.toRgba(uc,fc,pc)},e.ensureContrastRatio=function(e,s,r){let n=hc.relativeLuminance(e>>8),o=hc.relativeLuminance(s>>8);if(vc(n,o)<r){if(o<n){let o=t(e,s,r),a=vc(n,hc.relativeLuminance(o>>8));if(a<r){let t=i(e,s,r);return a>vc(n,hc.relativeLuminance(t>>8))?o:t}return o}let a=i(e,s,r),l=vc(n,hc.relativeLuminance(a>>8));if(l<r){let i=t(e,s,r);return l>vc(n,hc.relativeLuminance(i>>8))?a:i}return a}},e.reduceLuminance=t,e.increaseLuminance=i,e.toChannels=function(e){return[e>>24&255,e>>16&255,e>>8&255,255&e]}})(dc||(dc={}));var yc=class extends ro{constructor(e,t,i){super(),this.content=0,this.combinedData="",this.fg=e.fg,this.bg=e.bg,this.combinedData=t,this._width=i}isCombined(){return 2097152}getWidth(){return this._width}getChars(){return this.combinedData}getCode(){return 2097151}setFromCharData(e){throw new Error("not implemented")}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},xc=class{constructor(e){this._bufferService=e,this._characterJoiners=[],this._nextCharacterJoinerId=0,this._workCell=new oo}register(e){let t={id:this._nextCharacterJoinerId++,handler:e};return this._characterJoiners.push(t),t.id}deregister(e){for(let t=0;t<this._characterJoiners.length;t++)if(this._characterJoiners[t].id===e)return this._characterJoiners.splice(t,1),!0;return!1}getJoinedCharacters(e){if(0===this._characterJoiners.length)return[];let t=this._bufferService.buffer.lines.get(e);if(!t||0===t.length)return[];let i=[],s=t.translateToString(!0),r=0,n=0,o=0,a=t.getFg(0),l=t.getBg(0);for(let c=0;c<t.getTrimmedLength();c++)if(t.loadCell(c,this._workCell),0!==this._workCell.getWidth()){if(this._workCell.fg!==a||this._workCell.bg!==l){if(c-r>1){let e=this._getJoinedRanges(s,o,n,t,r);for(let t=0;t<e.length;t++)i.push(e[t])}r=c,o=n,a=this._workCell.fg,l=this._workCell.bg}n+=this._workCell.getChars().length||1}if(this._bufferService.cols-r>1){let e=this._getJoinedRanges(s,o,n,t,r);for(let t=0;t<e.length;t++)i.push(e[t])}return i}_getJoinedRanges(e,t,i,s,r){let n=e.substring(t,i),o=[];try{o=this._characterJoiners[0].handler(n)}catch(a){console.error(a)}for(let c=1;c<this._characterJoiners.length;c++)try{let e=this._characterJoiners[c].handler(n);for(let t=0;t<e.length;t++)xc._mergeRanges(o,e[t])}catch(l){console.error(l)}return this._stringRangesToCellRanges(o,s,r),o}_stringRangesToCellRanges(e,t,i){let s=0,r=!1,n=0,o=e[s];if(o){for(let a=i;a<this._bufferService.cols;a++){let i=t.getWidth(a),l=t.getString(a).length||1;if(0!==i){if(!r&&o[0]<=n&&(o[0]=a,r=!0),o[1]<=n){if(o[1]=a,o=e[++s],!o)break;o[0]<=n?(o[0]=a,r=!0):r=!1}n+=l}}o&&(o[1]=this._bufferService.cols)}}static _mergeRanges(e,t){let i=!1;for(let s=0;s<e.length;s++){let r=e[s];if(i){if(t[1]<=r[0])return e[s-1][1]=t[1],e;if(t[1]<=r[1])return e[s-1][1]=Math.max(t[1],r[1]),e.splice(s,1),e;e.splice(s,1),s--}else{if(t[1]<=r[0])return e.splice(s,0,t),e;if(t[1]<=r[1])return r[0]=Math.min(t[0],r[0]),e;t[0]<r[1]&&(r[0]=Math.min(t[0],r[0]),i=!0)}}return i?e[e.length-1][1]=t[1]:e.push(t),e}};xc=Wn([Fn(0,uo)],xc);var bc=class{constructor(e,t,i,s,r,n,o){this._document=e,this._characterJoinerService=t,this._optionsService=i,this._coreBrowserService=s,this._coreService=r,this._decorationService=n,this._themeService=o,this._workCell=new oo,this._columnSelectMode=!1,this.defaultSpacing=0}handleSelectionChanged(e,t,i){this._selectionStart=e,this._selectionEnd=t,this._columnSelectMode=i}createRow(e,t,i,s,r,n,o,a,l,c,h){let d=[],u=this._characterJoinerService.getJoinedCharacters(t),f=this._themeService.colors,p=e.getNoBgTrimmedLength();i&&p<n+1&&(p=n+1);let m,_=0,g="",v=0,y=0,x=0,b=0,w=!1,S=0,C=!1,k=0,E=0,N=[],M=-1!==c&&-1!==h;for(let j=0;j<p;j++){e.loadCell(j,this._workCell);let p=this._workCell.getWidth();if(0===p)continue;let D=!1,R=j>=E,P=j,L=this._workCell;if(u.length>0&&j===u[0][0]&&R){let s=u.shift(),r=this._isCellInSelection(s[0],t);for(v=s[0]+1;v<s[1];v++)R&&(R=r===this._isCellInSelection(v,t));R&&(R=!i||n<s[0]||n>=s[1]),R?(D=!0,L=new yc(this._workCell,e.translateToString(!0,s[0],s[1]),s[1]-s[0]),P=s[1]-1,p=L.getWidth()):E=s[1]}let I=this._isCellInSelection(j,t),T=i&&j===n,B=M&&j>=c&&j<=h,O=!1;this._decorationService.forEachDecorationAtCell(j,t,void 0,e=>{O=!0});let A=L.getChars()||so;if(" "===A&&(L.isUnderline()||L.isOverline())&&(A=" "),k=p*a-l.get(A,L.isBold(),L.isItalic()),m){if(_&&(I&&C||!I&&!C&&L.bg===y)&&(I&&C&&f.selectionForeground||L.fg===x)&&L.extended.ext===b&&B===w&&k===S&&!T&&!D&&!O&&R){L.isInvisible()?g+=so:g+=A,_++;continue}_&&(m.textContent=g),m=this._document.createElement("span"),_=0,g=""}else m=this._document.createElement("span");if(y=L.bg,x=L.fg,b=L.extended.ext,w=B,S=k,C=I,D&&n>=j&&n<=P&&(n=j),!this._coreService.isCursorHidden&&T&&this._coreService.isCursorInitialized)if(N.push("xterm-cursor"),this._coreBrowserService.isFocused)o&&N.push("xterm-cursor-blink"),N.push("bar"===s?"xterm-cursor-bar":"underline"===s?"xterm-cursor-underline":"xterm-cursor-block");else if(r)switch(r){case"outline":N.push("xterm-cursor-outline");break;case"block":N.push("xterm-cursor-block");break;case"bar":N.push("xterm-cursor-bar");break;case"underline":N.push("xterm-cursor-underline")}if(L.isBold()&&N.push("xterm-bold"),L.isItalic()&&N.push("xterm-italic"),L.isDim()&&N.push("xterm-dim"),g=L.isInvisible()?so:L.getChars()||so,L.isUnderline()&&(N.push(`xterm-underline-${L.extended.underlineStyle}`)," "===g&&(g=" "),!L.isUnderlineColorDefault()))if(L.isUnderlineColorRGB())m.style.textDecorationColor=`rgb(${ro.toColorRGB(L.getUnderlineColor()).join(",")})`;else{let e=L.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&L.isBold()&&e<8&&(e+=8),m.style.textDecorationColor=f.ansi[e].css}L.isOverline()&&(N.push("xterm-overline")," "===g&&(g=" ")),L.isStrikethrough()&&N.push("xterm-strikethrough"),B&&(m.style.textDecoration="underline");let z=L.getFgColor(),$=L.getFgColorMode(),H=L.getBgColor(),W=L.getBgColorMode(),F=!!L.isInverse();if(F){let e=z;z=H,H=e;let t=$;$=W,W=t}let K,U,V,q=!1;switch(this._decorationService.forEachDecorationAtCell(j,t,void 0,e=>{"top"!==e.options.layer&&q||(e.backgroundColorRGB&&(W=50331648,H=e.backgroundColorRGB.rgba>>8&16777215,K=e.backgroundColorRGB),e.foregroundColorRGB&&($=50331648,z=e.foregroundColorRGB.rgba>>8&16777215,U=e.foregroundColorRGB),q="top"===e.options.layer)}),!q&&I&&(K=this._coreBrowserService.isFocused?f.selectionBackgroundOpaque:f.selectionInactiveBackgroundOpaque,H=K.rgba>>8&16777215,W=50331648,q=!0,f.selectionForeground&&($=50331648,z=f.selectionForeground.rgba>>8&16777215,U=f.selectionForeground)),q&&N.push("xterm-decoration-top"),W){case 16777216:case 33554432:V=f.ansi[H],N.push(`xterm-bg-${H}`);break;case 50331648:V=ac.toColor(H>>16,H>>8&255,255&H),this._addStyle(m,`background-color:#${wc((H>>>0).toString(16),"0",6)}`);break;default:F?(V=f.foreground,N.push("xterm-bg-257")):V=f.background}switch(K||L.isDim()&&(K=lc.multiplyOpacity(V,.5)),$){case 16777216:case 33554432:L.isBold()&&z<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(z+=8),this._applyMinimumContrast(m,V,f.ansi[z],L,K,void 0)||N.push(`xterm-fg-${z}`);break;case 50331648:let e=ac.toColor(z>>16&255,z>>8&255,255&z);this._applyMinimumContrast(m,V,e,L,K,U)||this._addStyle(m,`color:#${wc(z.toString(16),"0",6)}`);break;default:this._applyMinimumContrast(m,V,f.foreground,L,K,U)||F&&N.push("xterm-fg-257")}N.length&&(m.className=N.join(" "),N.length=0),T||D||O||!R?m.textContent=g:_++,k!==this.defaultSpacing&&(m.style.letterSpacing=`${k}px`),d.push(m),j=P}return m&&_&&(m.textContent=g),d}_applyMinimumContrast(e,t,i,s,r,n){if(1===this._optionsService.rawOptions.minimumContrastRatio||(function(e){return 57508<=e&&e<=57558}(o=s.getCode())||function(e){return 9472<=e&&e<=9631}(o)))return!1;var o;let a,l=this._getContrastCache(s);if(!r&&!n&&(a=l.getColor(t.rgba,i.rgba)),void 0===a){let e=this._optionsService.rawOptions.minimumContrastRatio/(s.isDim()?2:1);a=lc.ensureContrastRatio(r||t,n||i,e),l.setColor((r||t).rgba,(n||i).rgba,a??null)}return!!a&&(this._addStyle(e,`color:${a.css}`),!0)}_getContrastCache(e){return e.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(e,t){e.setAttribute("style",`${e.getAttribute("style")||""}${t};`)}_isCellInSelection(e,t){let i=this._selectionStart,s=this._selectionEnd;return!(!i||!s)&&(this._columnSelectMode?i[0]<=s[0]?e>=i[0]&&t>=i[1]&&e<s[0]&&t<=s[1]:e<i[0]&&t>=i[1]&&e>=s[0]&&t<=s[1]:t>i[1]&&t<s[1]||i[1]===s[1]&&t===i[1]&&e>=i[0]&&e<s[0]||i[1]<s[1]&&t===s[1]&&e<s[0]||i[1]<s[1]&&t===i[1]&&e>=i[0])}};function wc(e,t,i){for(;e.length<i;)e=t+e;return e}bc=Wn([Fn(1,jo),Fn(2,vo),Fn(3,ko),Fn(4,po),Fn(5,bo),Fn(6,Do)],bc);var Sc=class{constructor(e,t){this._flat=new Float32Array(256),this._font="",this._fontSize=0,this._weight="normal",this._weightBold="bold",this._measureElements=[],this._container=e.createElement("div"),this._container.classList.add("xterm-width-cache-measure-container"),this._container.setAttribute("aria-hidden","true"),this._container.style.whiteSpace="pre",this._container.style.fontKerning="none";let i=e.createElement("span");i.classList.add("xterm-char-measure-element");let s=e.createElement("span");s.classList.add("xterm-char-measure-element"),s.style.fontWeight="bold";let r=e.createElement("span");r.classList.add("xterm-char-measure-element"),r.style.fontStyle="italic";let n=e.createElement("span");n.classList.add("xterm-char-measure-element"),n.style.fontWeight="bold",n.style.fontStyle="italic",this._measureElements=[i,s,r,n],this._container.appendChild(i),this._container.appendChild(s),this._container.appendChild(r),this._container.appendChild(n),t.appendChild(this._container),this.clear()}dispose(){this._container.remove(),this._measureElements.length=0,this._holey=void 0}clear(){this._flat.fill(-9999),this._holey=new Map}setFont(e,t,i,s){e===this._font&&t===this._fontSize&&i===this._weight&&s===this._weightBold||(this._font=e,this._fontSize=t,this._weight=i,this._weightBold=s,this._container.style.fontFamily=this._font,this._container.style.fontSize=`${this._fontSize}px`,this._measureElements[0].style.fontWeight=`${i}`,this._measureElements[1].style.fontWeight=`${s}`,this._measureElements[2].style.fontWeight=`${i}`,this._measureElements[3].style.fontWeight=`${s}`,this.clear())}get(e,t,i){let s=0;if(!t&&!i&&1===e.length&&(s=e.charCodeAt(0))<256){if(-9999!==this._flat[s])return this._flat[s];let t=this._measure(e,0);return t>0&&(this._flat[s]=t),t}let r=e;t&&(r+="B"),i&&(r+="I");let n=this._holey.get(r);if(void 0===n){let s=0;t&&(s|=1),i&&(s|=2),n=this._measure(e,s),n>0&&this._holey.set(r,n)}return n}_measure(e,t){let i=this._measureElements[t];return i.textContent=e.repeat(32),i.offsetWidth/32}},Cc=class{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(e,t,i,s=!1){if(this.selectionStart=t,this.selectionEnd=i,!t||!i||t[0]===i[0]&&t[1]===i[1])return void this.clear();let r=e.buffers.active.ydisp,n=t[1]-r,o=i[1]-r,a=Math.max(n,0),l=Math.min(o,e.rows-1);a>=e.rows||l<0?this.clear():(this.hasSelection=!0,this.columnSelectMode=s,this.viewportStartRow=n,this.viewportEndRow=o,this.viewportCappedStartRow=a,this.viewportCappedEndRow=l,this.startCol=t[0],this.endCol=i[0])}isCellSelected(e,t,i){return!!this.hasSelection&&(i-=e.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?t>=this.startCol&&i>=this.viewportCappedStartRow&&t<this.endCol&&i<=this.viewportCappedEndRow:t<this.startCol&&i>=this.viewportCappedStartRow&&t>=this.endCol&&i<=this.viewportCappedEndRow:i>this.viewportStartRow&&i<this.viewportEndRow||this.viewportStartRow===this.viewportEndRow&&i===this.viewportStartRow&&t>=this.startCol&&t<this.endCol||this.viewportStartRow<this.viewportEndRow&&i===this.viewportEndRow&&t<this.endCol||this.viewportStartRow<this.viewportEndRow&&i===this.viewportStartRow&&t>=this.startCol)}};var kc="xterm-dom-renderer-owner-",Ec="xterm-rows",Nc="xterm-fg-",Mc="xterm-bg-",jc="xterm-focus",Dc="xterm-selection",Rc=1,Pc=class extends qo{constructor(e,t,i,s,r,n,o,a,l,c,h,d,u,f){super(),this._terminal=e,this._document=t,this._element=i,this._screenElement=s,this._viewportElement=r,this._helperContainer=n,this._linkifier2=o,this._charSizeService=l,this._optionsService=c,this._bufferService=h,this._coreService=d,this._coreBrowserService=u,this._themeService=f,this._terminalClass=Rc++,this._rowElements=[],this._selectionRenderModel=new Cc,this.onRequestRedraw=this._register(new da).event,this._rowContainer=this._document.createElement("div"),this._rowContainer.classList.add(Ec),this._rowContainer.style.lineHeight="normal",this._rowContainer.setAttribute("aria-hidden","true"),this._refreshRowElements(this._bufferService.cols,this._bufferService.rows),this._selectionContainer=this._document.createElement("div"),this._selectionContainer.classList.add(Dc),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions={css:{canvas:{width:0,height:0},cell:{width:0,height:0}},device:{canvas:{width:0,height:0},cell:{width:0,height:0},char:{width:0,height:0,left:0,top:0}}},this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(e=>this._injectCss(e))),this._injectCss(this._themeService.colors),this._rowFactory=a.createInstance(bc,document),this._element.classList.add(kc+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(e=>this._handleLinkHover(e))),this._register(this._linkifier2.onHideLinkUnderline(e=>this._handleLinkLeave(e))),this._register(Ko(()=>{this._element.classList.remove(kc+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new Sc(this._document,this._helperContainer),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}_updateDimensions(){let e=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*e,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*e),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.left=0,this.dimensions.device.char.top=0,this.dimensions.device.canvas.width=this.dimensions.device.cell.width*this._bufferService.cols,this.dimensions.device.canvas.height=this.dimensions.device.cell.height*this._bufferService.rows,this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/e),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/e),this.dimensions.css.cell.width=this.dimensions.css.canvas.width/this._bufferService.cols,this.dimensions.css.cell.height=this.dimensions.css.canvas.height/this._bufferService.rows;for(let i of this._rowElements)i.style.width=`${this.dimensions.css.canvas.width}px`,i.style.height=`${this.dimensions.css.cell.height}px`,i.style.lineHeight=`${this.dimensions.css.cell.height}px`,i.style.overflow="hidden";this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._dimensionsStyleElement));let t=`${this._terminalSelector} .${Ec} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=t,this._selectionContainer.style.height=this._viewportElement.style.height,this._screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._screenElement.style.height=`${this.dimensions.css.canvas.height}px`}_injectCss(e){this._themeStyleElement||(this._themeStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._themeStyleElement));let t=`${this._terminalSelector} .${Ec} { pointer-events: none; color: ${e.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;t+=`${this._terminalSelector} .${Ec} .xterm-dim { color: ${lc.multiplyOpacity(e.foreground,.5).css};}`,t+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`;let i=`blink_underline_${this._terminalClass}`,s=`blink_bar_${this._terminalClass}`,r=`blink_block_${this._terminalClass}`;t+=`@keyframes ${i} { 50% { border-bottom-style: hidden; }}`,t+=`@keyframes ${s} { 50% { box-shadow: none; }}`,t+=`@keyframes ${r} { 0% { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css}; } 50% { background-color: inherit; color: ${e.cursor.css}; }}`,t+=`${this._terminalSelector} .${Ec}.${jc} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${Ec}.${jc} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${s} 1s step-end infinite;}${this._terminalSelector} .${Ec}.${jc} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${r} 1s step-end infinite;}${this._terminalSelector} .${Ec} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${Ec} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${Ec} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${Ec} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${Ec} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${Dc} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${Dc} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${Dc} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[n,o]of e.ansi.entries())t+=`${this._terminalSelector} .${Nc}${n} { color: ${o.css}; }${this._terminalSelector} .${Nc}${n}.xterm-dim { color: ${lc.multiplyOpacity(o,.5).css}; }${this._terminalSelector} .${Mc}${n} { background-color: ${o.css}; }`;t+=`${this._terminalSelector} .${Nc}257 { color: ${lc.opaque(e.background).css}; }${this._terminalSelector} .${Nc}257.xterm-dim { color: ${lc.multiplyOpacity(lc.opaque(e.background),.5).css}; }${this._terminalSelector} .${Mc}257 { background-color: ${e.foreground.css}; }`,this._themeStyleElement.textContent=t}_setDefaultSpacing(){let e=this.dimensions.css.cell.width-this._widthCache.get("W",!1,!1);this._rowContainer.style.letterSpacing=`${e}px`,this._rowFactory.defaultSpacing=e}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(e,t){for(let i=this._rowElements.length;i<=t;i++){let e=this._document.createElement("div");this._rowContainer.appendChild(e),this._rowElements.push(e)}for(;this._rowElements.length>t;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(e,t){this._refreshRowElements(e,t),this._updateDimensions(),this.handleSelectionChanged(this._selectionRenderModel.selectionStart,this._selectionRenderModel.selectionEnd,this._selectionRenderModel.columnSelectMode)}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(jc),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(jc),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(e,t,i){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(e,t,i),this.renderRows(0,this._bufferService.rows-1),!e||!t||(this._selectionRenderModel.update(this._terminal,e,t,i),!this._selectionRenderModel.hasSelection))return;let s=this._selectionRenderModel.viewportStartRow,r=this._selectionRenderModel.viewportEndRow,n=this._selectionRenderModel.viewportCappedStartRow,o=this._selectionRenderModel.viewportCappedEndRow,a=this._document.createDocumentFragment();if(i){let i=e[0]>t[0];a.appendChild(this._createSelectionElement(n,i?t[0]:e[0],i?e[0]:t[0],o-n+1))}else{let i=s===n?e[0]:0,l=n===r?t[0]:this._bufferService.cols;a.appendChild(this._createSelectionElement(n,i,l));let c=o-n-1;if(a.appendChild(this._createSelectionElement(n+1,0,this._bufferService.cols,c)),n!==o){let e=r===o?t[0]:this._bufferService.cols;a.appendChild(this._createSelectionElement(o,0,e))}}this._selectionContainer.appendChild(a)}_createSelectionElement(e,t,i,s=1){let r=this._document.createElement("div"),n=t*this.dimensions.css.cell.width,o=this.dimensions.css.cell.width*(i-t);return n+o>this.dimensions.css.canvas.width&&(o=this.dimensions.css.canvas.width-n),r.style.height=s*this.dimensions.css.cell.height+"px",r.style.top=e*this.dimensions.css.cell.height+"px",r.style.left=`${n}px`,r.style.width=`${o}px`,r}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(let e of this._rowElements)e.replaceChildren()}renderRows(e,t){let i=this._bufferService.buffer,s=i.ybase+i.y,r=Math.min(i.x,this._bufferService.cols-1),n=this._coreService.decPrivateModes.cursorBlink??this._optionsService.rawOptions.cursorBlink,o=this._coreService.decPrivateModes.cursorStyle??this._optionsService.rawOptions.cursorStyle,a=this._optionsService.rawOptions.cursorInactiveStyle;for(let l=e;l<=t;l++){let e=l+i.ydisp,t=this._rowElements[l],c=i.lines.get(e);if(!t||!c)break;t.replaceChildren(...this._rowFactory.createRow(c,e,e===s,o,a,r,n,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${kc}${this._terminalClass}`}_handleLinkHover(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!0)}_handleLinkLeave(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!1)}_setCellUnderline(e,t,i,s,r,n){i<0&&(e=0),s<0&&(t=0);let o=this._bufferService.rows-1;i=Math.max(Math.min(i,o),0),s=Math.max(Math.min(s,o),0),r=Math.min(r,this._bufferService.cols);let a=this._bufferService.buffer,l=a.ybase+a.y,c=Math.min(a.x,r-1),h=this._optionsService.rawOptions.cursorBlink,d=this._optionsService.rawOptions.cursorStyle,u=this._optionsService.rawOptions.cursorInactiveStyle;for(let f=i;f<=s;++f){let o=f+a.ydisp,p=this._rowElements[f],m=a.lines.get(o);if(!p||!m)break;p.replaceChildren(...this._rowFactory.createRow(m,o,o===l,d,u,c,h,this.dimensions.css.cell.width,this._widthCache,n?f===i?e:0:-1,n?(f===s?t:r)-1:-1))}}};Pc=Wn([Fn(7,_o),Fn(8,Co),Fn(9,vo),Fn(10,uo),Fn(11,po),Fn(12,ko),Fn(13,Do)],Pc);var Lc=class extends qo{constructor(e,t,i){super(),this._optionsService=i,this.width=0,this.height=0,this._onCharSizeChange=this._register(new da),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new Bc(this._optionsService))}catch{this._measureStrategy=this._register(new Tc(e,t,this._optionsService))}this._register(this._optionsService.onMultipleOptionChange(["fontFamily","fontSize"],()=>this.measure()))}get hasValidSize(){return this.width>0&&this.height>0}measure(){let e=this._measureStrategy.measure();(e.width!==this.width||e.height!==this.height)&&(this.width=e.width,this.height=e.height,this._onCharSizeChange.fire())}};Lc=Wn([Fn(2,vo)],Lc);var Ic=class extends qo{constructor(){super(...arguments),this._result={width:0,height:0}}_validateAndSet(e,t){void 0!==e&&e>0&&void 0!==t&&t>0&&(this._result.width=e,this._result.height=t)}},Tc=class extends Ic{constructor(e,t,i){super(),this._document=e,this._parentElement=t,this._optionsService=i,this._measureElement=this._document.createElement("span"),this._measureElement.classList.add("xterm-char-measure-element"),this._measureElement.textContent="W".repeat(32),this._measureElement.setAttribute("aria-hidden","true"),this._measureElement.style.whiteSpace="pre",this._measureElement.style.fontKerning="none",this._parentElement.appendChild(this._measureElement)}measure(){return this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}px`,this._validateAndSet(Number(this._measureElement.offsetWidth)/32,Number(this._measureElement.offsetHeight)),this._result}},Bc=class extends Ic{constructor(e){super(),this._optionsService=e,this._canvas=new OffscreenCanvas(100,100),this._ctx=this._canvas.getContext("2d");let t=this._ctx.measureText("W");if(!("width"in t&&"fontBoundingBoxAscent"in t&&"fontBoundingBoxDescent"in t))throw new Error("Required font metrics not supported")}measure(){this._ctx.font=`${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;let e=this._ctx.measureText("W");return this._validateAndSet(e.width,e.fontBoundingBoxAscent+e.fontBoundingBoxDescent),this._result}},Oc=class extends qo{constructor(e,t,i){super(),this._textarea=e,this._window=t,this.mainDocument=i,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=this._register(new Ac(this._window)),this._onDprChange=this._register(new da),this.onDprChange=this._onDprChange.event,this._onWindowChange=this._register(new da),this.onWindowChange=this._onWindowChange.event,this._register(this.onWindowChange(e=>this._screenDprMonitor.setWindow(e))),this._register(Zo.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(gl(this._textarea,"focus",()=>this._isFocused=!0)),this._register(gl(this._textarea,"blur",()=>this._isFocused=!1))}get window(){return this._window}set window(e){this._window!==e&&(this._window=e,this._onWindowChange.fire(this._window))}get dpr(){return this.window.devicePixelRatio}get isFocused(){return void 0===this._cachedIsFocused&&(this._cachedIsFocused=this._isFocused&&this._textarea.ownerDocument.hasFocus(),queueMicrotask(()=>this._cachedIsFocused=void 0)),this._cachedIsFocused}},Ac=class extends qo{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new Yo),this._onDprChange=this._register(new da),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register(Ko(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=gl(this._parentWindow,"resize",()=>this._setDprAndFireIfDiffers())}_setDprAndFireIfDiffers(){this._parentWindow.devicePixelRatio!==this._currentDevicePixelRatio&&this._onDprChange.fire(this._parentWindow.devicePixelRatio),this._updateDpr()}_updateDpr(){var e;this._outerListener&&(null==(e=this._resolutionMediaMatchList)||e.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){!this._resolutionMediaMatchList||!this._outerListener||(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._outerListener=void 0)}},zc=class extends qo{constructor(){super(),this.linkProviders=[],this._register(Ko(()=>this.linkProviders.length=0))}registerLinkProvider(e){return this.linkProviders.push(e),{dispose:()=>{let t=this.linkProviders.indexOf(e);-1!==t&&this.linkProviders.splice(t,1)}}}};function $c(e,t,i){let s=i.getBoundingClientRect(),r=e.getComputedStyle(i),n=parseInt(r.getPropertyValue("padding-left")),o=parseInt(r.getPropertyValue("padding-top"));return[t.clientX-s.left-n,t.clientY-s.top-o]}var Hc=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,i,s,r){return function(e,t,i,s,r,n,o,a,l){if(!n)return;let c=$c(e,t,i);return c?(c[0]=Math.ceil((c[0]+(l?o/2:0))/o),c[1]=Math.ceil(c[1]/a),c[0]=Math.min(Math.max(c[0],1),s+(l?1:0)),c[1]=Math.min(Math.max(c[1],1),r),c):void 0}(window,e,t,i,s,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,r)}getMouseReportCoords(e,t){let i=$c(window,e,t);if(this._charSizeService.hasValidSize)return i[0]=Math.min(Math.max(i[0],0),this._renderService.dimensions.css.canvas.width-1),i[1]=Math.min(Math.max(i[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(i[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(i[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(i[0]),y:Math.floor(i[1])}}};Hc=Wn([Fn(0,No),Fn(1,Co)],Hc);var Wc=class{constructor(e,t){this._renderCallback=e,this._coreBrowserService=t,this._refreshCallbacks=[]}dispose(){this._animationFrame&&(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0)}addRefreshCallback(e){return this._refreshCallbacks.push(e),this._animationFrame||(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh())),this._animationFrame}refresh(e,t,i){this._rowCount=i,e=void 0!==e?e:0,t=void 0!==t?t:this._rowCount-1,this._rowStart=void 0!==this._rowStart?Math.min(this._rowStart,e):e,this._rowEnd=void 0!==this._rowEnd?Math.max(this._rowEnd,t):t,!this._animationFrame&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()))}_innerRefresh(){if(this._animationFrame=void 0,void 0===this._rowStart||void 0===this._rowEnd||void 0===this._rowCount)return void this._runRefreshCallbacks();let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(let e of this._refreshCallbacks)e(0);this._refreshCallbacks=[]}},Fc={};((e,t)=>{for(var i in t)$n(e,i,{get:t[i],enumerable:!0})})(Fc,{getSafariVersion:()=>Gc,isChromeOS:()=>ih,isFirefox:()=>qc,isIpad:()=>Jc,isIphone:()=>Qc,isLegacyEdge:()=>Yc,isLinux:()=>th,isMac:()=>Zc,isNode:()=>Kc,isSafari:()=>Xc,isWindows:()=>eh});var Kc=typeof process<"u"&&"title"in process,Uc=Kc?"node":navigator.userAgent,Vc=Kc?"node":navigator.platform,qc=Uc.includes("Firefox"),Yc=Uc.includes("Edge"),Xc=/^((?!chrome|android).)*safari/i.test(Uc);function Gc(){if(!Xc)return 0;let e=Uc.match(/Version\/(\d+)/);return null===e||e.length<2?0:parseInt(e[1])}var Zc=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(Vc),Jc="iPad"===Vc,Qc="iPhone"===Vc,eh=["Windows","Win16","Win32","WinCE"].includes(Vc),th=Vc.indexOf("Linux")>=0,ih=/\bCrOS\b/.test(Uc),sh=class{constructor(){this._tasks=[],this._i=0}enqueue(e){this._tasks.push(e),this._start()}flush(){for(;this._i<this._tasks.length;)this._tasks[this._i]()||this._i++;this.clear()}clear(){this._idleCallback&&(this._cancelCallback(this._idleCallback),this._idleCallback=void 0),this._i=0,this._tasks.length=0}_start(){this._idleCallback||(this._idleCallback=this._requestCallback(this._process.bind(this)))}_process(e){this._idleCallback=void 0;let t=0,i=0,s=e.timeRemaining(),r=0;for(;this._i<this._tasks.length;){if(t=performance.now(),this._tasks[this._i]()||this._i++,t=Math.max(1,performance.now()-t),i=Math.max(t,i),r=e.timeRemaining(),1.5*i>r)return s-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(s-t))}ms`),void this._start();s=r}this.clear()}},rh=!Kc&&"requestIdleCallback"in window?class extends sh{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}}:class extends sh{_requestCallback(e){return setTimeout(()=>e(this._createDeadline(16)))}_cancelCallback(e){clearTimeout(e)}_createDeadline(e){let t=performance.now()+e;return{timeRemaining:()=>Math.max(0,t-performance.now())}}},nh=class{constructor(){this._queue=new rh}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},oh=class extends qo{constructor(e,t,i,s,r,n,o,a,l){super(),this._rowCount=e,this._optionsService=i,this._charSizeService=s,this._coreService=r,this._coreBrowserService=a,this._renderer=this._register(new Yo),this._pausedResizeTask=new nh,this._observerDisposable=this._register(new Yo),this._isPaused=!1,this._needsFullRefresh=!1,this._isNextRenderRedrawOnly=!0,this._needsSelectionRefresh=!1,this._canvasWidth=0,this._canvasHeight=0,this._selectionState={start:void 0,end:void 0,columnSelectMode:!1},this._onDimensionsChange=this._register(new da),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this._register(new da),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this._register(new da),this.onRender=this._onRender.event,this._onRefreshRequest=this._register(new da),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new Wc((e,t)=>this._renderRows(e,t),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new ah(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register(Ko(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(o.onResize(()=>this._fullRefresh())),this._register(o.buffers.onBufferActivate(()=>{var e;return null==(e=this._renderer.value)?void 0:e.clear()})),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._charSizeService.onCharSizeChange(()=>this.handleCharSizeChanged())),this._register(n.onDecorationRegistered(()=>this._fullRefresh())),this._register(n.onDecorationRemoved(()=>this._fullRefresh())),this._register(this._optionsService.onMultipleOptionChange(["customGlyphs","drawBoldTextInBrightColors","letterSpacing","lineHeight","fontFamily","fontSize","fontWeight","fontWeightBold","minimumContrastRatio","rescaleOverlappingGlyphs"],()=>{this.clear(),this.handleResize(o.cols,o.rows),this._fullRefresh()})),this._register(this._optionsService.onMultipleOptionChange(["cursorBlink","cursorStyle"],()=>this.refreshRows(o.buffer.y,o.buffer.y,!0))),this._register(l.onChangeColors(()=>this._fullRefresh())),this._registerIntersectionObserver(this._coreBrowserService.window,t),this._register(this._coreBrowserService.onWindowChange(e=>this._registerIntersectionObserver(e,t)))}get dimensions(){return this._renderer.value.dimensions}_registerIntersectionObserver(e,t){if("IntersectionObserver"in e){let i=new e.IntersectionObserver(e=>this._handleIntersectionChange(e[e.length-1]),{threshold:0});i.observe(t),this._observerDisposable.value=Ko(()=>i.disconnect())}}_handleIntersectionChange(e){this._isPaused=void 0===e.isIntersecting?0===e.intersectionRatio:!e.isIntersecting,!this._isPaused&&!this._charSizeService.hasValidSize&&this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(e,t,i=!1){if(this._isPaused)return void(this._needsFullRefresh=!0);if(this._coreService.decPrivateModes.synchronizedOutput)return void this._syncOutputHandler.bufferRows(e,t);let s=this._syncOutputHandler.flush();s&&(e=Math.min(e,s.start),t=Math.max(t,s.end)),i||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(e,t,this._rowCount)}_renderRows(e,t){if(this._renderer.value){if(this._coreService.decPrivateModes.synchronizedOutput)return void this._syncOutputHandler.bufferRows(e,t);e=Math.min(e,this._rowCount-1),t=Math.min(t,this._rowCount-1),this._renderer.value.renderRows(e,t),this._needsSelectionRefresh&&(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),this._needsSelectionRefresh=!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:e,end:t}),this._onRender.fire({start:e,end:t}),this._isNextRenderRedrawOnly=!0}}resize(e,t){this._rowCount=t,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(e){this._renderer.value=e,this._renderer.value&&(this._renderer.value.onRequestRedraw(e=>this.refreshRows(e.start,e.end,!0)),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(e){return this._renderDebouncer.addRefreshCallback(e)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){var e,t;this._renderer.value&&(null==(t=(e=this._renderer.value).clearTextureAtlas)||t.call(e),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(e,t){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set(()=>{var i;return null==(i=this._renderer.value)?void 0:i.handleResize(e,t)}):this._renderer.value.handleResize(e,t),this._fullRefresh())}handleCharSizeChanged(){var e;null==(e=this._renderer.value)||e.handleCharSizeChanged()}handleBlur(){var e;null==(e=this._renderer.value)||e.handleBlur()}handleFocus(){var e;null==(e=this._renderer.value)||e.handleFocus()}handleSelectionChanged(e,t,i){var s;this._selectionState.start=e,this._selectionState.end=t,this._selectionState.columnSelectMode=i,null==(s=this._renderer.value)||s.handleSelectionChanged(e,t,i)}handleCursorMove(){var e;null==(e=this._renderer.value)||e.handleCursorMove()}clear(){var e;null==(e=this._renderer.value)||e.clear()}};oh=Wn([Fn(2,vo),Fn(3,Co),Fn(4,po),Fn(5,bo),Fn(6,uo),Fn(7,ko),Fn(8,Do)],oh);var ah=class{constructor(e,t,i){this._coreBrowserService=e,this._coreService=t,this._onTimeout=i,this._start=0,this._end=0,this._isBuffering=!1}bufferRows(e,t){this._isBuffering?(this._start=Math.min(this._start,e),this._end=Math.max(this._end,t)):(this._start=e,this._end=t,this._isBuffering=!0),void 0===this._timeout&&(this._timeout=this._coreBrowserService.window.setTimeout(()=>{this._timeout=void 0,this._coreService.decPrivateModes.synchronizedOutput=!1,this._onTimeout()},1e3))}flush(){if(void 0!==this._timeout&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0),!this._isBuffering)return;let e={start:this._start,end:this._end};return this._isBuffering=!1,e}dispose(){void 0!==this._timeout&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0)}};function lh(e,t,i,s){let r,n=i.buffer.x,o=i.buffer.y;if(!i.buffer.hasScrollback)return function(e,t,i,s,r,n){return 0===ch(t,s,r,n).length?"":ph(uh(e,t,e,t-hh(t,r),!1,r).length,fh("D",n))}(n,o,0,t,i,s)+ch(o,t,i,s)+function(e,t,i,s,r,n){let o;o=ch(t,s,r,n).length>0?s-hh(s,r):t;let a=s,l=function(e,t,i,s,r,n){let o;return o=ch(i,s,r,n).length>0?s-hh(s,r):t,e<i&&o<=s||e>=i&&o<s?"C":"D"}(e,t,i,s,r,n);return ph(uh(e,o,i,a,"C"===l,r).length,fh(l,n))}(n,o,e,t,i,s);if(o===t)return r=n>e?"D":"C",ph(Math.abs(n-e),fh(r,s));r=o>t?"D":"C";let a=Math.abs(o-t),l=function(e,t){return t.cols-e}(o>t?e:n,i)+(a-1)*i.cols+1+function(e){return e-1}(o>t?n:e);return ph(l,fh(r,s))}function ch(e,t,i,s){let r=e-hh(e,i),n=t-hh(t,i),o=Math.abs(r-n)-function(e,t,i){var s;let r=0,n=e-hh(e,i),o=t-hh(t,i);for(let a=0;a<Math.abs(n-o);a++){let o="A"===dh(e,t)?-1:1;(null==(s=i.buffer.lines.get(n+o*a))?void 0:s.isWrapped)&&r++}return r}(e,t,i);return ph(o,fh(dh(e,t),s))}function hh(e,t){let i=0,s=t.buffer.lines.get(e),r=null==s?void 0:s.isWrapped;for(;r&&e>=0&&e<t.rows;)i++,s=t.buffer.lines.get(--e),r=null==s?void 0:s.isWrapped;return i}function dh(e,t){return e>t?"A":"B"}function uh(e,t,i,s,r,n){let o=e,a=t,l="";for(;(o!==i||a!==s)&&a>=0&&a<n.buffer.lines.length;)o+=r?1:-1,r&&o>n.cols-1?(l+=n.buffer.translateBufferLineToString(a,!1,e,o),o=0,e=0,a++):!r&&o<0&&(l+=n.buffer.translateBufferLineToString(a,!1,0,e+1),o=n.cols-1,e=o,a--);return l+n.buffer.translateBufferLineToString(a,!1,e,o)}function fh(e,t){let i=t?"O":"[";return Gl.ESC+i+e}function ph(e,t){e=Math.floor(e);let i="";for(let s=0;s<e;s++)i+=t;return i}var mh=class{constructor(e){this._bufferService=e,this.isSelectAllActive=!1,this.selectionStartLength=0}clearSelection(){this.selectionStart=void 0,this.selectionEnd=void 0,this.isSelectAllActive=!1,this.selectionStartLength=0}get finalSelectionStart(){return this.isSelectAllActive?[0,0]:this.selectionEnd&&this.selectionStart&&this.areSelectionValuesReversed()?this.selectionEnd:this.selectionStart}get finalSelectionEnd(){if(this.isSelectAllActive)return[this._bufferService.cols,this._bufferService.buffer.ybase+this._bufferService.rows-1];if(this.selectionStart){if(!this.selectionEnd||this.areSelectionValuesReversed()){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?e%this._bufferService.cols===0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)-1]:[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[e,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[Math.max(e,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){let e=this.selectionStart,t=this.selectionEnd;return!(!e||!t)&&(e[1]>t[1]||e[1]===t[1]&&e[0]>t[0])}handleTrim(e){return this.selectionStart&&(this.selectionStart[1]-=e),this.selectionEnd&&(this.selectionEnd[1]-=e),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}};function _h(e,t){if(e.start.y>e.end.y)throw new Error(`Buffer range end (${e.end.x}, ${e.end.y}) cannot be before start (${e.start.x}, ${e.start.y})`);return t*(e.end.y-e.start.y)+(e.end.x-e.start.x+1)}var gh=new RegExp(" ","g"),vh=class extends qo{constructor(e,t,i,s,r,n,o,a,l){super(),this._element=e,this._screenElement=t,this._linkifier=i,this._bufferService=s,this._coreService=r,this._mouseService=n,this._optionsService=o,this._renderService=a,this._coreBrowserService=l,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new oo,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this._register(new da),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this._register(new da),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this._register(new da),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this._register(new da),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=e=>this._handleMouseMove(e),this._mouseUpListener=e=>this._handleMouseUp(e),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(e=>this._handleTrim(e)),this._register(this._bufferService.buffers.onBufferActivate(e=>this._handleBufferActivate(e))),this.enable(),this._model=new mh(this._bufferService),this._activeSelectionMode=0,this._register(Ko(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(e=>{e.rowsChanged&&this.clearSelection()}))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;return!(!e||!t)&&(e[0]!==t[0]||e[1]!==t[1])}get selectionText(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;if(!e||!t)return"";let i=this._bufferService.buffer,s=[];if(3===this._activeSelectionMode){if(e[0]===t[0])return"";let r=e[0]<t[0]?e[0]:t[0],n=e[0]<t[0]?t[0]:e[0];for(let o=e[1];o<=t[1];o++){let e=i.translateBufferLineToString(o,!0,r,n);s.push(e)}}else{let r=e[1]===t[1]?t[0]:void 0;s.push(i.translateBufferLineToString(e[1],!0,e[0],r));for(let n=e[1]+1;n<=t[1]-1;n++){let e=i.lines.get(n),t=i.translateBufferLineToString(n,!0);(null==e?void 0:e.isWrapped)?s[s.length-1]+=t:s.push(t)}if(e[1]!==t[1]){let e=i.lines.get(t[1]),r=i.translateBufferLineToString(t[1],!0,0,t[0]);e&&e.isWrapped?s[s.length-1]+=r:s.push(r)}}return s.map(e=>e.replace(gh," ")).join(eh?"\r\n":"\n")}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),th&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:3===this._activeSelectionMode})}_isClickInSelection(e){let t=this._getMouseBufferCoords(e),i=this._model.finalSelectionStart,s=this._model.finalSelectionEnd;return!!(i&&s&&t)&&this._areCoordsInSelection(t,i,s)}isCellInSelection(e,t){let i=this._model.finalSelectionStart,s=this._model.finalSelectionEnd;return!(!i||!s)&&this._areCoordsInSelection([e,t],i,s)}_areCoordsInSelection(e,t,i){return e[1]>t[1]&&e[1]<i[1]||t[1]===i[1]&&e[1]===t[1]&&e[0]>=t[0]&&e[0]<i[0]||t[1]<i[1]&&e[1]===i[1]&&e[0]<i[0]||t[1]<i[1]&&e[1]===t[1]&&e[0]>=t[0]}_selectWordAtCursor(e,t){var i,s;let r=null==(s=null==(i=this._linkifier.currentLink)?void 0:i.link)?void 0:s.range;if(r)return this._model.selectionStart=[r.start.x-1,r.start.y-1],this._model.selectionStartLength=_h(r,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let n=this._getMouseBufferCoords(e);return!!n&&(this._selectWordAt(n,t),this._model.selectionEnd=void 0,!0)}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=$c(this._coreBrowserService.window,e,this._screenElement)[1],i=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=i?0:(t>i&&(t-=i),t=Math.min(Math.max(t,-50),50),t/=50,t/Math.abs(t)+Math.round(14*t))}shouldForceSelection(e){return Zc?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,(2!==e.button||!this.hasSelection)&&0===e.button){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):1===e.detail?this._handleSingleClick(e):2===e.detail?this._handleDoubleClick(e):3===e.detail&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener("mouseup",this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),50)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener("mouseup",this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&0===t.hasWidth(this._model.selectionStart[0])&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(Zc&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd)return void this.refresh(!0);2===this._activeSelectionMode?this._model.selectionEnd[1]<this._model.selectionStart[1]?this._model.selectionEnd[0]=0:this._model.selectionEnd[0]=this._bufferService.cols:1===this._activeSelectionMode&&this._selectToWordAt(this._model.selectionEnd),this._dragScrollAmount=this._getMouseEventScrollAmount(e),3!==this._activeSelectionMode&&(this._dragScrollAmount>0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));let i=this._bufferService.buffer;if(this._model.selectionEnd[1]<i.lines.length){let e=i.lines.get(this._model.selectionEnd[1]);e&&0===e.hasWidth(this._model.selectionEnd[0])&&this._model.selectionEnd[0]<this._bufferService.cols&&this._model.selectionEnd[0]++}(!t||t[0]!==this._model.selectionEnd[0]||t[1]!==this._model.selectionEnd[1])&&this.refresh(!0)}_dragScroll(){if(this._model.selectionEnd&&this._model.selectionStart&&this._dragScrollAmount){this._onRequestScrollLines.fire({amount:this._dragScrollAmount,suppressScrollEvent:!1});let e=this._bufferService.buffer;this._dragScrollAmount>0?(3!==this._activeSelectionMode&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(3!==this._activeSelectionMode&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}}_handleMouseUp(e){let t=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&t<500&&e.altKey&&this._optionsService.rawOptions.altClickMovesCursor){if(this._bufferService.buffer.ybase===this._bufferService.buffer.ydisp){let t=this._mouseService.getCoords(e,this._element,this._bufferService.cols,this._bufferService.rows,!1);if(t&&void 0!==t[0]&&void 0!==t[1]){let e=lh(t[0]-1,t[1]-1,this._bufferService,this._coreService.decPrivateModes.applicationCursorKeys);this._coreService.triggerDataEvent(e,!0)}}}else this._fireEventIfSelectionChanged()}_fireEventIfSelectionChanged(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd,i=!(!e||!t||e[0]===t[0]&&e[1]===t[1]);i?!e||!t||(!this._oldSelectionStart||!this._oldSelectionEnd||e[0]!==this._oldSelectionStart[0]||e[1]!==this._oldSelectionStart[1]||t[0]!==this._oldSelectionEnd[0]||t[1]!==this._oldSelectionEnd[1])&&this._fireOnSelectionChange(e,t,i):this._oldHasSelection&&this._fireOnSelectionChange(e,t,i)}_fireOnSelectionChange(e,t,i){this._oldSelectionStart=e,this._oldSelectionEnd=t,this._oldHasSelection=i,this._onSelectionChange.fire()}_handleBufferActivate(e){this.clearSelection(),this._trimListener.dispose(),this._trimListener=e.activeBuffer.lines.onTrim(e=>this._handleTrim(e))}_convertViewportColToCharacterIndex(e,t){let i=t;for(let s=0;t>=s;s++){let r=e.loadCell(s,this._workCell).getChars().length;0===this._workCell.getWidth()?i--:r>1&&t!==s&&(i+=r-1)}return i}setSelection(e,t,i){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=i,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,t,i=!0,s=!0){if(e[0]>=this._bufferService.cols)return;let r=this._bufferService.buffer,n=r.lines.get(e[1]);if(!n)return;let o=r.translateBufferLineToString(e[1],!1),a=this._convertViewportColToCharacterIndex(n,e[0]),l=a,c=e[0]-a,h=0,d=0,u=0,f=0;if(" "===o.charAt(a)){for(;a>0&&" "===o.charAt(a-1);)a--;for(;l<o.length&&" "===o.charAt(l+1);)l++}else{let t=e[0],i=e[0];0===n.getWidth(t)&&(h++,t--),2===n.getWidth(i)&&(d++,i++);let s=n.getString(i).length;for(s>1&&(f+=s-1,l+=s-1);t>0&&a>0&&!this._isCharWordSeparator(n.loadCell(t-1,this._workCell));){n.loadCell(t-1,this._workCell);let e=this._workCell.getChars().length;0===this._workCell.getWidth()?(h++,t--):e>1&&(u+=e-1,a-=e-1),a--,t--}for(;i<n.length&&l+1<o.length&&!this._isCharWordSeparator(n.loadCell(i+1,this._workCell));){n.loadCell(i+1,this._workCell);let e=this._workCell.getChars().length;2===this._workCell.getWidth()?(d++,i++):e>1&&(f+=e-1,l+=e-1),l++,i++}}l++;let p=a+c-h+u,m=Math.min(this._bufferService.cols,l-a+h+d-u-f);if(t||""!==o.slice(a,l).trim()){if(i&&0===p&&32!==n.getCodePoint(0)){let t=r.lines.get(e[1]-1);if(t&&n.isWrapped&&32!==t.getCodePoint(this._bufferService.cols-1)){let t=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(t){let e=this._bufferService.cols-t.start;p-=e,m+=e}}}if(s&&p+m===this._bufferService.cols&&32!==n.getCodePoint(this._bufferService.cols-1)){let t=r.lines.get(e[1]+1);if((null==t?void 0:t.isWrapped)&&32!==t.getCodePoint(0)){let t=this._getWordAt([0,e[1]+1],!1,!1,!0);t&&(m+=t.length)}}return{start:p,length:m}}}_selectWordAt(e,t){let i=this._getWordAt(e,t);if(i){for(;i.start<0;)i.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[i.start,e[1]],this._model.selectionStartLength=i.length}}_selectToWordAt(e){let t=this._getWordAt(e,!0);if(t){let i=e[1];for(;t.start<0;)t.start+=this._bufferService.cols,i--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,i++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,i]}}_isCharWordSeparator(e){return 0!==e.getWidth()&&this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){let t=this._bufferService.buffer.getWrappedRangeForLine(e),i={start:{x:0,y:t.first},end:{x:this._bufferService.cols-1,y:t.last}};this._model.selectionStart=[0,t.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=_h(i,this._bufferService.cols)}};vh=Wn([Fn(3,uo),Fn(4,po),Fn(5,Eo),Fn(6,vo),Fn(7,No),Fn(8,ko)],vh);var yh=class{constructor(){this._data={}}set(e,t,i){this._data[e]||(this._data[e]={}),this._data[e][t]=i}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}},xh=class{constructor(){this._color=new yh,this._css=new yh}setCss(e,t,i){this._css.set(e,t,i)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,i){this._color.set(e,t,i)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}},bh=Object.freeze((()=>{let e=[cc.toColor("#2e3436"),cc.toColor("#cc0000"),cc.toColor("#4e9a06"),cc.toColor("#c4a000"),cc.toColor("#3465a4"),cc.toColor("#75507b"),cc.toColor("#06989a"),cc.toColor("#d3d7cf"),cc.toColor("#555753"),cc.toColor("#ef2929"),cc.toColor("#8ae234"),cc.toColor("#fce94f"),cc.toColor("#729fcf"),cc.toColor("#ad7fa8"),cc.toColor("#34e2e2"),cc.toColor("#eeeeec")],t=[0,95,135,175,215,255];for(let i=0;i<216;i++){let s=t[i/36%6|0],r=t[i/6%6|0],n=t[i%6];e.push({css:ac.toCss(s,r,n),rgba:ac.toRgba(s,r,n)})}for(let i=0;i<24;i++){let t=8+10*i;e.push({css:ac.toCss(t,t,t),rgba:ac.toRgba(t,t,t)})}return e})()),wh=cc.toColor("#ffffff"),Sh=cc.toColor("#000000"),Ch=cc.toColor("#ffffff"),kh=Sh,Eh={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117},Nh=wh,Mh=class extends qo{constructor(e){super(),this._optionsService=e,this._contrastCache=new xh,this._halfContrastCache=new xh,this._onChangeColors=this._register(new da),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:wh,background:Sh,cursor:Ch,cursorAccent:kh,selectionForeground:void 0,selectionBackgroundTransparent:Eh,selectionBackgroundOpaque:lc.blend(Sh,Eh),selectionInactiveBackgroundTransparent:Eh,selectionInactiveBackgroundOpaque:lc.blend(Sh,Eh),scrollbarSliderBackground:lc.opacity(wh,.2),scrollbarSliderHoverBackground:lc.opacity(wh,.4),scrollbarSliderActiveBackground:lc.opacity(wh,.5),overviewRulerBorder:wh,ansi:bh.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this._register(this._optionsService.onSpecificOptionChange("minimumContrastRatio",()=>this._contrastCache.clear())),this._register(this._optionsService.onSpecificOptionChange("theme",()=>this._setTheme(this._optionsService.rawOptions.theme)))}get colors(){return this._colors}_setTheme(e={}){let t=this._colors;if(t.foreground=jh(e.foreground,wh),t.background=jh(e.background,Sh),t.cursor=lc.blend(t.background,jh(e.cursor,Ch)),t.cursorAccent=lc.blend(t.background,jh(e.cursorAccent,kh)),t.selectionBackgroundTransparent=jh(e.selectionBackground,Eh),t.selectionBackgroundOpaque=lc.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=jh(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=lc.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?jh(e.selectionForeground,_c):void 0,t.selectionForeground===_c&&(t.selectionForeground=void 0),lc.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=lc.opacity(t.selectionBackgroundTransparent,.3)),lc.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=lc.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=jh(e.scrollbarSliderBackground,lc.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=jh(e.scrollbarSliderHoverBackground,lc.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=jh(e.scrollbarSliderActiveBackground,lc.opacity(t.foreground,.5)),t.overviewRulerBorder=jh(e.overviewRulerBorder,Nh),t.ansi=bh.slice(),t.ansi[0]=jh(e.black,bh[0]),t.ansi[1]=jh(e.red,bh[1]),t.ansi[2]=jh(e.green,bh[2]),t.ansi[3]=jh(e.yellow,bh[3]),t.ansi[4]=jh(e.blue,bh[4]),t.ansi[5]=jh(e.magenta,bh[5]),t.ansi[6]=jh(e.cyan,bh[6]),t.ansi[7]=jh(e.white,bh[7]),t.ansi[8]=jh(e.brightBlack,bh[8]),t.ansi[9]=jh(e.brightRed,bh[9]),t.ansi[10]=jh(e.brightGreen,bh[10]),t.ansi[11]=jh(e.brightYellow,bh[11]),t.ansi[12]=jh(e.brightBlue,bh[12]),t.ansi[13]=jh(e.brightMagenta,bh[13]),t.ansi[14]=jh(e.brightCyan,bh[14]),t.ansi[15]=jh(e.brightWhite,bh[15]),e.extendedAnsi){let i=Math.min(t.ansi.length-16,e.extendedAnsi.length);for(let s=0;s<i;s++)t.ansi[s+16]=jh(e.extendedAnsi[s],bh[s+16])}this._contrastCache.clear(),this._halfContrastCache.clear(),this._updateRestoreColors(),this._onChangeColors.fire(this.colors)}restoreColor(e){this._restoreColor(e),this._onChangeColors.fire(this.colors)}_restoreColor(e){if(void 0!==e)switch(e){case 256:this._colors.foreground=this._restoreColors.foreground;break;case 257:this._colors.background=this._restoreColors.background;break;case 258:this._colors.cursor=this._restoreColors.cursor;break;default:this._colors.ansi[e]=this._restoreColors.ansi[e]}else for(let t=0;t<this._restoreColors.ansi.length;++t)this._colors.ansi[t]=this._restoreColors.ansi[t]}modifyColors(e){e(this._colors),this._onChangeColors.fire(this.colors)}_updateRestoreColors(){this._restoreColors={foreground:this._colors.foreground,background:this._colors.background,cursor:this._colors.cursor,ansi:this._colors.ansi.slice()}}};function jh(e,t){if(void 0!==e)try{return cc.toColor(e)}catch{}return t}Mh=Wn([Fn(0,vo)],Mh);var Dh=class{constructor(...e){this._entries=new Map;for(let[t,i]of e)this.set(t,i)}set(e,t){let i=this._entries.get(e);return this._entries.set(e,t),i}forEach(e){for(let[t,i]of this._entries.entries())e(t,i)}has(e){return this._entries.has(e)}get(e){return this._entries.get(e)}},Rh=class{constructor(){this._services=new Dh,this._services.set(_o,this)}setService(e,t){this._services.set(e,t)}getService(e){return this._services.get(e)}createInstance(e,...t){let i=(r=e,r[lo]||[]).sort((e,t)=>e.index-t.index),s=[];var r;for(let o of i){let t=this._services.get(o.id);if(!t)throw new Error(`[createInstance] ${e.name} depends on UNKNOWN service ${o.id._id}.`);s.push(t)}let n=i.length>0?i[0].index:t.length;if(t.length!==n)throw new Error(`[createInstance] First service dependency of ${e.name} at position ${n+1} conflicts with ${t.length} static arguments`);return new e(...t,...s)}},Ph={trace:0,debug:1,info:2,warn:3,error:4,off:5},Lh=class extends qo{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange("logLevel",()=>this._updateLogLevel()))}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=Ph[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let t=0;t<e.length;t++)"function"==typeof e[t]&&(e[t]=e[t]())}_log(e,t,i){this._evalLazyOptionalParams(i),e.call(console,(this._optionsService.options.logger?"":"xterm.js: ")+t,...i)}trace(e,...t){var i;this._logLevel<=0&&this._log((null==(i=this._optionsService.options.logger)?void 0:i.trace.bind(this._optionsService.options.logger))??console.log,e,t)}debug(e,...t){var i;this._logLevel<=1&&this._log((null==(i=this._optionsService.options.logger)?void 0:i.debug.bind(this._optionsService.options.logger))??console.log,e,t)}info(e,...t){var i;this._logLevel<=2&&this._log((null==(i=this._optionsService.options.logger)?void 0:i.info.bind(this._optionsService.options.logger))??console.info,e,t)}warn(e,...t){var i;this._logLevel<=3&&this._log((null==(i=this._optionsService.options.logger)?void 0:i.warn.bind(this._optionsService.options.logger))??console.warn,e,t)}error(e,...t){var i;this._logLevel<=4&&this._log((null==(i=this._optionsService.options.logger)?void 0:i.error.bind(this._optionsService.options.logger))??console.error,e,t)}};Lh=Wn([Fn(0,vo)],Lh);var Ih=class extends qo{constructor(e){super(),this._maxLength=e,this.onDeleteEmitter=this._register(new da),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this._register(new da),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this._register(new da),this.onTrim=this.onTrimEmitter.event,this._array=new Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(e){if(this._maxLength===e)return;let t=new Array(e);for(let i=0;i<Math.min(e,this.length);i++)t[i]=this._array[this._getCyclicIndex(i)];this._array=t,this._maxLength=e,this._startIndex=0}get length(){return this._length}set length(e){if(e>this._length)for(let t=this._length;t<e;t++)this._array[t]=void 0;this._length=e}get(e){return this._array[this._getCyclicIndex(e)]}set(e,t){this._array[this._getCyclicIndex(e)]=t}push(e){this._array[this._getCyclicIndex(this._length)]=e,this._length===this._maxLength?(this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1)):this._length++}recycle(){if(this._length!==this._maxLength)throw new Error("Can only recycle when the buffer is full");return this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1),this._array[this._getCyclicIndex(this._length-1)]}get isFull(){return this._length===this._maxLength}pop(){return this._array[this._getCyclicIndex(this._length---1)]}splice(e,t,...i){if(t){for(let i=e;i<this._length-t;i++)this._array[this._getCyclicIndex(i)]=this._array[this._getCyclicIndex(i+t)];this._length-=t,this.onDeleteEmitter.fire({index:e,amount:t})}for(let s=this._length-1;s>=e;s--)this._array[this._getCyclicIndex(s+i.length)]=this._array[this._getCyclicIndex(s)];for(let s=0;s<i.length;s++)this._array[this._getCyclicIndex(e+s)]=i[s];if(i.length&&this.onInsertEmitter.fire({index:e,amount:i.length}),this._length+i.length>this._maxLength){let e=this._length+i.length-this._maxLength;this._startIndex+=e,this._length=this._maxLength,this.onTrimEmitter.fire(e)}else this._length+=i.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,i){if(!(t<=0)){if(e<0||e>=this._length)throw new Error("start argument out of range");if(e+i<0)throw new Error("Cannot shift elements in list beyond index 0");if(i>0){for(let r=t-1;r>=0;r--)this.set(e+r+i,this.get(e+r));let s=e+t+i-this._length;if(s>0)for(this._length+=s;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let s=0;s<t;s++)this.set(e+s+i,this.get(e+s))}}_getCyclicIndex(e){return(this._startIndex+e)%this._maxLength}},Th=Object.freeze(new ro),Bh=0,Oh=class e{constructor(e,t,i=!1){this.isWrapped=i,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(3*e);let s=t||oo.fromCharData([0,"",1,0]);for(let r=0;r<e;++r)this.setCell(r,s);this.length=e}get(e){let t=this._data[3*e+0],i=2097151&t;return[this._data[3*e+1],2097152&t?this._combined[e]:i?Qn(i):"",t>>22,2097152&t?this._combined[e].charCodeAt(this._combined[e].length-1):i]}set(e,t){this._data[3*e+1]=t[0],t[1].length>1?(this._combined[e]=t[1],this._data[3*e+0]=2097152|e|t[2]<<22):this._data[3*e+0]=t[1].charCodeAt(0)|t[2]<<22}getWidth(e){return this._data[3*e+0]>>22}hasWidth(e){return 12582912&this._data[3*e+0]}getFg(e){return this._data[3*e+1]}getBg(e){return this._data[3*e+2]}hasContent(e){return 4194303&this._data[3*e+0]}getCodePoint(e){let t=this._data[3*e+0];return 2097152&t?this._combined[e].charCodeAt(this._combined[e].length-1):2097151&t}isCombined(e){return 2097152&this._data[3*e+0]}getString(e){let t=this._data[3*e+0];return 2097152&t?this._combined[e]:2097151&t?Qn(2097151&t):""}isProtected(e){return 536870912&this._data[3*e+2]}loadCell(e,t){return Bh=3*e,t.content=this._data[Bh+0],t.fg=this._data[Bh+1],t.bg=this._data[Bh+2],2097152&t.content&&(t.combinedData=this._combined[e]),268435456&t.bg&&(t.extended=this._extendedAttrs[e]),t}setCell(e,t){2097152&t.content&&(this._combined[e]=t.combinedData),268435456&t.bg&&(this._extendedAttrs[e]=t.extended),this._data[3*e+0]=t.content,this._data[3*e+1]=t.fg,this._data[3*e+2]=t.bg}setCellFromCodepoint(e,t,i,s){268435456&s.bg&&(this._extendedAttrs[e]=s.extended),this._data[3*e+0]=t|i<<22,this._data[3*e+1]=s.fg,this._data[3*e+2]=s.bg}addCodepointToCell(e,t,i){let s=this._data[3*e+0];2097152&s?this._combined[e]+=Qn(t):2097151&s?(this._combined[e]=Qn(2097151&s)+Qn(t),s&=-2097152,s|=2097152):s=t|1<<22,i&&(s&=-12582913,s|=i<<22),this._data[3*e+0]=s}insertCells(e,t,i){if((e%=this.length)&&2===this.getWidth(e-1)&&this.setCellFromCodepoint(e-1,0,1,i),t<this.length-e){let s=new oo;for(let i=this.length-e-t-1;i>=0;--i)this.setCell(e+t+i,this.loadCell(e+i,s));for(let r=0;r<t;++r)this.setCell(e+r,i)}else for(let s=e;s<this.length;++s)this.setCell(s,i);2===this.getWidth(this.length-1)&&this.setCellFromCodepoint(this.length-1,0,1,i)}deleteCells(e,t,i){if(e%=this.length,t<this.length-e){let s=new oo;for(let i=0;i<this.length-e-t;++i)this.setCell(e+i,this.loadCell(e+t+i,s));for(let e=this.length-t;e<this.length;++e)this.setCell(e,i)}else for(let s=e;s<this.length;++s)this.setCell(s,i);e&&2===this.getWidth(e-1)&&this.setCellFromCodepoint(e-1,0,1,i),0===this.getWidth(e)&&!this.hasContent(e)&&this.setCellFromCodepoint(e,0,1,i)}replaceCells(e,t,i,s=!1){if(s)for(e&&2===this.getWidth(e-1)&&!this.isProtected(e-1)&&this.setCellFromCodepoint(e-1,0,1,i),t<this.length&&2===this.getWidth(t-1)&&!this.isProtected(t)&&this.setCellFromCodepoint(t,0,1,i);e<t&&e<this.length;)this.isProtected(e)||this.setCell(e,i),e++;else for(e&&2===this.getWidth(e-1)&&this.setCellFromCodepoint(e-1,0,1,i),t<this.length&&2===this.getWidth(t-1)&&this.setCellFromCodepoint(t,0,1,i);e<t&&e<this.length;)this.setCell(e++,i)}resize(e,t){if(e===this.length)return 4*this._data.length*2<this._data.buffer.byteLength;let i=3*e;if(e>this.length){if(this._data.buffer.byteLength>=4*i)this._data=new Uint32Array(this._data.buffer,0,i);else{let e=new Uint32Array(i);e.set(this._data),this._data=e}for(let i=this.length;i<e;++i)this.setCell(i,t)}else{this._data=this._data.subarray(0,i);let t=Object.keys(this._combined);for(let i=0;i<t.length;i++){let s=parseInt(t[i],10);s>=e&&delete this._combined[s]}let s=Object.keys(this._extendedAttrs);for(let i=0;i<s.length;i++){let t=parseInt(s[i],10);t>=e&&delete this._extendedAttrs[t]}}return this.length=e,4*i*2<this._data.buffer.byteLength}cleanupMemory(){if(4*this._data.length*2<this._data.buffer.byteLength){let e=new Uint32Array(this._data.length);return e.set(this._data),this._data=e,1}return 0}fill(e,t=!1){if(t)for(let i=0;i<this.length;++i)this.isProtected(i)||this.setCell(i,e);else{this._combined={},this._extendedAttrs={};for(let t=0;t<this.length;++t)this.setCell(t,e)}}copyFrom(e){this.length!==e.length?this._data=new Uint32Array(e._data):this._data.set(e._data),this.length=e.length,this._combined={};for(let t in e._combined)this._combined[t]=e._combined[t];this._extendedAttrs={};for(let t in e._extendedAttrs)this._extendedAttrs[t]=e._extendedAttrs[t];this.isWrapped=e.isWrapped}clone(){let t=new e(0);t._data=new Uint32Array(this._data),t.length=this.length;for(let e in this._combined)t._combined[e]=this._combined[e];for(let e in this._extendedAttrs)t._extendedAttrs[e]=this._extendedAttrs[e];return t.isWrapped=this.isWrapped,t}getTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(4194303&this._data[3*e+0])return e+(this._data[3*e+0]>>22);return 0}getNoBgTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(4194303&this._data[3*e+0]||50331648&this._data[3*e+2])return e+(this._data[3*e+0]>>22);return 0}copyCellsFrom(e,t,i,s,r){let n=e._data;if(r)for(let a=s-1;a>=0;a--){for(let e=0;e<3;e++)this._data[3*(i+a)+e]=n[3*(t+a)+e];268435456&n[3*(t+a)+2]&&(this._extendedAttrs[i+a]=e._extendedAttrs[t+a])}else for(let a=0;a<s;a++){for(let e=0;e<3;e++)this._data[3*(i+a)+e]=n[3*(t+a)+e];268435456&n[3*(t+a)+2]&&(this._extendedAttrs[i+a]=e._extendedAttrs[t+a])}let o=Object.keys(e._combined);for(let a=0;a<o.length;a++){let s=parseInt(o[a],10);s>=t&&(this._combined[s-t+i]=e._combined[s])}}translateToString(e,t,i,s){t=t??0,i=i??this.length,e&&(i=Math.min(i,this.getTrimmedLength())),s&&(s.length=0);let r="";for(;t<i;){let e=this._data[3*t+0],i=2097151&e,n=2097152&e?this._combined[t]:i?Qn(i):so;if(r+=n,s)for(let r=0;r<n.length;++r)s.push(t);t+=e>>22||1}return s&&s.push(t),r}};function Ah(e,t,i){let s=[],r=e.map((i,s)=>zh(e,s,t)).reduce((e,t)=>e+t),n=0,o=0,a=0;for(;a<r;){if(r-a<i){s.push(r-a);break}n+=i;let l=zh(e,o,t);n>l&&(n-=l,o++);let c=2===e[o].getWidth(n-1);c&&n--;let h=c?i-1:i;s.push(h),a+=h}return s}function zh(e,t,i){if(t===e.length-1)return e[t].getTrimmedLength();let s=!e[t].hasContent(i-1)&&1===e[t].getWidth(i-1),r=2===e[t+1].getWidth(0);return s&&r?i-1:i}var $h=class e{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=e._nextId++,this._onDispose=this.register(new da),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),Fo(this._disposables),this._disposables.length=0)}register(e){return this._disposables.push(e),e}};$h._nextId=1;var Hh=$h,Wh={},Fh=Wh.B;Wh[0]={"`":"◆",a:"▒",b:"␉",c:"␌",d:"␍",e:"␊",f:"°",g:"±",h:"␤",i:"␋",j:"┘",k:"┐",l:"┌",m:"└",n:"┼",o:"⎺",p:"⎻",q:"─",r:"⎼",s:"⎽",t:"├",u:"┤",v:"┴",w:"┬",x:"│",y:"≤",z:"≥","{":"π","|":"≠","}":"£","~":"·"},Wh.A={"#":"£"},Wh.B=void 0,Wh[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"},Wh.C=Wh[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"},Wh.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"},Wh.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"},Wh.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"},Wh.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"},Wh.E=Wh[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"},Wh.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"},Wh.H=Wh[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"},Wh["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"};var Kh=4294967295,Uh=class{constructor(e,t,i){this._hasScrollback=e,this._optionsService=t,this._bufferService=i,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=Th.clone(),this.savedCharset=Fh,this.markers=[],this._nullCell=oo.fromCharData([0,"",1,0]),this._whitespaceCell=oo.fromCharData([0,so,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new rh,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new Ih(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg,this._nullCell.extended=e.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new no),this._nullCell}getWhitespaceCell(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg,this._whitespaceCell.extended=e.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new no),this._whitespaceCell}getBlankLine(e,t){return new Oh(this._bufferService.cols,this.getNullCell(e),t)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let e=this.ybase+this.y-this.ydisp;return e>=0&&e<this._rows}_getCorrectBufferLength(e){if(!this._hasScrollback)return e;let t=e+this._optionsService.rawOptions.scrollback;return t>Kh?Kh:t}fillViewportRows(e){if(0===this.lines.length){void 0===e&&(e=Th);let t=this._rows;for(;t--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new Ih(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let i=this.getNullCell(Th),s=0,r=this._getCorrectBufferLength(t);if(r>this.lines.maxLength&&(this.lines.maxLength=r),this.lines.length>0){if(this._cols<e)for(let t=0;t<this.lines.length;t++)s+=+this.lines.get(t).resize(e,i);let n=0;if(this._rows<t)for(let s=this._rows;s<t;s++)this.lines.length<t+this.ybase&&(this._optionsService.rawOptions.windowsMode||void 0!==this._optionsService.rawOptions.windowsPty.backend||void 0!==this._optionsService.rawOptions.windowsPty.buildNumber?this.lines.push(new Oh(e,i)):this.ybase>0&&this.lines.length<=this.ybase+this.y+n+1?(this.ybase--,n++,this.ydisp>0&&this.ydisp--):this.lines.push(new Oh(e,i)));else for(let e=this._rows;e>t;e--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(r<this.lines.maxLength){let e=this.lines.length-r;e>0&&(this.lines.trimStart(e),this.ybase=Math.max(this.ybase-e,0),this.ydisp=Math.max(this.ydisp-e,0),this.savedY=Math.max(this.savedY-e,0)),this.lines.maxLength=r}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),n&&(this.y+=n),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(let n=0;n<this.lines.length;n++)s+=+this.lines.get(n).resize(e,i);this._cols=e,this._rows=t,this._memoryCleanupQueue.clear(),s>.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let e=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e=!1);let t=0;for(;this._memoryCleanupPosition<this.lines.length;)if(t+=this.lines.get(this._memoryCleanupPosition++).cleanupMemory(),t>100)return!0;return e}get _isReflowEnabled(){let e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&"conpty"===e.backend&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))}_reflowLarger(e,t){let i=this._optionsService.rawOptions.reflowCursorLine,s=function(e,t,i,s,r,n){let o=[];for(let a=0;a<e.length-1;a++){let l=a,c=e.get(++l);if(!c.isWrapped)continue;let h=[e.get(a)];for(;l<e.length&&c.isWrapped;)h.push(c),c=e.get(++l);if(!n&&s>=a&&s<l){a+=h.length-1;continue}let d=0,u=zh(h,d,t),f=1,p=0;for(;f<h.length;){let e=zh(h,f,t),s=e-p,n=i-u,o=Math.min(s,n);h[d].copyCellsFrom(h[f],p,u,o,!1),u+=o,u===i&&(d++,u=0),p+=o,p===e&&(f++,p=0),0===u&&0!==d&&2===h[d-1].getWidth(i-1)&&(h[d].copyCellsFrom(h[d-1],i-1,u++,1,!1),h[d-1].setCell(i-1,r))}h[d].replaceCells(u,i,r);let m=0;for(let e=h.length-1;e>0&&(e>d||0===h[e].getTrimmedLength());e--)m++;m>0&&(o.push(a+h.length-m),o.push(m)),a+=h.length-1}return o}(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(Th),i);if(s.length>0){let i=function(e,t){let i=[],s=0,r=t[s],n=0;for(let o=0;o<e.length;o++)if(r===o){let i=t[++s];e.onDeleteEmitter.fire({index:o-n,amount:i}),o+=i-1,n+=i,r=t[++s]}else i.push(o);return{layout:i,countRemoved:n}}(this.lines,s);(function(e,t){let i=[];for(let s=0;s<t.length;s++)i.push(e.get(t[s]));for(let s=0;s<i.length;s++)e.set(s,i[s]);e.length=t.length})(this.lines,i.layout),this._reflowLargerAdjustViewport(e,t,i.countRemoved)}}_reflowLargerAdjustViewport(e,t,i){let s=this.getNullCell(Th),r=i;for(;r-- >0;)0===this.ybase?(this.y>0&&this.y--,this.lines.length<t&&this.lines.push(new Oh(e,s))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-i,0)}_reflowSmaller(e,t){let i=this._optionsService.rawOptions.reflowCursorLine,s=this.getNullCell(Th),r=[],n=0;for(let o=this.lines.length-1;o>=0;o--){let a=this.lines.get(o);if(!a||!a.isWrapped&&a.getTrimmedLength()<=e)continue;let l=[a];for(;a.isWrapped&&o>0;)a=this.lines.get(--o),l.unshift(a);if(!i){let e=this.ybase+this.y;if(e>=o&&e<o+l.length)continue}let c,h=l[l.length-1].getTrimmedLength(),d=Ah(l,this._cols,e),u=d.length-l.length;c=0===this.ybase&&this.y!==this.lines.length-1?Math.max(0,this.y-this.lines.maxLength+u):Math.max(0,this.lines.length-this.lines.maxLength+u);let f=[];for(let e=0;e<u;e++){let e=this.getBlankLine(Th,!0);f.push(e)}f.length>0&&(r.push({start:o+l.length+n,newLines:f}),n+=f.length),l.push(...f);let p=d.length-1,m=d[p];0===m&&(p--,m=d[p]);let _=l.length-u-1,g=h;for(;_>=0;){let e=Math.min(g,m);if(void 0===l[p])break;if(l[p].copyCellsFrom(l[_],g-e,m-e,e,!0),m-=e,0===m&&(p--,m=d[p]),g-=e,0===g){_--,g=zh(l,Math.max(_,0),this._cols)}}for(let t=0;t<l.length;t++)d[t]<e&&l[t].setCell(d[t],s);let v=u-c;for(;v-- >0;)0===this.ybase?this.y<t-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+n)-t&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+u,this.ybase+t-1)}if(r.length>0){let e=[],t=[];for(let r=0;r<this.lines.length;r++)t.push(this.lines.get(r));let i=this.lines.length,s=i-1,o=0,a=r[o];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+n);let l=0;for(let d=Math.min(this.lines.maxLength-1,i+n-1);d>=0;d--)if(a&&a.start>s+l){for(let e=a.newLines.length-1;e>=0;e--)this.lines.set(d--,a.newLines[e]);d++,e.push({index:s+1,amount:a.newLines.length}),l+=a.newLines.length,a=r[++o]}else this.lines.set(d,t[s--]);let c=0;for(let r=e.length-1;r>=0;r--)e[r].index+=c,this.lines.onInsertEmitter.fire(e[r]),c+=e[r].amount;let h=Math.max(0,i+n-this.lines.maxLength);h>0&&this.lines.onTrimEmitter.fire(h)}}translateBufferLineToString(e,t,i=0,s){let r=this.lines.get(e);return r?r.translateToString(t,i,s):""}getWrappedRangeForLine(e){let t=e,i=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;i+1<this.lines.length&&this.lines.get(i+1).isWrapped;)i++;return{first:t,last:i}}setupTabStops(e){for(null!=e?this.tabs[e]||(e=this.prevStop(e)):(this.tabs={},e=0);e<this._cols;e+=this._optionsService.rawOptions.tabStopWidth)this.tabs[e]=!0}prevStop(e){for(null==e&&(e=this.x);!this.tabs[--e]&&e>0;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(null==e&&(e=this.x);!this.tabs[++e]&&e<this._cols;);return e>=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t<this.markers.length;t++)this.markers[t].line===e&&(this.markers[t].dispose(),this.markers.splice(t--,1));this._isClearing=!1}clearAllMarkers(){this._isClearing=!0;for(let e=0;e<this.markers.length;e++)this.markers[e].dispose();this.markers.length=0,this._isClearing=!1}addMarker(e){let t=new Hh(e);return this.markers.push(t),t.register(this.lines.onTrim(e=>{t.line-=e,t.line<0&&t.dispose()})),t.register(this.lines.onInsert(e=>{t.line>=e.index&&(t.line+=e.amount)})),t.register(this.lines.onDelete(e=>{t.line>=e.index&&t.line<e.index+e.amount&&t.dispose(),t.line>e.index&&(t.line-=e.amount)})),t.register(t.onDispose(()=>this._removeMarker(t))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}},Vh=class extends qo{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new da),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this._register(this._optionsService.onSpecificOptionChange("scrollback",()=>this.resize(this._bufferService.cols,this._bufferService.rows))),this._register(this._optionsService.onSpecificOptionChange("tabStopWidth",()=>this.setupTabStops()))}reset(){this._normal=new Uh(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new Uh(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e,t){this._normal.resize(e,t),this._alt.resize(e,t),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}},qh=class extends qo{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new da),this.onResize=this._onResize.event,this._onScroll=this._register(new da),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,2),this.rows=Math.max(e.rawOptions.rows||0,1),this.buffers=this._register(new Vh(e,this)),this._register(this.buffers.onBufferActivate(e=>{this._onScroll.fire(e.activeBuffer.ydisp)}))}get buffer(){return this.buffers.active}resize(e,t){let i=this.cols!==e,s=this.rows!==t;this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t,colsChanged:i,rowsChanged:s})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){let i,s=this.buffer;i=this._cachedBlankLine,(!i||i.length!==this.cols||i.getFg(0)!==e.fg||i.getBg(0)!==e.bg)&&(i=s.getBlankLine(e,t),this._cachedBlankLine=i),i.isWrapped=t;let r=s.ybase+s.scrollTop,n=s.ybase+s.scrollBottom;if(0===s.scrollTop){let e=s.lines.isFull;n===s.lines.length-1?e?s.lines.recycle().copyFrom(i):s.lines.push(i.clone()):s.lines.splice(n+1,0,i.clone()),e?this.isUserScrolling&&(s.ydisp=Math.max(s.ydisp-1,0)):(s.ybase++,this.isUserScrolling||s.ydisp++)}else{let e=n-r+1;s.lines.shiftElements(r+1,e-1,-1),s.lines.set(n,i.clone())}this.isUserScrolling||(s.ydisp=s.ybase),this._onScroll.fire(s.ydisp)}scrollLines(e,t){let i=this.buffer;if(e<0){if(0===i.ydisp)return;this.isUserScrolling=!0}else e+i.ydisp>=i.ybase&&(this.isUserScrolling=!1);let s=i.ydisp;i.ydisp=Math.max(Math.min(i.ydisp+e,i.ybase),0),s!==i.ydisp&&(t||this._onScroll.fire(i.ydisp))}};qh=Wn([Fn(0,vo)],qh);var Yh={cols:80,rows:24,cursorBlink:!1,cursorStyle:"block",cursorWidth:1,cursorInactiveStyle:"outline",customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:"alt",fastScrollSensitivity:5,fontFamily:"monospace",fontSize:15,fontWeight:"normal",fontWeightBold:"bold",ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:"info",logger:null,scrollback:1e3,scrollOnEraseInDisplay:!1,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},reflowCursorLine:!1,rescaleOverlappingGlyphs:!1,rightClickSelectsWord:Zc,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRuler:{}},Xh=["normal","bold","100","200","300","400","500","600","700","800","900"],Gh=class extends qo{constructor(e){super(),this._onOptionChange=this._register(new da),this.onOptionChange=this._onOptionChange.event;let t={...Yh};for(let i in e)if(i in t)try{let s=e[i];t[i]=this._sanitizeAndValidateOption(i,s)}catch(Nl){console.error(Nl)}this.rawOptions=t,this.options={...t},this._setupOptions(),this._register(Ko(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(e,t){return this.onOptionChange(i=>{i===e&&t(this.rawOptions[e])})}onMultipleOptionChange(e,t){return this.onOptionChange(i=>{-1!==e.indexOf(i)&&t()})}_setupOptions(){let e=e=>{if(!(e in Yh))throw new Error(`No option with key "${e}"`);return this.rawOptions[e]},t=(e,t)=>{if(!(e in Yh))throw new Error(`No option with key "${e}"`);t=this._sanitizeAndValidateOption(e,t),this.rawOptions[e]!==t&&(this.rawOptions[e]=t,this._onOptionChange.fire(e))};for(let i in this.rawOptions){let s={get:e.bind(this,i),set:t.bind(this,i)};Object.defineProperty(this.options,i,s)}}_sanitizeAndValidateOption(e,t){switch(e){case"cursorStyle":if(t||(t=Yh[e]),"block"!==(i=t)&&"underline"!==i&&"bar"!==i)throw new Error(`"${t}" is not a valid value for ${e}`);break;case"wordSeparator":t||(t=Yh[e]);break;case"fontWeight":case"fontWeightBold":if("number"==typeof t&&1<=t&&t<=1e3)break;t=Xh.includes(t)?t:Yh[e];break;case"cursorWidth":t=Math.floor(t);case"lineHeight":case"tabStopWidth":if(t<1)throw new Error(`${e} cannot be less than 1, value: ${t}`);break;case"minimumContrastRatio":t=Math.max(1,Math.min(21,Math.round(10*t)/10));break;case"scrollback":if((t=Math.min(t,4294967295))<0)throw new Error(`${e} cannot be less than 0, value: ${t}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(t<=0)throw new Error(`${e} cannot be less than or equal to 0, value: ${t}`);break;case"rows":case"cols":if(!t&&0!==t)throw new Error(`${e} must be numeric, value: ${t}`);break;case"windowsPty":t=t??{}}var i;return t}};function Zh(e,t=5){if("object"!=typeof e)return e;let i=Array.isArray(e)?[]:{};for(let s in e)i[s]=t<=1?e[s]:e[s]&&Zh(e[s],t-1);return i}var Jh=Object.freeze({insertMode:!1}),Qh=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),ed=class extends qo{constructor(e,t,i){super(),this._bufferService=e,this._logService=t,this._optionsService=i,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new da),this.onData=this._onData.event,this._onUserInput=this._register(new da),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new da),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new da),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=Zh(Jh),this.decPrivateModes=Zh(Qh)}reset(){this.modes=Zh(Jh),this.decPrivateModes=Zh(Qh)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;let i=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&i.ybase!==i.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`),this._logService.trace("sending data (codes)",()=>e.split("").map(e=>e.charCodeAt(0))),this._onData.fire(e)}triggerBinaryEvent(e){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${e}"`),this._logService.trace("sending binary (codes)",()=>e.split("").map(e=>e.charCodeAt(0))),this._onBinary.fire(e))}};ed=Wn([Fn(0,uo),Fn(1,go),Fn(2,vo)],ed);var td={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:e=>4!==e.button&&1===e.action&&(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)},VT200:{events:19,restrict:e=>32!==e.action},DRAG:{events:23,restrict:e=>!(32===e.action&&3===e.button)},ANY:{events:31,restrict:e=>!0}};function id(e,t){let i=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return 4===e.button?(i|=64,i|=e.action):(i|=3&e.button,4&e.button&&(i|=64),8&e.button&&(i|=128),32===e.action?i|=32:0===e.action&&!t&&(i|=3)),i}var sd=String.fromCharCode,rd={DEFAULT:e=>{let t=[id(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?"":`${sd(t[0])}${sd(t[1])}${sd(t[2])}`},SGR:e=>{let t=0===e.action&&4!==e.button?"m":"M";return`[<${id(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=0===e.action&&4!==e.button?"m":"M";return`[<${id(e,!0)};${e.x};${e.y}${t}`}},nd=class extends qo{constructor(e,t,i){super(),this._bufferService=e,this._coreService=t,this._optionsService=i,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new da),this.onProtocolChange=this._onProtocolChange.event;for(let s of Object.keys(td))this.addProtocol(s,td[s]);for(let s of Object.keys(rd))this.addEncoding(s,rd[s]);this.reset()}addProtocol(e,t){this._protocols[e]=t}addEncoding(e,t){this._encodings[e]=t}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return 0!==this._protocols[this._activeProtocol].events}set activeProtocol(e){if(!this._protocols[e])throw new Error(`unknown protocol "${e}"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw new Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(e,t,i){if(0===e.deltaY||e.shiftKey||void 0===t||void 0===i)return 0;let s=t/i,r=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(r/=s+0,Math.abs(e.deltaY)<50&&(r*=.3),this._wheelPartialScroll+=r,r=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(r*=this._bufferService.rows),r}_applyScrollModifier(e,t){return t.altKey||t.ctrlKey||t.shiftKey?e*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:e*this._optionsService.rawOptions.scrollSensitivity}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows||4===e.button&&32===e.action||3===e.button&&32!==e.action||4!==e.button&&(2===e.action||3===e.action)||(e.col++,e.row++,32===e.action&&this._lastEvent&&this._equalEvents(this._lastEvent,e,"SGR_PIXELS"===this._activeEncoding))||!this._protocols[this._activeProtocol].restrict(e))return!1;let t=this._encodings[this._activeEncoding](e);return t&&("DEFAULT"===this._activeEncoding?this._coreService.triggerBinaryEvent(t):this._coreService.triggerDataEvent(t,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(1&e),up:!!(2&e),drag:!!(4&e),move:!!(8&e),wheel:!!(16&e)}}_equalEvents(e,t,i){if(i){if(e.x!==t.x||e.y!==t.y)return!1}else if(e.col!==t.col||e.row!==t.row)return!1;return!(e.button!==t.button||e.action!==t.action||e.ctrl!==t.ctrl||e.alt!==t.alt||e.shift!==t.shift)}};nd=Wn([Fn(0,uo),Fn(1,po),Fn(2,vo)],nd);var od,ad=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],ld=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]];var cd=class{constructor(){if(this.version="6",!od){(od=new Uint8Array(65536)).fill(1),od[0]=0,od.fill(0,1,32),od.fill(0,127,160),od.fill(2,4352,4448),od[9001]=2,od[9002]=2,od.fill(2,11904,42192),od[12351]=1,od.fill(2,44032,55204),od.fill(2,63744,64256),od.fill(2,65040,65050),od.fill(2,65072,65136),od.fill(2,65280,65377),od.fill(2,65504,65511);for(let e=0;e<ad.length;++e)od.fill(0,ad[e][0],ad[e][1]+1)}}wcwidth(e){return e<32?0:e<127?1:e<65536?od[e]:function(e,t){let i,s=0,r=t.length-1;if(e<t[0][0]||e>t[r][1])return!1;for(;r>=s;)if(i=s+r>>1,e>t[i][1])s=i+1;else{if(!(e<t[i][0]))return!0;r=i-1}return!1}(e,ld)?0:e>=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let i=this.wcwidth(e),s=0===i&&0!==t;if(s){let e=hd.extractWidth(t);0===e?s=!1:e>i&&(i=e)}return hd.createPropertyValue(0,i,s)}},hd=class e{constructor(){this._providers=Object.create(null),this._active="",this._onChange=new da,this.onChange=this._onChange.event;let e=new cd;this.register(e),this._active=e.version,this._activeProvider=e}static extractShouldJoin(e){return!!(1&e)}static extractWidth(e){return e>>1&3}static extractCharKind(e){return e>>3}static createPropertyValue(e,t,i=!1){return(16777215&e)<<3|(3&t)<<1|(i?1:0)}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(e){if(!this._providers[e])throw new Error(`unknown Unicode version "${e}"`);this._active=e,this._activeProvider=this._providers[e],this._onChange.fire(e)}register(e){this._providers[e.version]=e}wcwidth(e){return this._activeProvider.wcwidth(e)}getStringCellWidth(t){let i=0,s=0,r=t.length;for(let n=0;n<r;++n){let o=t.charCodeAt(n);if(55296<=o&&o<=56319){if(++n>=r)return i+this.wcwidth(o);let e=t.charCodeAt(n);56320<=e&&e<=57343?o=1024*(o-55296)+e-56320+65536:i+=this.wcwidth(e)}let a=this.charProperties(o,s),l=e.extractWidth(a);e.extractShouldJoin(a)&&(l-=e.extractWidth(s)),i+=l,s=a}return i}charProperties(e,t){return this._activeProvider.charProperties(e,t)}},dd=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(e){this.glevel=e,this.charset=this._charsets[e]}setgCharset(e,t){this._charsets[e]=t,this.glevel===e&&(this.charset=t)}};function ud(e){var t;let i=null==(t=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1))?void 0:t.get(e.cols-1),s=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);s&&i&&(s.isWrapped=0!==i[3]&&32!==i[3])}var fd=2147483647,pd=class e{constructor(e=32,t=32){if(this.maxLength=e,this.maxSubParamsLength=t,t>256)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(e),this.length=0,this._subParams=new Int32Array(t),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(e),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}static fromArray(t){let i=new e;if(!t.length)return i;for(let e=Array.isArray(t[0])?1:0;e<t.length;++e){let s=t[e];if(Array.isArray(s))for(let e=0;e<s.length;++e)i.addSubParam(s[e]);else i.addParam(s)}return i}clone(){let t=new e(this.maxLength,this.maxSubParamsLength);return t.params.set(this.params),t.length=this.length,t._subParams.set(this._subParams),t._subParamsLength=this._subParamsLength,t._subParamsIdx.set(this._subParamsIdx),t._rejectDigits=this._rejectDigits,t._rejectSubDigits=this._rejectSubDigits,t._digitIsSub=this._digitIsSub,t}toArray(){let e=[];for(let t=0;t<this.length;++t){e.push(this.params[t]);let i=this._subParamsIdx[t]>>8,s=255&this._subParamsIdx[t];s-i>0&&e.push(Array.prototype.slice.call(this._subParams,i,s))}return e}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(e){if(this._digitIsSub=!1,this.length>=this.maxLength)this._rejectDigits=!0;else{if(e<-1)throw new Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=e>fd?fd:e}}addSubParam(e){if(this._digitIsSub=!0,this.length){if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength)return void(this._rejectSubDigits=!0);if(e<-1)throw new Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=e>fd?fd:e,this._subParamsIdx[this.length-1]++}}hasSubParams(e){return(255&this._subParamsIdx[e])-(this._subParamsIdx[e]>>8)>0}getSubParams(e){let t=this._subParamsIdx[e]>>8,i=255&this._subParamsIdx[e];return i-t>0?this._subParams.subarray(t,i):null}getSubParamsAll(){let e={};for(let t=0;t<this.length;++t){let i=this._subParamsIdx[t]>>8,s=255&this._subParamsIdx[t];s-i>0&&(e[t]=this._subParams.slice(i,s))}return e}addDigit(e){let t;if(this._rejectDigits||!(t=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let i=this._digitIsSub?this._subParams:this.params,s=i[t-1];i[t-1]=~s?Math.min(10*s+e,fd):e}},md=[],_d=class{constructor(){this._state=0,this._active=md,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(e,t){void 0===this._handlers[e]&&(this._handlers[e]=[]);let i=this._handlers[e];return i.push(t),{dispose:()=>{let e=i.indexOf(t);-1!==e&&i.splice(e,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=md}reset(){if(2===this._state)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].end(!1);this._stack.paused=!1,this._active=md,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||md,this._active.length)for(let e=this._active.length-1;e>=0;e--)this._active[e].start();else this._handlerFb(this._id,"START")}_put(e,t,i){if(this._active.length)for(let s=this._active.length-1;s>=0;s--)this._active[s].put(e,t,i);else this._handlerFb(this._id,"PUT",eo(e,t,i))}start(){this.reset(),this._state=1}put(e,t,i){if(3!==this._state){if(1===this._state)for(;t<i;){let i=e[t++];if(59===i){this._state=2,this._start();break}if(i<48||57<i)return void(this._state=3);-1===this._id&&(this._id=0),this._id=10*this._id+i-48}2===this._state&&i-t>0&&this._put(e,t,i)}}end(e,t=!0){if(0!==this._state){if(3!==this._state)if(1===this._state&&this._start(),this._active.length){let i=!1,s=this._active.length-1,r=!1;if(this._stack.paused&&(s=this._stack.loopPosition-1,i=t,r=this._stack.fallThrough,this._stack.paused=!1),!r&&!1===i){for(;s>=0&&(i=this._active[s].end(e),!0!==i);s--)if(i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!1,i;s--}for(;s>=0;s--)if(i=this._active[s].end(!1),i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!0,i}else this._handlerFb(this._id,"END",e);this._active=md,this._id=-1,this._state=0}}},gd=class{constructor(e){this._handler=e,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=eo(e,t,i),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}end(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data),t instanceof Promise))return t.then(e=>(this._data="",this._hitLimit=!1,e));return this._data="",this._hitLimit=!1,t}},vd=[],yd=class{constructor(){this._handlers=Object.create(null),this._active=vd,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=vd}registerHandler(e,t){void 0===this._handlers[e]&&(this._handlers[e]=[]);let i=this._handlers[e];return i.push(t),{dispose:()=>{let e=i.indexOf(t);-1!==e&&i.splice(e,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}reset(){if(this._active.length)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].unhook(!1);this._stack.paused=!1,this._active=vd,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||vd,this._active.length)for(let i=this._active.length-1;i>=0;i--)this._active[i].hook(t);else this._handlerFb(this._ident,"HOOK",t)}put(e,t,i){if(this._active.length)for(let s=this._active.length-1;s>=0;s--)this._active[s].put(e,t,i);else this._handlerFb(this._ident,"PUT",eo(e,t,i))}unhook(e,t=!0){if(this._active.length){let i=!1,s=this._active.length-1,r=!1;if(this._stack.paused&&(s=this._stack.loopPosition-1,i=t,r=this._stack.fallThrough,this._stack.paused=!1),!r&&!1===i){for(;s>=0&&(i=this._active[s].unhook(e),!0!==i);s--)if(i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!1,i;s--}for(;s>=0;s--)if(i=this._active[s].unhook(!1),i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!0,i}else this._handlerFb(this._ident,"UNHOOK",e);this._active=vd,this._ident=0}},xd=new pd;xd.addParam(0);var bd=class{constructor(e){this._handler=e,this._data="",this._params=xd,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():xd,this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=eo(e,t,i),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}unhook(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data,this._params),t instanceof Promise))return t.then(e=>(this._params=xd,this._data="",this._hitLimit=!1,e));return this._params=xd,this._data="",this._hitLimit=!1,t}},wd=class{constructor(e){this.table=new Uint8Array(e)}setDefault(e,t){this.table.fill(e<<4|t)}add(e,t,i,s){this.table[t<<8|e]=i<<4|s}addMany(e,t,i,s){for(let r=0;r<e.length;r++)this.table[t<<8|e[r]]=i<<4|s}},Sd=160,Cd=function(){let e=new wd(4095),t=Array.apply(null,Array(256)).map((e,t)=>t),i=(e,i)=>t.slice(e,i),s=i(32,127),r=i(0,24);r.push(25),r.push.apply(r,i(28,32));let n,o=i(0,14);for(n in e.setDefault(1,0),e.addMany(s,0,2,0),o)e.addMany([24,26,153,154],n,3,0),e.addMany(i(128,144),n,3,0),e.addMany(i(144,152),n,3,0),e.add(156,n,0,0),e.add(27,n,11,1),e.add(157,n,4,8),e.addMany([152,158,159],n,0,7),e.add(155,n,11,3),e.add(144,n,11,9);return e.addMany(r,0,3,0),e.addMany(r,1,3,1),e.add(127,1,0,1),e.addMany(r,8,0,8),e.addMany(r,3,3,3),e.add(127,3,0,3),e.addMany(r,4,3,4),e.add(127,4,0,4),e.addMany(r,6,3,6),e.addMany(r,5,3,5),e.add(127,5,0,5),e.addMany(r,2,3,2),e.add(127,2,0,2),e.add(93,1,4,8),e.addMany(s,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(i(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(s,7,0,7),e.addMany(r,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(i(64,127),3,7,0),e.addMany(i(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(i(48,60),4,8,4),e.addMany(i(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(i(32,64),6,0,6),e.add(127,6,0,6),e.addMany(i(64,127),6,0,0),e.addMany(i(32,48),3,9,5),e.addMany(i(32,48),5,9,5),e.addMany(i(48,64),5,0,6),e.addMany(i(64,127),5,7,0),e.addMany(i(32,48),4,9,5),e.addMany(i(32,48),1,9,2),e.addMany(i(32,48),2,9,2),e.addMany(i(48,127),2,10,0),e.addMany(i(48,80),1,10,0),e.addMany(i(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(i(96,127),1,10,0),e.add(80,1,11,9),e.addMany(r,9,0,9),e.add(127,9,0,9),e.addMany(i(28,32),9,0,9),e.addMany(i(32,48),9,9,12),e.addMany(i(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(r,11,0,11),e.addMany(i(32,128),11,0,11),e.addMany(i(28,32),11,0,11),e.addMany(r,10,0,10),e.add(127,10,0,10),e.addMany(i(28,32),10,0,10),e.addMany(i(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(i(32,48),10,9,12),e.addMany(r,12,0,12),e.add(127,12,0,12),e.addMany(i(28,32),12,0,12),e.addMany(i(32,48),12,9,12),e.addMany(i(48,64),12,0,11),e.addMany(i(64,127),12,12,13),e.addMany(i(64,127),10,12,13),e.addMany(i(64,127),9,12,13),e.addMany(r,13,13,13),e.addMany(s,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(Sd,0,2,0),e.add(Sd,8,5,8),e.add(Sd,6,0,6),e.add(Sd,11,0,11),e.add(Sd,13,13,13),e}(),kd=class extends qo{constructor(e=Cd){super(),this._transitions=e,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new pd,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(e,t,i)=>{},this._executeHandlerFb=e=>{},this._csiHandlerFb=(e,t)=>{},this._escHandlerFb=e=>{},this._errorHandlerFb=e=>e,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register(Ko(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new _d),this._dcsParser=this._register(new yd),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},()=>!0)}_identifier(e,t=[64,126]){let i=0;if(e.prefix){if(e.prefix.length>1)throw new Error("only one byte as prefix supported");if(i=e.prefix.charCodeAt(0),i&&60>i||i>63)throw new Error("prefix must be in range 0x3c .. 0x3f")}if(e.intermediates){if(e.intermediates.length>2)throw new Error("only two bytes as intermediates are supported");for(let t=0;t<e.intermediates.length;++t){let s=e.intermediates.charCodeAt(t);if(32>s||s>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");i<<=8,i|=s}}if(1!==e.final.length)throw new Error("final must be a single byte");let s=e.final.charCodeAt(0);if(t[0]>s||s>t[1])throw new Error(`final must be in range ${t[0]} .. ${t[1]}`);return i<<=8,i|=s,i}identToString(e){let t=[];for(;e;)t.push(String.fromCharCode(255&e)),e>>=8;return t.reverse().join("")}setPrintHandler(e){this._printHandler=e}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e,t){let i=this._identifier(e,[48,126]);void 0===this._escHandlers[i]&&(this._escHandlers[i]=[]);let s=this._escHandlers[i];return s.push(t),{dispose:()=>{let e=s.indexOf(t);-1!==e&&s.splice(e,1)}}}clearEscHandler(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]}setEscHandlerFallback(e){this._escHandlerFb=e}setExecuteHandler(e,t){this._executeHandlers[e.charCodeAt(0)]=t}clearExecuteHandler(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]}setExecuteHandlerFallback(e){this._executeHandlerFb=e}registerCsiHandler(e,t){let i=this._identifier(e);void 0===this._csiHandlers[i]&&(this._csiHandlers[i]=[]);let s=this._csiHandlers[i];return s.push(t),{dispose:()=>{let e=s.indexOf(t);-1!==e&&s.splice(e,1)}}}clearCsiHandler(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]}setCsiHandlerFallback(e){this._csiHandlerFb=e}registerDcsHandler(e,t){return this._dcsParser.registerHandler(this._identifier(e),t)}clearDcsHandler(e){this._dcsParser.clearHandler(this._identifier(e))}setDcsHandlerFallback(e){this._dcsParser.setHandlerFallback(e)}registerOscHandler(e,t){return this._oscParser.registerHandler(e,t)}clearOscHandler(e){this._oscParser.clearHandler(e)}setOscHandlerFallback(e){this._oscParser.setHandlerFallback(e)}setErrorHandler(e){this._errorHandler=e}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,0!==this._parseStack.state&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(e,t,i,s,r){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=i,this._parseStack.transition=s,this._parseStack.chunkPos=r}parse(e,t,i){let s,r=0,n=0,o=0;if(this._parseStack.state)if(2===this._parseStack.state)this._parseStack.state=0,o=this._parseStack.chunkPos+1;else{if(void 0===i||1===this._parseStack.state)throw this._parseStack.state=1,new Error("improper continuation due to previous async handler, giving up parsing");let t=this._parseStack.handlers,n=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(!1===i&&n>-1)for(;n>=0&&(s=t[n](this._params),!0!==s);n--)if(s instanceof Promise)return this._parseStack.handlerPos=n,s;this._parseStack.handlers=[];break;case 4:if(!1===i&&n>-1)for(;n>=0&&(s=t[n](),!0!==s);n--)if(s instanceof Promise)return this._parseStack.handlerPos=n,s;this._parseStack.handlers=[];break;case 6:if(r=e[this._parseStack.chunkPos],s=this._dcsParser.unhook(24!==r&&26!==r,i),s)return s;27===r&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(r=e[this._parseStack.chunkPos],s=this._oscParser.end(24!==r&&26!==r,i),s)return s;27===r&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0}this._parseStack.state=0,o=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=15&this._parseStack.transition}for(let a=o;a<t;++a){switch(r=e[a],n=this._transitions.table[this.currentState<<8|(r<160?r:Sd)],n>>4){case 2:for(let s=a+1;;++s){if(s>=t||(r=e[s])<32||r>126&&r<Sd){this._printHandler(e,a,s),a=s-1;break}if(++s>=t||(r=e[s])<32||r>126&&r<Sd){this._printHandler(e,a,s),a=s-1;break}if(++s>=t||(r=e[s])<32||r>126&&r<Sd){this._printHandler(e,a,s),a=s-1;break}if(++s>=t||(r=e[s])<32||r>126&&r<Sd){this._printHandler(e,a,s),a=s-1;break}}break;case 3:this._executeHandlers[r]?this._executeHandlers[r]():this._executeHandlerFb(r),this.precedingJoinState=0;break;case 0:break;case 1:if(this._errorHandler({position:a,code:r,currentState:this.currentState,collect:this._collect,params:this._params,abort:!1}).abort)return;break;case 7:let i=this._csiHandlers[this._collect<<8|r],o=i?i.length-1:-1;for(;o>=0&&(s=i[o](this._params),!0!==s);o--)if(s instanceof Promise)return this._preserveStack(3,i,o,n,a),s;o<0&&this._csiHandlerFb(this._collect<<8|r,this._params),this.precedingJoinState=0;break;case 8:do{switch(r){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(r-48)}}while(++a<t&&(r=e[a])>47&&r<60);a--;break;case 9:this._collect<<=8,this._collect|=r;break;case 10:let l=this._escHandlers[this._collect<<8|r],c=l?l.length-1:-1;for(;c>=0&&(s=l[c](),!0!==s);c--)if(s instanceof Promise)return this._preserveStack(4,l,c,n,a),s;c<0&&this._escHandlerFb(this._collect<<8|r),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|r,this._params);break;case 13:for(let s=a+1;;++s)if(s>=t||24===(r=e[s])||26===r||27===r||r>127&&r<Sd){this._dcsParser.put(e,a,s),a=s-1;break}break;case 14:if(s=this._dcsParser.unhook(24!==r&&26!==r),s)return this._preserveStack(6,[],0,n,a),s;27===r&&(n|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break;case 4:this._oscParser.start();break;case 5:for(let s=a+1;;s++)if(s>=t||(r=e[s])<32||r>127&&r<Sd){this._oscParser.put(e,a,s),a=s-1;break}break;case 6:if(s=this._oscParser.end(24!==r&&26!==r),s)return this._preserveStack(5,[],0,n,a),s;27===r&&(n|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0}this.currentState=15&n}}},Ed=/^([\da-f])\/([\da-f])\/([\da-f])$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$/,Nd=/^[\da-f]+$/;function Md(e){if(!e)return;let t=e.toLowerCase();if(0===t.indexOf("rgb:")){t=t.slice(4);let e=Ed.exec(t);if(e){let t=e[1]?15:e[4]?255:e[7]?4095:65535;return[Math.round(parseInt(e[1]||e[4]||e[7]||e[10],16)/t*255),Math.round(parseInt(e[2]||e[5]||e[8]||e[11],16)/t*255),Math.round(parseInt(e[3]||e[6]||e[9]||e[12],16)/t*255)]}}else if(0===t.indexOf("#")&&(t=t.slice(1),Nd.exec(t)&&[3,6,9,12].includes(t.length))){let e=t.length/3,i=[0,0,0];for(let s=0;s<3;++s){let r=parseInt(t.slice(e*s,e*s+e),16);i[s]=1===e?r<<4:2===e?r:3===e?r>>4:r>>8}return i}}function jd(e,t){let i=e.toString(16),s=i.length<2?"0"+i:i;switch(t){case 4:return i[0];case 8:return s;case 12:return(s+s).slice(0,3);default:return s+s}}function Dd(e,t=16){let[i,s,r]=e;return`rgb:${jd(i,t)}/${jd(s,t)}/${jd(r,t)}`}var Rd={"(":0,")":1,"*":2,"+":3,"-":1,".":2},Pd=131072;function Ld(e,t){if(e>24)return t.setWinLines||!1;switch(e){case 1:return!!t.restoreWin;case 2:return!!t.minimizeWin;case 3:return!!t.setWinPosition;case 4:return!!t.setWinSizePixels;case 5:return!!t.raiseWin;case 6:return!!t.lowerWin;case 7:return!!t.refreshWin;case 8:return!!t.setWinSizeChars;case 9:return!!t.maximizeWin;case 10:return!!t.fullscreenWin;case 11:return!!t.getWinState;case 13:return!!t.getWinPosition;case 14:return!!t.getWinSizePixels;case 15:return!!t.getScreenSizePixels;case 16:return!!t.getCellSizePixels;case 18:return!!t.getWinSizeChars;case 19:return!!t.getScreenSizeChars;case 20:return!!t.getIconTitle;case 21:return!!t.getWinTitle;case 22:return!!t.pushTitle;case 23:return!!t.popTitle;case 24:return!!t.setWinLines}return!1}var Id=0,Td=class extends qo{constructor(e,t,i,s,r,n,o,a,l=new kd){super(),this._bufferService=e,this._charsetService=t,this._coreService=i,this._logService=s,this._optionsService=r,this._oscLinkService=n,this._coreMouseService=o,this._unicodeService=a,this._parser=l,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new to,this._utf8Decoder=new io,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=Th.clone(),this._eraseAttrDataInternal=Th.clone(),this._onRequestBell=this._register(new da),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new da),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new da),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new da),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new da),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new da),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new da),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new da),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new da),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new da),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new da),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new da),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new da),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this._register(this._parser),this._dirtyRowTracker=new Bd(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(e=>this._activeBuffer=e.activeBuffer)),this._parser.setCsiHandlerFallback((e,t)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(e),params:t.toArray()})}),this._parser.setEscHandlerFallback(e=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(e)})}),this._parser.setExecuteHandlerFallback(e=>{this._logService.debug("Unknown EXECUTE code: ",{code:e})}),this._parser.setOscHandlerFallback((e,t,i)=>{this._logService.debug("Unknown OSC code: ",{identifier:e,action:t,data:i})}),this._parser.setDcsHandlerFallback((e,t,i)=>{"HOOK"===t&&(i=i.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(e),action:t,payload:i})}),this._parser.setPrintHandler((e,t,i)=>this.print(e,t,i)),this._parser.registerCsiHandler({final:"@"},e=>this.insertChars(e)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},e=>this.scrollLeft(e)),this._parser.registerCsiHandler({final:"A"},e=>this.cursorUp(e)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},e=>this.scrollRight(e)),this._parser.registerCsiHandler({final:"B"},e=>this.cursorDown(e)),this._parser.registerCsiHandler({final:"C"},e=>this.cursorForward(e)),this._parser.registerCsiHandler({final:"D"},e=>this.cursorBackward(e)),this._parser.registerCsiHandler({final:"E"},e=>this.cursorNextLine(e)),this._parser.registerCsiHandler({final:"F"},e=>this.cursorPrecedingLine(e)),this._parser.registerCsiHandler({final:"G"},e=>this.cursorCharAbsolute(e)),this._parser.registerCsiHandler({final:"H"},e=>this.cursorPosition(e)),this._parser.registerCsiHandler({final:"I"},e=>this.cursorForwardTab(e)),this._parser.registerCsiHandler({final:"J"},e=>this.eraseInDisplay(e,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},e=>this.eraseInDisplay(e,!0)),this._parser.registerCsiHandler({final:"K"},e=>this.eraseInLine(e,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},e=>this.eraseInLine(e,!0)),this._parser.registerCsiHandler({final:"L"},e=>this.insertLines(e)),this._parser.registerCsiHandler({final:"M"},e=>this.deleteLines(e)),this._parser.registerCsiHandler({final:"P"},e=>this.deleteChars(e)),this._parser.registerCsiHandler({final:"S"},e=>this.scrollUp(e)),this._parser.registerCsiHandler({final:"T"},e=>this.scrollDown(e)),this._parser.registerCsiHandler({final:"X"},e=>this.eraseChars(e)),this._parser.registerCsiHandler({final:"Z"},e=>this.cursorBackwardTab(e)),this._parser.registerCsiHandler({final:"`"},e=>this.charPosAbsolute(e)),this._parser.registerCsiHandler({final:"a"},e=>this.hPositionRelative(e)),this._parser.registerCsiHandler({final:"b"},e=>this.repeatPrecedingCharacter(e)),this._parser.registerCsiHandler({final:"c"},e=>this.sendDeviceAttributesPrimary(e)),this._parser.registerCsiHandler({prefix:">",final:"c"},e=>this.sendDeviceAttributesSecondary(e)),this._parser.registerCsiHandler({final:"d"},e=>this.linePosAbsolute(e)),this._parser.registerCsiHandler({final:"e"},e=>this.vPositionRelative(e)),this._parser.registerCsiHandler({final:"f"},e=>this.hVPosition(e)),this._parser.registerCsiHandler({final:"g"},e=>this.tabClear(e)),this._parser.registerCsiHandler({final:"h"},e=>this.setMode(e)),this._parser.registerCsiHandler({prefix:"?",final:"h"},e=>this.setModePrivate(e)),this._parser.registerCsiHandler({final:"l"},e=>this.resetMode(e)),this._parser.registerCsiHandler({prefix:"?",final:"l"},e=>this.resetModePrivate(e)),this._parser.registerCsiHandler({final:"m"},e=>this.charAttributes(e)),this._parser.registerCsiHandler({final:"n"},e=>this.deviceStatus(e)),this._parser.registerCsiHandler({prefix:"?",final:"n"},e=>this.deviceStatusPrivate(e)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},e=>this.softReset(e)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},e=>this.setCursorStyle(e)),this._parser.registerCsiHandler({final:"r"},e=>this.setScrollRegion(e)),this._parser.registerCsiHandler({final:"s"},e=>this.saveCursor(e)),this._parser.registerCsiHandler({final:"t"},e=>this.windowOptions(e)),this._parser.registerCsiHandler({final:"u"},e=>this.restoreCursor(e)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},e=>this.insertColumns(e)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},e=>this.deleteColumns(e)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},e=>this.selectProtected(e)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},e=>this.requestMode(e,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},e=>this.requestMode(e,!1)),this._parser.setExecuteHandler(Gl.BEL,()=>this.bell()),this._parser.setExecuteHandler(Gl.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(Gl.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(Gl.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(Gl.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(Gl.BS,()=>this.backspace()),this._parser.setExecuteHandler(Gl.HT,()=>this.tab()),this._parser.setExecuteHandler(Gl.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(Gl.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(Jl.IND,()=>this.index()),this._parser.setExecuteHandler(Jl.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(Jl.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new gd(e=>(this.setTitle(e),this.setIconName(e),!0))),this._parser.registerOscHandler(1,new gd(e=>this.setIconName(e))),this._parser.registerOscHandler(2,new gd(e=>this.setTitle(e))),this._parser.registerOscHandler(4,new gd(e=>this.setOrReportIndexedColor(e))),this._parser.registerOscHandler(8,new gd(e=>this.setHyperlink(e))),this._parser.registerOscHandler(10,new gd(e=>this.setOrReportFgColor(e))),this._parser.registerOscHandler(11,new gd(e=>this.setOrReportBgColor(e))),this._parser.registerOscHandler(12,new gd(e=>this.setOrReportCursorColor(e))),this._parser.registerOscHandler(104,new gd(e=>this.restoreIndexedColor(e))),this._parser.registerOscHandler(110,new gd(e=>this.restoreFgColor(e))),this._parser.registerOscHandler(111,new gd(e=>this.restoreBgColor(e))),this._parser.registerOscHandler(112,new gd(e=>this.restoreCursorColor(e))),this._parser.registerEscHandler({final:"7"},()=>this.saveCursor()),this._parser.registerEscHandler({final:"8"},()=>this.restoreCursor()),this._parser.registerEscHandler({final:"D"},()=>this.index()),this._parser.registerEscHandler({final:"E"},()=>this.nextLine()),this._parser.registerEscHandler({final:"H"},()=>this.tabSet()),this._parser.registerEscHandler({final:"M"},()=>this.reverseIndex()),this._parser.registerEscHandler({final:"="},()=>this.keypadApplicationMode()),this._parser.registerEscHandler({final:">"},()=>this.keypadNumericMode()),this._parser.registerEscHandler({final:"c"},()=>this.fullReset()),this._parser.registerEscHandler({final:"n"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"o"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"|"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"}"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"~"},()=>this.setgLevel(1)),this._parser.registerEscHandler({intermediates:"%",final:"@"},()=>this.selectDefaultCharset()),this._parser.registerEscHandler({intermediates:"%",final:"G"},()=>this.selectDefaultCharset());for(let c in Wh)this._parser.registerEscHandler({intermediates:"(",final:c},()=>this.selectCharset("("+c)),this._parser.registerEscHandler({intermediates:")",final:c},()=>this.selectCharset(")"+c)),this._parser.registerEscHandler({intermediates:"*",final:c},()=>this.selectCharset("*"+c)),this._parser.registerEscHandler({intermediates:"+",final:c},()=>this.selectCharset("+"+c)),this._parser.registerEscHandler({intermediates:"-",final:c},()=>this.selectCharset("-"+c)),this._parser.registerEscHandler({intermediates:".",final:c},()=>this.selectCharset("."+c)),this._parser.registerEscHandler({intermediates:"/",final:c},()=>this.selectCharset("/"+c));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(e=>(this._logService.error("Parsing error: ",e),e)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new bd((e,t)=>this.requestStatusString(e,t)))}getAttrData(){return this._curAttrData}_preserveStack(e,t,i,s){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=i,this._parseStack.position=s}_logSlowResolvingAsync(e){this._logService.logLevel<=3&&Promise.race([e,new Promise((e,t)=>setTimeout(()=>t("#SLOW_TIMEOUT"),5e3))]).catch(e=>{if("#SLOW_TIMEOUT"!==e)throw e;console.warn("async parser handler taking longer than 5000 ms")})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let i,s=this._activeBuffer.x,r=this._activeBuffer.y,n=0,o=this._parseStack.paused;if(o){if(i=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(i),i;s=this._parseStack.cursorStartX,r=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>Pd&&(n=this._parseStack.position+Pd)}if(this._logService.logLevel<=1&&this._logService.debug("parsing data "+("string"==typeof e?` "${e}"`:` "${Array.prototype.map.call(e,e=>String.fromCharCode(e)).join("")}"`)),0===this._logService.logLevel&&this._logService.trace("parsing data (codes)","string"==typeof e?e.split("").map(e=>e.charCodeAt(0)):e),this._parseBuffer.length<e.length&&this._parseBuffer.length<Pd&&(this._parseBuffer=new Uint32Array(Math.min(e.length,Pd))),o||this._dirtyRowTracker.clearRange(),e.length>Pd)for(let c=n;c<e.length;c+=Pd){let t=c+Pd<e.length?c+Pd:e.length,n="string"==typeof e?this._stringDecoder.decode(e.substring(c,t),this._parseBuffer):this._utf8Decoder.decode(e.subarray(c,t),this._parseBuffer);if(i=this._parser.parse(this._parseBuffer,n))return this._preserveStack(s,r,n,c),this._logSlowResolvingAsync(i),i}else if(!o){let t="string"==typeof e?this._stringDecoder.decode(e,this._parseBuffer):this._utf8Decoder.decode(e,this._parseBuffer);if(i=this._parser.parse(this._parseBuffer,t))return this._preserveStack(s,r,t,0),this._logSlowResolvingAsync(i),i}(this._activeBuffer.x!==s||this._activeBuffer.y!==r)&&this._onCursorMove.fire();let a=this._dirtyRowTracker.end+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp),l=this._dirtyRowTracker.start+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp);l<this._bufferService.rows&&this._onRequestRefreshRows.fire({start:Math.min(l,this._bufferService.rows-1),end:Math.min(a,this._bufferService.rows-1)})}print(e,t,i){let s,r,n=this._charsetService.charset,o=this._optionsService.rawOptions.screenReaderMode,a=this._bufferService.cols,l=this._coreService.decPrivateModes.wraparound,c=this._coreService.modes.insertMode,h=this._curAttrData,d=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&i-t>0&&2===d.getWidth(this._activeBuffer.x-1)&&d.setCellFromCodepoint(this._activeBuffer.x-1,0,1,h);let u=this._parser.precedingJoinState;for(let f=t;f<i;++f){if(s=e[f],s<127&&n){let e=n[String.fromCharCode(s)];e&&(s=e.charCodeAt(0))}let t=this._unicodeService.charProperties(s,u);r=hd.extractWidth(t);let i=hd.extractShouldJoin(t),p=i?hd.extractWidth(u):0;if(u=t,o&&this._onA11yChar.fire(Qn(s)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+r-p>a)if(l){let e=d,t=this._activeBuffer.x-p;for(this._activeBuffer.x=p,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),d=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),p>0&&d instanceof Oh&&d.copyCellsFrom(e,t,0,p,!1);t<a;)e.setCellFromCodepoint(t++,0,1,h)}else if(this._activeBuffer.x=a-1,2===r)continue;if(i&&this._activeBuffer.x){let e=d.getWidth(this._activeBuffer.x-1)?1:2;d.addCodepointToCell(this._activeBuffer.x-e,s,r);for(let t=r-p;--t>=0;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,h);continue}if(c&&(d.insertCells(this._activeBuffer.x,r-p,this._activeBuffer.getNullCell(h)),2===d.getWidth(a-1)&&d.setCellFromCodepoint(a-1,0,1,h)),d.setCellFromCodepoint(this._activeBuffer.x++,s,r,h),r>0)for(;--r;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,h)}this._parser.precedingJoinState=u,this._activeBuffer.x<a&&i-t>0&&0===d.getWidth(this._activeBuffer.x)&&!d.hasContent(this._activeBuffer.x)&&d.setCellFromCodepoint(this._activeBuffer.x,0,1,h),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return"t"!==e.final||e.prefix||e.intermediates?this._parser.registerCsiHandler(e,t):this._parser.registerCsiHandler(e,e=>!Ld(e.params[0],this._optionsService.rawOptions.windowOptions)||t(e))}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new bd(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new gd(t))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){var e;if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(0===this._activeBuffer.x&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&(null==(e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y))?void 0:e.isWrapped)){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);e.hasWidth(this._activeBuffer.x)&&!e.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e,t){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+t):(this._activeBuffer.x=e,this._activeBuffer.y=t),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,t){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+t)}cursorUp(e){let t=this._activeBuffer.y-this._activeBuffer.scrollTop;return t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){let t=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){let t=e.params[0];return 0===t?delete this._activeBuffer.tabs[this._activeBuffer.x]:3===t&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){let t=e.params[0];return 1===t&&(this._curAttrData.bg|=536870912),(2===t||0===t)&&(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,t,i,s=!1,r=!1){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.replaceCells(t,i,this._activeBuffer.getNullCell(this._eraseAttrData()),r),s&&(n.isWrapped=!1)}_resetBufferLine(e,t=!1){let i=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);i&&(i.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),i.isWrapped=!1)}eraseInDisplay(e,t=!1){var i;let s;switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:for(s=this._activeBuffer.y,this._dirtyRowTracker.markDirty(s),this._eraseInBufferLine(s++,this._activeBuffer.x,this._bufferService.cols,0===this._activeBuffer.x,t);s<this._bufferService.rows;s++)this._resetBufferLine(s,t);this._dirtyRowTracker.markDirty(s);break;case 1:for(s=this._activeBuffer.y,this._dirtyRowTracker.markDirty(s),this._eraseInBufferLine(s,0,this._activeBuffer.x+1,!0,t),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(s+1).isWrapped=!1);s--;)this._resetBufferLine(s,t);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(s=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,s-1);s--&&!(null==(i=this._activeBuffer.lines.get(this._activeBuffer.ybase+s))?void 0:i.getTrimmedLength()););for(;s>=0;s--)this._bufferService.scroll(this._eraseAttrData())}else{for(s=this._bufferService.rows,this._dirtyRowTracker.markDirty(s-1);s--;)this._resetBufferLine(s,t);this._dirtyRowTracker.markDirty(0)}break;case 3:let e=this._activeBuffer.lines.length-this._bufferService.rows;e>0&&(this._activeBuffer.lines.trimStart(e),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-e,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-e,0),this._onScroll.fire(0))}return!0}eraseInLine(e,t=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,0===this._activeBuffer.x,t);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t)}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let i=this._activeBuffer.ybase+this._activeBuffer.y,s=this._bufferService.rows-1-this._activeBuffer.scrollBottom,r=this._bufferService.rows-1+this._activeBuffer.ybase-s+1;for(;t--;)this._activeBuffer.lines.splice(r-1,1),this._activeBuffer.lines.splice(i,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}deleteLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let i,s=this._activeBuffer.ybase+this._activeBuffer.y;for(i=this._bufferService.rows-1-this._activeBuffer.scrollBottom,i=this._bufferService.rows-1+this._activeBuffer.ybase-i;t--;)this._activeBuffer.lines.splice(s,1),this._activeBuffer.lines.splice(i,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}insertChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.insertCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}deleteChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.deleteCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}scrollUp(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollDown(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,0,this._activeBuffer.getBlankLine(Th));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollLeft(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let i=this._activeBuffer.scrollTop;i<=this._activeBuffer.scrollBottom;++i){let e=this._activeBuffer.lines.get(this._activeBuffer.ybase+i);e.deleteCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),e.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollRight(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let i=this._activeBuffer.scrollTop;i<=this._activeBuffer.scrollBottom;++i){let e=this._activeBuffer.lines.get(this._activeBuffer.ybase+i);e.insertCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),e.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}insertColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let i=this._activeBuffer.scrollTop;i<=this._activeBuffer.scrollBottom;++i){let e=this._activeBuffer.lines.get(this._activeBuffer.ybase+i);e.insertCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),e.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}deleteColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let i=this._activeBuffer.scrollTop;i<=this._activeBuffer.scrollBottom;++i){let e=this._activeBuffer.lines.get(this._activeBuffer.ybase+i);e.deleteCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),e.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}eraseChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.replaceCells(this._activeBuffer.x,this._activeBuffer.x+(e.params[0]||1),this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}repeatPrecedingCharacter(e){let t=this._parser.precedingJoinState;if(!t)return!0;let i=e.params[0]||1,s=hd.extractWidth(t),r=this._activeBuffer.x-s,n=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).getString(r),o=new Uint32Array(n.length*i),a=0;for(let c=0;c<n.length;){let e=n.codePointAt(c)||0;o[a++]=e,c+=e>65535?2:1}let l=a;for(let c=1;c<i;++c)o.copyWithin(l,0,a),l+=a;return this.print(o,0,l),!0}sendDeviceAttributesPrimary(e){return e.params[0]>0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(Gl.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(Gl.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(Gl.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(Gl.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(e.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(Gl.ESC+"[>83;40003;0c")),!0}_is(e){return 0===(this._optionsService.rawOptions.termName+"").indexOf(e)}setMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!0;break;case 20:this._optionsService.options.convertEol=!0}return!0}setModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._charsetService.setgCharset(0,Fh),this._charsetService.setgCharset(1,Fh),this._charsetService.setgCharset(2,Fh),this._charsetService.setgCharset(3,Fh);break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(132,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!0,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!0;break;case 12:this._optionsService.options.cursorBlink=!0;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!0;break;case 66:this._logService.debug("Serial port requested application keypad."),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire();break;case 9:this._coreMouseService.activeProtocol="X10";break;case 1e3:this._coreMouseService.activeProtocol="VT200";break;case 1002:this._coreMouseService.activeProtocol="DRAG";break;case 1003:this._coreMouseService.activeProtocol="ANY";break;case 1004:this._coreService.decPrivateModes.sendFocus=!0,this._onRequestSendFocus.fire();break;case 1005:this._logService.debug("DECSET 1005 not supported (see #2507)");break;case 1006:this._coreMouseService.activeEncoding="SGR";break;case 1015:this._logService.debug("DECSET 1015 not supported (see #2507)");break;case 1016:this._coreMouseService.activeEncoding="SGR_PIXELS";break;case 25:this._coreService.isCursorHidden=!1;break;case 1048:this.saveCursor();break;case 1049:this.saveCursor();case 47:case 1047:this._bufferService.buffers.activateAltBuffer(this._eraseAttrData()),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!0;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!0}return!0}resetMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!1;break;case 20:this._optionsService.options.convertEol=!1}return!0}resetModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!1;break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(80,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!1,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!1;break;case 12:this._optionsService.options.cursorBlink=!1;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!1;break;case 66:this._logService.debug("Switching back to normal keypad."),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire();break;case 9:case 1e3:case 1002:case 1003:this._coreMouseService.activeProtocol="NONE";break;case 1004:this._coreService.decPrivateModes.sendFocus=!1;break;case 1005:this._logService.debug("DECRST 1005 not supported (see #2507)");break;case 1006:case 1016:this._coreMouseService.activeEncoding="DEFAULT";break;case 1015:this._logService.debug("DECRST 1015 not supported (see #2507)");break;case 25:this._coreService.isCursorHidden=!0;break;case 1048:this.restoreCursor();break;case 1049:case 47:case 1047:this._bufferService.buffers.activateNormalBuffer(),1049===e.params[t]&&this.restoreCursor(),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!1;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!1,this._onRequestRefreshRows.fire(void 0)}return!0}requestMode(e,t){let i;var s;(s=i||(i={}))[s.NOT_RECOGNIZED=0]="NOT_RECOGNIZED",s[s.SET=1]="SET",s[s.RESET=2]="RESET",s[s.PERMANENTLY_SET=3]="PERMANENTLY_SET",s[s.PERMANENTLY_RESET=4]="PERMANENTLY_RESET";let r=this._coreService.decPrivateModes,{activeProtocol:n,activeEncoding:o}=this._coreMouseService,a=this._coreService,{buffers:l,cols:c}=this._bufferService,{active:h,alt:d}=l,u=this._optionsService.rawOptions,f=(e,i)=>(a.triggerDataEvent(`${Gl.ESC}[${t?"":"?"}${e};${i}$y`),!0),p=e=>e?1:2,m=e.params[0];return f(m,t?2===m?4:4===m?p(a.modes.insertMode):12===m?3:20===m?p(u.convertEol):0:1===m?p(r.applicationCursorKeys):3===m?u.windowOptions.setWinLines?80===c?2:132===c?1:0:0:6===m?p(r.origin):7===m?p(r.wraparound):8===m?3:9===m?p("X10"===n):12===m?p(u.cursorBlink):25===m?p(!a.isCursorHidden):45===m?p(r.reverseWraparound):66===m?p(r.applicationKeypad):67===m?4:1e3===m?p("VT200"===n):1002===m?p("DRAG"===n):1003===m?p("ANY"===n):1004===m?p(r.sendFocus):1005===m?4:1006===m?p("SGR"===o):1015===m?4:1016===m?p("SGR_PIXELS"===o):1048===m?1:47===m||1047===m||1049===m?p(h===d):2004===m?p(r.bracketedPasteMode):2026===m?p(r.synchronizedOutput):0)}_updateAttrColor(e,t,i,s,r){return 2===t?(e|=50331648,e&=-16777216,e|=ro.fromColorRGB([i,s,r])):5===t&&(e&=-50331904,e|=33554432|255&i),e}_extractColor(e,t,i){let s=[0,0,-1,0,0,0],r=0,n=0;do{if(s[n+r]=e.params[t+n],e.hasSubParams(t+n)){let i=e.getSubParams(t+n),o=0;do{5===s[1]&&(r=1),s[n+o+1+r]=i[o]}while(++o<i.length&&o+n+1+r<s.length);break}if(5===s[1]&&n+r>=2||2===s[1]&&n+r>=5)break;s[1]&&(r=1)}while(++n+t<e.length&&n+r<s.length);for(let o=2;o<s.length;++o)-1===s[o]&&(s[o]=0);switch(s[0]){case 38:i.fg=this._updateAttrColor(i.fg,s[1],s[3],s[4],s[5]);break;case 48:i.bg=this._updateAttrColor(i.bg,s[1],s[3],s[4],s[5]);break;case 58:i.extended=i.extended.clone(),i.extended.underlineColor=this._updateAttrColor(i.extended.underlineColor,s[1],s[3],s[4],s[5])}return n}_processUnderline(e,t){t.extended=t.extended.clone(),(!~e||e>5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,0===e&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=Th.fg,e.bg=Th.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(1===e.length&&0===e.params[0])return this._processSGR0(this._curAttrData),!0;let t,i=e.length,s=this._curAttrData;for(let r=0;r<i;r++)t=e.params[r],t>=30&&t<=37?(s.fg&=-50331904,s.fg|=16777216|t-30):t>=40&&t<=47?(s.bg&=-50331904,s.bg|=16777216|t-40):t>=90&&t<=97?(s.fg&=-50331904,s.fg|=16777224|t-90):t>=100&&t<=107?(s.bg&=-50331904,s.bg|=16777224|t-100):0===t?this._processSGR0(s):1===t?s.fg|=134217728:3===t?s.bg|=67108864:4===t?(s.fg|=268435456,this._processUnderline(e.hasSubParams(r)?e.getSubParams(r)[0]:1,s)):5===t?s.fg|=536870912:7===t?s.fg|=67108864:8===t?s.fg|=1073741824:9===t?s.fg|=2147483648:2===t?s.bg|=134217728:21===t?this._processUnderline(2,s):22===t?(s.fg&=-134217729,s.bg&=-134217729):23===t?s.bg&=-67108865:24===t?(s.fg&=-268435457,this._processUnderline(0,s)):25===t?s.fg&=-536870913:27===t?s.fg&=-67108865:28===t?s.fg&=-1073741825:29===t?s.fg&=2147483647:39===t?(s.fg&=-67108864,s.fg|=16777215&Th.fg):49===t?(s.bg&=-67108864,s.bg|=16777215&Th.bg):38===t||48===t||58===t?r+=this._extractColor(e,r,s):53===t?s.bg|=1073741824:55===t?s.bg&=-1073741825:59===t?(s.extended=s.extended.clone(),s.extended.underlineColor=-1,s.updateExtended()):100===t?(s.fg&=-67108864,s.fg|=16777215&Th.fg,s.bg&=-67108864,s.bg|=16777215&Th.bg):this._logService.debug("Unknown SGR attribute: %d.",t);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${Gl.ESC}[0n`);break;case 6:let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${Gl.ESC}[${e};${t}R`)}return!0}deviceStatusPrivate(e){if(6===e.params[0]){let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${Gl.ESC}[?${e};${t}R`)}return!0}softReset(e){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=Th.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){let t=0===e.length?1:e.params[0];if(0===t)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(t){case 1:case 2:this._coreService.decPrivateModes.cursorStyle="block";break;case 3:case 4:this._coreService.decPrivateModes.cursorStyle="underline";break;case 5:case 6:this._coreService.decPrivateModes.cursorStyle="bar"}let e=t%2==1;this._coreService.decPrivateModes.cursorBlink=e}return!0}setScrollRegion(e){let t,i=e.params[0]||1;return(e.length<2||(t=e.params[1])>this._bufferService.rows||0===t)&&(t=this._bufferService.rows),t>i&&(this._activeBuffer.scrollTop=i-1,this._activeBuffer.scrollBottom=t-1,this._setCursor(0,0)),!0}windowOptions(e){if(!Ld(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;let t=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:2!==t&&this._onRequestWindowsOptionsReport.fire(0);break;case 16:this._onRequestWindowsOptionsReport.fire(1);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${Gl.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(0===t||2===t)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>10&&this._windowTitleStack.shift()),(0===t||1===t)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>10&&this._iconNameStack.shift());break;case 23:(0===t||2===t)&&this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),(0===t||1===t)&&this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop())}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){let t=[],i=e.split(";");for(;i.length>1;){let e=i.shift(),s=i.shift();if(/^\d+$/.exec(e)){let i=parseInt(e);if(Od(i))if("?"===s)t.push({type:0,index:i});else{let e=Md(s);e&&t.push({type:1,index:i,color:e})}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){let t=e.indexOf(";");if(-1===t)return!0;let i=e.slice(0,t).trim(),s=e.slice(t+1);return s?this._createHyperlink(i,s):!i.trim()&&this._finishHyperlink()}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let i,s=e.split(":"),r=s.findIndex(e=>e.startsWith("id="));return-1!==r&&(i=s[r].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:i,uri:t}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,t){let i=e.split(";");for(let s=0;s<i.length&&!(t>=this._specialColors.length);++s,++t)if("?"===i[s])this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let e=Md(i[s]);e&&this._onColor.fire([{type:1,index:this._specialColors[t],color:e}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;let t=[],i=e.split(";");for(let s=0;s<i.length;++s)if(/^\d+$/.exec(i[s])){let e=parseInt(i[s]);Od(e)&&t.push({type:2,index:e})}return t.length&&this._onColor.fire(t),!0}restoreFgColor(e){return this._onColor.fire([{type:2,index:256}]),!0}restoreBgColor(e){return this._onColor.fire([{type:2,index:257}]),!0}restoreCursorColor(e){return this._onColor.fire([{type:2,index:258}]),!0}nextLine(){return this._activeBuffer.x=0,this.index(),!0}keypadApplicationMode(){return this._logService.debug("Serial port requested application keypad."),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire(),!0}keypadNumericMode(){return this._logService.debug("Switching back to normal keypad."),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire(),!0}selectDefaultCharset(){return this._charsetService.setgLevel(0),this._charsetService.setgCharset(0,Fh),!0}selectCharset(e){return 2!==e.length?(this.selectDefaultCharset(),!0):("/"===e[0]||this._charsetService.setgCharset(Rd[e[0]],Wh[e[1]]||Fh),!0)}index(){return this._restrictCursor(),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=Th.clone(),this._eraseAttrDataInternal=Th.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=67108863&this._curAttrData.bg,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){let e=new oo;e.content=4194373,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t<this._bufferService.rows;++t){let i=this._activeBuffer.ybase+this._activeBuffer.y+t,s=this._activeBuffer.lines.get(i);s&&(s.fill(e),s.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(e,t){let i=this._bufferService.buffer,s=this._optionsService.rawOptions;return(e=>(this._coreService.triggerDataEvent(`${Gl.ESC}${e}${Gl.ESC}\\`),!0))('"q'===e?`P1$r${this._curAttrData.isProtected()?1:0}"q`:'"p'===e?'P1$r61;1"p':"r"===e?`P1$r${i.scrollTop+1};${i.scrollBottom+1}r`:"m"===e?"P1$r0m":" q"===e?`P1$r${{block:2,underline:4,bar:6}[s.cursorStyle]-(s.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}},Bd=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){e<this.start?this.start=e:e>this.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(Id=e,e=t,t=Id),e<this.start&&(this.start=e),t>this.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};function Od(e){return 0<=e&&e<256}Bd=Wn([Fn(0,uo)],Bd);var Ad=class extends qo{constructor(e){super(),this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this._register(new da),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(e,t){if(void 0!==t&&this._syncCalls>t)return void(this._syncCalls=0);if(this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;let i;for(this._isSyncWriting=!0;i=this._writeBuffer.shift();){this._action(i);let e=this._callbacks.shift();e&&e()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>5e7)throw new Error("write data discarded, use flow control to avoid losing data");if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput)return this._didUserInput=!1,this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t),void this._innerWrite();setTimeout(()=>this._innerWrite())}this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t)}_innerWrite(e=0,t=!0){let i=e||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let e=this._writeBuffer[this._bufferOffset],s=this._action(e,t);if(s){let e=e=>performance.now()-i>=12?setTimeout(()=>this._innerWrite(0,e)):this._innerWrite(i,e);return void s.catch(e=>(queueMicrotask(()=>{throw e}),Promise.resolve(!1))).then(e)}let r=this._callbacks[this._bufferOffset];if(r&&r(),this._bufferOffset++,this._pendingData-=e.length,performance.now()-i>=12)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>50&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout(()=>this._innerWrite())):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}},zd=class{constructor(e){this._bufferService=e,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(e){let t=this._bufferService.buffer;if(void 0===e.id){let i=t.addMarker(t.ybase+t.y),s={data:e,id:this._nextId++,lines:[i]};return i.onDispose(()=>this._removeMarkerFromLink(s,i)),this._dataByLinkId.set(s.id,s),s.id}let i=e,s=this._getEntryIdKey(i),r=this._entriesWithId.get(s);if(r)return this.addLineToLink(r.id,t.ybase+t.y),r.id;let n=t.addMarker(t.ybase+t.y),o={id:this._nextId++,key:this._getEntryIdKey(i),data:i,lines:[n]};return n.onDispose(()=>this._removeMarkerFromLink(o,n)),this._entriesWithId.set(o.key,o),this._dataByLinkId.set(o.id,o),o.id}addLineToLink(e,t){let i=this._dataByLinkId.get(e);if(i&&i.lines.every(e=>e.line!==t)){let e=this._bufferService.buffer.addMarker(t);i.lines.push(e),e.onDispose(()=>this._removeMarkerFromLink(i,e))}}getLinkData(e){var t;return null==(t=this._dataByLinkId.get(e))?void 0:t.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,t){let i=e.lines.indexOf(t);-1!==i&&(e.lines.splice(i,1),0===e.lines.length&&(void 0!==e.data.id&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};zd=Wn([Fn(0,uo)],zd);var $d=!1,Hd=class extends qo{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new Yo),this._onBinary=this._register(new da),this.onBinary=this._onBinary.event,this._onData=this._register(new da),this.onData=this._onData.event,this._onLineFeed=this._register(new da),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new da),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new da),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new da),this._instantiationService=new Rh,this.optionsService=this._register(new Gh(e)),this._instantiationService.setService(vo,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(qh)),this._instantiationService.setService(uo,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(Lh)),this._instantiationService.setService(go,this._logService),this.coreService=this._register(this._instantiationService.createInstance(ed)),this._instantiationService.setService(po,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(nd)),this._instantiationService.setService(fo,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(hd)),this._instantiationService.setService(xo,this.unicodeService),this._charsetService=this._instantiationService.createInstance(dd),this._instantiationService.setService(mo,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(zd),this._instantiationService.setService(yo,this._oscLinkService),this._inputHandler=this._register(new Td(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(Zo.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(Zo.forward(this._bufferService.onResize,this._onResize)),this._register(Zo.forward(this.coreService.onData,this._onData)),this._register(Zo.forward(this.coreService.onBinary,this._onBinary)),this._register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom(!0))),this._register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this._register(this.optionsService.onMultipleOptionChange(["windowsMode","windowsPty"],()=>this._handleWindowsPtyOptionChange())),this._register(this._bufferService.onScroll(()=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this._register(new Ad((e,t)=>this._inputHandler.parse(e,t))),this._register(Zo.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new da),this._onScroll.event(e=>{var t;null==(t=this._onScrollApi)||t.fire(e.position)})),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(e){for(let t in e)this.optionsService.options[t]=e[t]}write(e,t){this._writeBuffer.write(e,t)}writeSync(e,t){this._logService.logLevel<=3&&!$d&&(this._logService.warn("writeSync is unreliable and will be removed soon."),$d=!0),this._writeBuffer.writeSync(e,t)}input(e,t=!0){this.coreService.triggerDataEvent(e,t)}resize(e,t){isNaN(e)||isNaN(t)||(e=Math.max(e,2),t=Math.max(t,1),this._bufferService.resize(e,t))}scroll(e,t=!1){this._bufferService.scroll(e,t)}scrollLines(e,t){this._bufferService.scrollLines(e,t)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;0!==t&&this.scrollLines(t)}registerEscHandler(e,t){return this._inputHandler.registerEscHandler(e,t)}registerDcsHandler(e,t){return this._inputHandler.registerDcsHandler(e,t)}registerCsiHandler(e,t){return this._inputHandler.registerCsiHandler(e,t)}registerOscHandler(e,t){return this._inputHandler.registerOscHandler(e,t)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1,t=this.optionsService.rawOptions.windowsPty;t&&void 0!==t.buildNumber&&void 0!==t.buildNumber?e="conpty"===t.backend&&t.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let e=[];e.push(this.onLineFeed(ud.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:"H"},()=>(ud(this._bufferService),!1))),this._windowsWrappingHeuristics.value=Ko(()=>{for(let t of e)t.dispose()})}}},Wd={48:["0",")"],49:["1","!"],50:["2","@"],51:["3","#"],52:["4","$"],53:["5","%"],54:["6","^"],55:["7","&"],56:["8","*"],57:["9","("],186:[";",":"],187:["=","+"],188:[",","<"],189:["-","_"],190:[".",">"],191:["/","?"],192:["`","~"],219:["[","{"],220:["\\","|"],221:["]","}"],222:["'",'"']};var Fd=0,Kd=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new rh,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new rh,this._isFlushingDeleted=!1}clear(){this._array.length=0,this._insertedValues.length=0,this._flushInsertedTask.clear(),this._isFlushingInserted=!1,this._deletedIndices.length=0,this._flushDeletedTask.clear(),this._isFlushingDeleted=!1}insert(e){this._flushCleanupDeleted(),0===this._insertedValues.length&&this._flushInsertedTask.enqueue(()=>this._flushInserted()),this._insertedValues.push(e)}_flushInserted(){let e=this._insertedValues.sort((e,t)=>this._getKey(e)-this._getKey(t)),t=0,i=0,s=new Array(this._array.length+this._insertedValues.length);for(let r=0;r<s.length;r++)i>=this._array.length||this._getKey(e[t])<=this._getKey(this._array[i])?(s[r]=e[t],t++):s[r]=this._array[i++];this._array=s,this._insertedValues.length=0}_flushCleanupInserted(){!this._isFlushingInserted&&this._insertedValues.length>0&&this._flushInsertedTask.flush()}delete(e){if(this._flushCleanupInserted(),0===this._array.length)return!1;let t=this._getKey(e);if(void 0===t||-1===(Fd=this._search(t))||this._getKey(this._array[Fd])!==t)return!1;do{if(this._array[Fd]===e)return 0===this._deletedIndices.length&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(Fd),!0}while(++Fd<this._array.length&&this._getKey(this._array[Fd])===t);return!1}_flushDeleted(){this._isFlushingDeleted=!0;let e=this._deletedIndices.sort((e,t)=>e-t),t=0,i=new Array(this._array.length-e.length),s=0;for(let r=0;r<this._array.length;r++)e[t]===r?t++:i[s++]=this._array[r];this._array=i,this._deletedIndices.length=0,this._isFlushingDeleted=!1}_flushCleanupDeleted(){!this._isFlushingDeleted&&this._deletedIndices.length>0&&this._flushDeletedTask.flush()}*getKeyIterator(e){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),0!==this._array.length&&(!((Fd=this._search(e))<0||Fd>=this._array.length)&&this._getKey(this._array[Fd])===e))do{yield this._array[Fd]}while(++Fd<this._array.length&&this._getKey(this._array[Fd])===e)}forEachByKey(e,t){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),0!==this._array.length&&(!((Fd=this._search(e))<0||Fd>=this._array.length)&&this._getKey(this._array[Fd])===e))do{t(this._array[Fd])}while(++Fd<this._array.length&&this._getKey(this._array[Fd])===e)}values(){return this._flushCleanupInserted(),this._flushCleanupDeleted(),[...this._array].values()}_search(e){let t=0,i=this._array.length-1;for(;i>=t;){let s=t+i>>1,r=this._getKey(this._array[s]);if(r>e)i=s-1;else{if(!(r<e)){for(;s>0&&this._getKey(this._array[s-1])===e;)s--;return s}t=s+1}}return t}},Ud=0,Vd=0,qd=class extends qo{constructor(){super(),this._decorations=new Kd(e=>null==e?void 0:e.marker.line),this._onDecorationRegistered=this._register(new da),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new da),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register(Ko(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new Yd(e);if(t){let e=t.marker.onDispose(()=>t.dispose()),i=t.onDispose(()=>{i.dispose(),t&&(this._decorations.delete(t)&&this._onDecorationRemoved.fire(t),e.dispose())});this._decorations.insert(t),this._onDecorationRegistered.fire(t)}return t}reset(){for(let e of this._decorations.values())e.dispose();this._decorations.clear()}*getDecorationsAtCell(e,t,i){let s=0,r=0;for(let n of this._decorations.getKeyIterator(t))s=n.options.x??0,r=s+(n.options.width??1),e>=s&&e<r&&(!i||(n.options.layer??"bottom")===i)&&(yield n)}forEachDecorationAtCell(e,t,i,s){this._decorations.forEachByKey(t,t=>{Ud=t.options.x??0,Vd=Ud+(t.options.width??1),e>=Ud&&e<Vd&&(!i||(t.options.layer??"bottom")===i)&&s(t)})}},Yd=class extends Vo{constructor(e){super(),this.options=e,this.onRenderEmitter=this.add(new da),this.onRender=this.onRenderEmitter.event,this._onDispose=this.add(new da),this.onDispose=this._onDispose.event,this._cachedBg=null,this._cachedFg=null,this.marker=e.marker,this.options.overviewRulerOptions&&!this.options.overviewRulerOptions.position&&(this.options.overviewRulerOptions.position="full")}get backgroundColorRGB(){return null===this._cachedBg&&(this.options.backgroundColor?this._cachedBg=cc.toColor(this.options.backgroundColor):this._cachedBg=void 0),this._cachedBg}get foregroundColorRGB(){return null===this._cachedFg&&(this.options.foregroundColor?this._cachedFg=cc.toColor(this.options.foregroundColor):this._cachedFg=void 0),this._cachedFg}dispose(){this._onDispose.fire(),super.dispose()}},Xd=class{constructor(e,t=1e3){this._renderCallback=e,this._debounceThresholdMS=t,this._lastRefreshMs=0,this._additionalRefreshRequested=!1}dispose(){this._refreshTimeoutID&&clearTimeout(this._refreshTimeoutID)}refresh(e,t,i){this._rowCount=i,e=void 0!==e?e:0,t=void 0!==t?t:this._rowCount-1,this._rowStart=void 0!==this._rowStart?Math.min(this._rowStart,e):e,this._rowEnd=void 0!==this._rowEnd?Math.max(this._rowEnd,t):t;let s=performance.now();if(s-this._lastRefreshMs>=this._debounceThresholdMS)this._lastRefreshMs=s,this._innerRefresh();else if(!this._additionalRefreshRequested){let e=s-this._lastRefreshMs,t=this._debounceThresholdMS-e;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},t)}}_innerRefresh(){if(void 0===this._rowStart||void 0===this._rowEnd||void 0===this._rowCount)return;let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t)}},Gd=class extends qo{constructor(e,t,i,s){super(),this._terminal=e,this._coreBrowserService=i,this._renderService=s,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="";let r=this._coreBrowserService.mainDocument;this._accessibilityContainer=r.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=r.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let n=0;n<this._terminal.rows;n++)this._rowElements[n]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[n]);if(this._topBoundaryFocusListener=e=>this._handleBoundaryFocus(e,0),this._bottomBoundaryFocusListener=e=>this._handleBoundaryFocus(e,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=r.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this._register(new Xd(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this._register(this._terminal.onResize(e=>this._handleResize(e.rows))),this._register(this._terminal.onRender(e=>this._refreshRows(e.start,e.end))),this._register(this._terminal.onScroll(()=>this._refreshRows())),this._register(this._terminal.onA11yChar(e=>this._handleChar(e))),this._register(this._terminal.onLineFeed(()=>this._handleChar("\n"))),this._register(this._terminal.onA11yTab(e=>this._handleTab(e))),this._register(this._terminal.onKey(e=>this._handleKey(e.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(gl(r,"selectionchange",()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(Ko(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t<e;t++)this._handleChar(" ")}_handleChar(e){this._liveRegionLineCount<21&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,"\n"===e&&(this._liveRegionLineCount++,21===this._liveRegionLineCount&&(this._liveRegion.textContent+=Yn())))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),new RegExp("\\p{Control}","u").test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let i=this._terminal.buffer,s=i.lines.length.toString();for(let r=e;r<=t;r++){let e=i.lines.get(i.ydisp+r),t=[],n=(null==e?void 0:e.translateToString(!0,void 0,void 0,t))||"",o=(i.ydisp+r+1).toString(),a=this._rowElements[r];a&&(0===n.length?(a.textContent=" ",this._rowColumns.set(a,[0,1])):(a.textContent=n,this._rowColumns.set(a,t)),a.setAttribute("aria-posinset",o),a.setAttribute("aria-setsize",s),this._alignRowWidth(a))}this._announceCharacters()}_announceCharacters(){0!==this._charsToAnnounce.length&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(e,t){let i,s,r=e.target,n=this._rowElements[0===t?1:this._rowElements.length-2];if(r.getAttribute("aria-posinset")!==(0===t?"1":`${this._terminal.buffer.lines.length}`)&&e.relatedTarget===n){if(0===t?(i=r,s=this._rowElements.pop(),this._rowContainer.removeChild(s)):(i=this._rowElements.shift(),s=r,this._rowContainer.removeChild(i)),i.removeEventListener("focus",this._topBoundaryFocusListener),s.removeEventListener("focus",this._bottomBoundaryFocusListener),0===t){let e=this._createAccessibilityTreeNode();this._rowElements.unshift(e),this._rowContainer.insertAdjacentElement("afterbegin",e)}else{let e=this._createAccessibilityTreeNode();this._rowElements.push(e),this._rowContainer.appendChild(e)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(0===t?-1:1),this._rowElements[0===t?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}}_handleSelectionChange(){var e;if(0===this._rowElements.length)return;let t=this._coreBrowserService.mainDocument.getSelection();if(!t)return;if(t.isCollapsed)return void(this._rowContainer.contains(t.anchorNode)&&this._terminal.clearSelection());if(!t.anchorNode||!t.focusNode)return void console.error("anchorNode and/or focusNode are null");let i={node:t.anchorNode,offset:t.anchorOffset},s={node:t.focusNode,offset:t.focusOffset};if((i.node.compareDocumentPosition(s.node)&Node.DOCUMENT_POSITION_PRECEDING||i.node===s.node&&i.offset>s.offset)&&([i,s]=[s,i]),i.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(i={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(i.node))return;let r=this._rowElements.slice(-1)[0];if(s.node.compareDocumentPosition(r)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(s={node:r,offset:(null==(e=r.textContent)?void 0:e.length)??0}),!this._rowContainer.contains(s.node))return;let n=({node:e,offset:t})=>{let i=e instanceof Text?e.parentNode:e,s=parseInt(null==i?void 0:i.getAttribute("aria-posinset"),10)-1;if(isNaN(s))return console.warn("row is invalid. Race condition?"),null;let r=this._rowColumns.get(i);if(!r)return console.warn("columns is null. Race condition?"),null;let n=t<r.length?r[t]:r.slice(-1)[0]+1;return n>=this._terminal.cols&&(++s,n=0),{row:s,column:n}},o=n(i),a=n(s);if(o&&a){if(o.row>a.row||o.row===a.row&&o.column>=a.column)throw new Error("invalid range");this._terminal.select(o.column,o.row,(a.row-o.row)*this._terminal.cols-o.column+a.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let t=this._rowContainer.children.length;t<this._terminal.rows;t++)this._rowElements[t]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[t]);for(;this._rowElements.length>e;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){let e=this._coreBrowserService.mainDocument.createElement("div");return e.setAttribute("role","listitem"),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e<this._terminal.rows;e++)this._refreshRowDimensions(this._rowElements[e]),this._alignRowWidth(this._rowElements[e])}}_refreshRowDimensions(e){e.style.height=`${this._renderService.dimensions.css.cell.height}px`}_alignRowWidth(e){var t,i;e.style.transform="";let s=e.getBoundingClientRect().width,r=null==(i=null==(t=this._rowColumns.get(e))?void 0:t.slice(-1))?void 0:i[0];if(!r)return;let n=r*this._renderService.dimensions.css.cell.width;e.style.transform=`scaleX(${n/s})`}};Gd=Wn([Fn(1,_o),Fn(2,ko),Fn(3,No)],Gd);var Zd=class extends qo{constructor(e,t,i,s,r){super(),this._element=e,this._mouseService=t,this._renderService=i,this._bufferService=s,this._linkProviderService=r,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this._register(new da),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this._register(new da),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this._register(Ko(()=>{var e;Fo(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,null==(e=this._activeProviderReplies)||e.clear()})),this._register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this._register(gl(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(gl(this._element,"mousemove",this._handleMouseMove.bind(this))),this._register(gl(this._element,"mousedown",this._handleMouseDown.bind(this))),this._register(gl(this._element,"mouseup",this._handleMouseUp.bind(this)))}get currentLink(){return this._currentLink}_handleMouseMove(e){this._lastMouseEvent=e;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);if(!t)return;this._isMouseOut=!1;let i=e.composedPath();for(let s=0;s<i.length;s++){let e=i[s];if(e.classList.contains("xterm"))break;if(e.classList.contains("xterm-hover"))return}(!this._lastBufferCell||t.x!==this._lastBufferCell.x||t.y!==this._lastBufferCell.y)&&(this._handleHover(t),this._lastBufferCell=t)}_handleHover(e){if(this._activeLine!==e.y||this._wasResized)return this._clearCurrentLink(),this._askForLink(e,!1),void(this._wasResized=!1);this._currentLink&&this._linkAtPosition(this._currentLink.link,e)||(this._clearCurrentLink(),this._askForLink(e,!0))}_askForLink(e,t){var i,s;(!this._activeProviderReplies||!t)&&(null==(i=this._activeProviderReplies)||i.forEach(e=>{null==e||e.forEach(e=>{e.link.dispose&&e.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let r=!1;for(let[n,o]of this._linkProviderService.linkProviders.entries())t?(null==(s=this._activeProviderReplies)?void 0:s.get(n))&&(r=this._checkLinkProviderResult(n,e,r)):o.provideLinks(e.y,t=>{var i,s;if(this._isMouseOut)return;let o=null==t?void 0:t.map(e=>({link:e}));null==(i=this._activeProviderReplies)||i.set(n,o),r=this._checkLinkProviderResult(n,e,r),(null==(s=this._activeProviderReplies)?void 0:s.size)===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,t){let i=new Set;for(let s=0;s<t.size;s++){let r=t.get(s);if(r)for(let t=0;t<r.length;t++){let s=r[t],n=s.link.range.start.y<e?0:s.link.range.start.x,o=s.link.range.end.y>e?this._bufferService.cols:s.link.range.end.x;for(let e=n;e<=o;e++){if(i.has(e)){r.splice(t--,1);break}i.add(e)}}}}_checkLinkProviderResult(e,t,i){var s;if(!this._activeProviderReplies)return i;let r=this._activeProviderReplies.get(e),n=!1;for(let o=0;o<e;o++)(!this._activeProviderReplies.has(o)||this._activeProviderReplies.get(o))&&(n=!0);if(!n&&r){let e=r.find(e=>this._linkAtPosition(e.link,t));e&&(i=!0,this._handleNewLink(e))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!i)for(let o=0;o<this._activeProviderReplies.size;o++){let e=null==(s=this._activeProviderReplies.get(o))?void 0:s.find(e=>this._linkAtPosition(e.link,t));if(e){i=!0,this._handleNewLink(e);break}}return i}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);var i,s;t&&this._mouseDownLink&&(i=this._mouseDownLink.link,s=this._currentLink.link,i.text===s.text&&i.range.start.x===s.range.start.x&&i.range.start.y===s.range.start.y&&i.range.end.x===s.range.end.x&&i.range.end.y===s.range.end.y)&&this._linkAtPosition(this._currentLink.link,t)&&this._currentLink.link.activate(e,this._currentLink.link.text)}_clearCurrentLink(e,t){!this._currentLink||!this._lastMouseEvent||(!e||!t||this._currentLink.link.range.start.y>=e&&this._currentLink.link.range.end.y<=t)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,Fo(this._linkCacheDisposables),this._linkCacheDisposables.length=0)}_handleNewLink(e){if(!this._lastMouseEvent)return;let t=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);t&&this._linkAtPosition(e.link,t)&&(this._currentLink=e,this._currentLink.state={decorations:{underline:void 0===e.link.decorations||e.link.decorations.underline,pointerCursor:void 0===e.link.decorations||e.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,e.link,this._lastMouseEvent),e.link.decorations={},Object.defineProperties(e.link.decorations,{pointerCursor:{get:()=>{var e,t;return null==(t=null==(e=this._currentLink)?void 0:e.state)?void 0:t.decorations.pointerCursor},set:e=>{var t;(null==(t=this._currentLink)?void 0:t.state)&&this._currentLink.state.decorations.pointerCursor!==e&&(this._currentLink.state.decorations.pointerCursor=e,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",e))}},underline:{get:()=>{var e,t;return null==(t=null==(e=this._currentLink)?void 0:e.state)?void 0:t.decorations.underline},set:t=>{var i,s,r;(null==(i=this._currentLink)?void 0:i.state)&&(null==(r=null==(s=this._currentLink)?void 0:s.state)?void 0:r.decorations.underline)!==t&&(this._currentLink.state.decorations.underline=t,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,t))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(e=>{if(!this._currentLink)return;let t=0===e.start?0:e.start+1+this._bufferService.buffer.ydisp,i=this._bufferService.buffer.ydisp+1+e.end;if(this._currentLink.link.range.start.y>=t&&this._currentLink.link.range.end.y<=i&&(this._clearCurrentLink(t,i),this._lastMouseEvent)){let e=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);e&&this._askForLink(e,!1)}})))}_linkHover(e,t,i){var s;(null==(s=this._currentLink)?void 0:s.state)&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add("xterm-cursor-pointer")),t.hover&&t.hover(i,t.text)}_fireUnderlineEvent(e,t){let i=e.range,s=this._bufferService.buffer.ydisp,r=this._createLinkUnderlineEvent(i.start.x-1,i.start.y-s-1,i.end.x,i.end.y-s-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(r)}_linkLeave(e,t,i){var s;(null==(s=this._currentLink)?void 0:s.state)&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove("xterm-cursor-pointer")),t.leave&&t.leave(i,t.text)}_linkAtPosition(e,t){let i=e.range.start.y*this._bufferService.cols+e.range.start.x,s=e.range.end.y*this._bufferService.cols+e.range.end.x,r=t.y*this._bufferService.cols+t.x;return i<=r&&r<=s}_positionFromMouseEvent(e,t,i){let s=i.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(s)return{x:s[0],y:s[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,i,s,r){return{x1:e,y1:t,x2:i,y2:s,cols:this._bufferService.cols,fg:r}}};Zd=Wn([Fn(1,Eo),Fn(2,No),Fn(3,uo),Fn(4,Ro)],Zd);var Jd=class extends Hd{constructor(e={}){super(e),this._linkifier=this._register(new Yo),this.browser=Fc,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new Yo),this._onCursorMove=this._register(new da),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new da),this.onKey=this._onKey.event,this._onRender=this._register(new da),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new da),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new da),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new da),this.onBell=this._onBell.event,this._onFocus=this._register(new da),this._onBlur=this._register(new da),this._onA11yCharEmitter=this._register(new da),this._onA11yTabEmitter=this._register(new da),this._onWillOpen=this._register(new da),this._setup(),this._decorationService=this._instantiationService.createInstance(qd),this._instantiationService.setService(bo,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(zc),this._instantiationService.setService(Ro,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(wo)),this._register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this._register(this._inputHandler.onRequestRefreshRows(e=>this.refresh((null==e?void 0:e.start)??0,(null==e?void 0:e.end)??this.rows-1))),this._register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this._register(this._inputHandler.onRequestReset(()=>this.reset())),this._register(this._inputHandler.onRequestWindowsOptionsReport(e=>this._reportWindowsOptions(e))),this._register(this._inputHandler.onColor(e=>this._handleColorEvent(e))),this._register(Zo.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(Zo.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(Zo.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(Zo.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(e=>this._afterResize(e.cols,e.rows))),this._register(Ko(()=>{var e,t;this._customKeyEventHandler=void 0,null==(t=null==(e=this.element)?void 0:e.parentNode)||t.removeChild(this.element)}))}get linkifier(){return this._linkifier.value}get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}_handleColorEvent(e){if(this._themeService)for(let t of e){let e,i="";switch(t.index){case 256:e="foreground",i="10";break;case 257:e="background",i="11";break;case 258:e="cursor",i="12";break;default:e="ansi",i="4;"+t.index}switch(t.type){case 0:let s=lc.toColorRGB("ansi"===e?this._themeService.colors.ansi[t.index]:this._themeService.colors[e]);this.coreService.triggerDataEvent(`${Gl.ESC}]${i};${Dd(s)}${ec.ST}`);break;case 1:if("ansi"===e)this._themeService.modifyColors(e=>e.ansi[t.index]=ac.toColor(...t.color));else{let i=e;this._themeService.modifyColors(e=>e[i]=ac.toColor(...t.color))}break;case 2:this._themeService.restoreColor(t.index)}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(e){e?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(Gd,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(Gl.ESC+"[I"),this.element.classList.add("focus"),this._showCursor(),this._onFocus.fire()}blur(){var e;return null==(e=this.textarea)?void 0:e.blur()}_handleTextAreaBlur(){this.textarea.value="",this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(Gl.ESC+"[O"),this.element.classList.remove("focus"),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;let e=this.buffer.ybase+this.buffer.y,t=this.buffer.lines.get(e);if(!t)return;let i=Math.min(this.buffer.x,this.cols-1),s=this._renderService.dimensions.css.cell.height,r=t.getWidth(i),n=this._renderService.dimensions.css.cell.width*r,o=this.buffer.y*this._renderService.dimensions.css.cell.height,a=i*this._renderService.dimensions.css.cell.width;this.textarea.style.left=a+"px",this.textarea.style.top=o+"px",this.textarea.style.width=n+"px",this.textarea.style.height=s+"px",this.textarea.style.lineHeight=s+"px",this.textarea.style.zIndex="-5"}_initGlobal(){this._bindKeys(),this._register(gl(this.element,"copy",e=>{var t,i;this.hasSelection()&&(t=e,i=this._selectionService,t.clipboardData&&t.clipboardData.setData("text/plain",i.selectionText),t.preventDefault())}));let e=e=>function(e,t,i,s){e.stopPropagation(),e.clipboardData&&Gn(e.clipboardData.getData("text/plain"),t,i,s)}(e,this.textarea,this.coreService,this.optionsService);this._register(gl(this.textarea,"paste",e)),this._register(gl(this.element,"paste",e)),qc?this._register(gl(this.element,"mousedown",e=>{2===e.button&&Jn(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(gl(this.element,"contextmenu",e=>{Jn(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),th&&this._register(gl(this.element,"auxclick",e=>{1===e.button&&Zn(e,this.textarea,this.screenElement)}))}_bindKeys(){this._register(gl(this.textarea,"keyup",e=>this._keyUp(e),!0)),this._register(gl(this.textarea,"keydown",e=>this._keyDown(e),!0)),this._register(gl(this.textarea,"keypress",e=>this._keyPress(e),!0)),this._register(gl(this.textarea,"compositionstart",()=>this._compositionHelper.compositionstart())),this._register(gl(this.textarea,"compositionupdate",e=>this._compositionHelper.compositionupdate(e))),this._register(gl(this.textarea,"compositionend",()=>this._compositionHelper.compositionend())),this._register(gl(this.textarea,"input",e=>this._inputEvent(e),!0)),this._register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(e){var t;if(!e)throw new Error("Terminal requires a parent element.");if(e.isConnected||this._logService.debug("Terminal.open was called on an element that was not attached to the DOM"),(null==(t=this.element)?void 0:t.ownerDocument.defaultView)&&this._coreBrowserService)return void(this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView));this._document=e.ownerDocument,this.options.documentOverride&&this.options.documentOverride instanceof Document&&(this._document=this.optionsService.rawOptions.documentOverride),this.element=this._document.createElement("div"),this.element.dir="ltr",this.element.classList.add("terminal"),this.element.classList.add("xterm"),e.appendChild(this.element);let i=this._document.createDocumentFragment();this._viewportElement=this._document.createElement("div"),this._viewportElement.classList.add("xterm-viewport"),i.appendChild(this._viewportElement),this.screenElement=this._document.createElement("div"),this.screenElement.classList.add("xterm-screen"),this._register(gl(this.screenElement,"mousemove",e=>this.updateCursorStyle(e))),this._helperContainer=this._document.createElement("div"),this._helperContainer.classList.add("xterm-helpers"),this.screenElement.appendChild(this._helperContainer),i.appendChild(this.screenElement);let s=this.textarea=this._document.createElement("textarea");this.textarea.classList.add("xterm-helper-textarea"),this.textarea.setAttribute("aria-label",Un()),ih||this.textarea.setAttribute("aria-multiline","false"),this.textarea.setAttribute("autocorrect","off"),this.textarea.setAttribute("autocapitalize","off"),this.textarea.setAttribute("spellcheck","false"),this.textarea.tabIndex=0,this._register(this.optionsService.onSpecificOptionChange("disableStdin",()=>s.readOnly=this.optionsService.rawOptions.disableStdin)),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(Oc,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<"u"?window.document:null)),this._instantiationService.setService(ko,this._coreBrowserService),this._register(gl(this.textarea,"focus",e=>this._handleTextAreaFocus(e))),this._register(gl(this.textarea,"blur",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(Lc,this._document,this._helperContainer),this._instantiationService.setService(Co,this._charSizeService),this._themeService=this._instantiationService.createInstance(Mh),this._instantiationService.setService(Do,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(xc),this._instantiationService.setService(jo,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(oh,this.rows,this.screenElement)),this._instantiationService.setService(No,this._renderService),this._register(this._renderService.onRenderedViewportChange(e=>this._onRender.fire(e))),this.onResize(e=>this._renderService.resize(e.cols,e.rows)),this._compositionView=this._document.createElement("div"),this._compositionView.classList.add("composition-view"),this._compositionHelper=this._instantiationService.createInstance(oc,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(Hc),this._instantiationService.setService(Eo,this._mouseService);let r=this._linkifier.value=this._register(this._instantiationService.createInstance(Zd,this.screenElement));this.element.appendChild(i);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._register(this.onCursorMove(()=>{this._renderService.handleCursorMove(),this._syncTextArea()})),this._register(this.onResize(()=>this._renderService.handleResize(this.cols,this.rows))),this._register(this.onBlur(()=>this._renderService.handleBlur())),this._register(this.onFocus(()=>this._renderService.handleFocus())),this._viewport=this._register(this._instantiationService.createInstance(Yl,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines(e=>{super.scrollLines(e,!1),this.refresh(0,this.rows-1)})),this._selectionService=this._register(this._instantiationService.createInstance(vh,this.element,this.screenElement,r)),this._instantiationService.setService(Mo,this._selectionService),this._register(this._selectionService.onRequestScrollLines(e=>this.scrollLines(e.amount,e.suppressScrollEvent))),this._register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this._register(this._selectionService.onRequestRedraw(e=>this._renderService.handleSelectionChanged(e.start,e.end,e.columnSelectMode))),this._register(this._selectionService.onLinuxMouseSelection(e=>{this.textarea.value=e,this.textarea.focus(),this.textarea.select()})),this._register(Zo.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{var e;this._selectionService.refresh(),null==(e=this._viewport)||e.queueSync()})),this._register(this._instantiationService.createInstance(Xl,this.screenElement)),this._register(gl(this.element,"mousedown",e=>this._selectionService.handleMouseDown(e))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add("enable-mouse-events")):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(Gd,this)),this._register(this.optionsService.onSpecificOptionChange("screenReaderMode",e=>this._handleScreenReaderModeOptionChange(e))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(nc,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRuler",e=>{!this._overviewRulerRenderer&&e&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(nc,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(Pc,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function i(t){var i,s,r,n,o;let a,l,c=e._mouseService.getMouseReportCoords(t,e.screenElement);if(!c)return!1;switch(t.overrideType||t.type){case"mousemove":l=32,void 0===t.buttons?(a=3,void 0!==t.button&&(a=t.button<3?t.button:3)):a=1&t.buttons?0:4&t.buttons?1:2&t.buttons?2:3;break;case"mouseup":l=0,a=t.button<3?t.button:3;break;case"mousedown":l=1,a=t.button<3?t.button:3;break;case"wheel":if(e._customWheelEventHandler&&!1===e._customWheelEventHandler(t))return!1;let c=t.deltaY;if(0===c||0===e.coreMouseService.consumeWheelEvent(t,null==(n=null==(r=null==(s=null==(i=e._renderService)?void 0:i.dimensions)?void 0:s.device)?void 0:r.cell)?void 0:n.height,null==(o=e._coreBrowserService)?void 0:o.dpr))return!1;l=c<0?0:1,a=4;break;default:return!1}return!(void 0===l||void 0===a||a>4)&&e.coreMouseService.triggerMouseEvent({col:c.col,row:c.row,x:c.x,y:c.y,button:a,action:l,ctrl:t.ctrlKey,alt:t.altKey,shift:t.shiftKey})}let s={mouseup:null,wheel:null,mousedrag:null,mousemove:null},r={mouseup:e=>(i(e),e.buttons||(this._document.removeEventListener("mouseup",s.mouseup),s.mousedrag&&this._document.removeEventListener("mousemove",s.mousedrag)),this.cancel(e)),wheel:e=>(i(e),this.cancel(e,!0)),mousedrag:e=>{e.buttons&&i(e)},mousemove:e=>{e.buttons||i(e)}};this._register(this.coreMouseService.onProtocolChange(e=>{e?("debug"===this.optionsService.rawOptions.logLevel&&this._logService.debug("Binding to mouse events:",this.coreMouseService.explainEvents(e)),this.element.classList.add("enable-mouse-events"),this._selectionService.disable()):(this._logService.debug("Unbinding from mouse events."),this.element.classList.remove("enable-mouse-events"),this._selectionService.enable()),8&e?s.mousemove||(t.addEventListener("mousemove",r.mousemove),s.mousemove=r.mousemove):(t.removeEventListener("mousemove",s.mousemove),s.mousemove=null),16&e?s.wheel||(t.addEventListener("wheel",r.wheel,{passive:!1}),s.wheel=r.wheel):(t.removeEventListener("wheel",s.wheel),s.wheel=null),2&e?s.mouseup||(s.mouseup=r.mouseup):(this._document.removeEventListener("mouseup",s.mouseup),s.mouseup=null),4&e?s.mousedrag||(s.mousedrag=r.mousedrag):(this._document.removeEventListener("mousemove",s.mousedrag),s.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(gl(t,"mousedown",e=>{if(e.preventDefault(),this.focus(),this.coreMouseService.areMouseEventsActive&&!this._selectionService.shouldForceSelection(e))return i(e),s.mouseup&&this._document.addEventListener("mouseup",s.mouseup),s.mousedrag&&this._document.addEventListener("mousemove",s.mousedrag),this.cancel(e)})),this._register(gl(t,"wheel",t=>{var i,r,n,o,a;if(!s.wheel){if(this._customWheelEventHandler&&!1===this._customWheelEventHandler(t))return!1;if(!this.buffer.hasScrollback){if(0===t.deltaY)return!1;if(0===e.coreMouseService.consumeWheelEvent(t,null==(o=null==(n=null==(r=null==(i=e._renderService)?void 0:i.dimensions)?void 0:r.device)?void 0:n.cell)?void 0:o.height,null==(a=e._coreBrowserService)?void 0:a.dpr))return this.cancel(t,!0);let s=Gl.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(t.deltaY<0?"A":"B");return this.coreService.triggerDataEvent(s,!0),this.cancel(t,!0)}}},{passive:!1}))}refresh(e,t){var i;null==(i=this._renderService)||i.refreshRows(e,t)}updateCursorStyle(e){var t;(null==(t=this._selectionService)?void 0:t.shouldColumnSelect(e))?this.element.classList.add("column-select"):this.element.classList.remove("column-select")}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(e,t){this._viewport?this._viewport.scrollLines(e):super.scrollLines(e,t),this.refresh(0,this.rows-1)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){e&&this._viewport?this._viewport.scrollToLine(this.buffer.ybase,!0):this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;0!==t&&this.scrollLines(t)}paste(e){Gn(e,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(e){this._customKeyEventHandler=e}attachCustomWheelEventHandler(e){this._customWheelEventHandler=e}registerLinkProvider(e){return this._linkProviderService.registerLinkProvider(e)}registerCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");let t=this._characterJoinerService.register(e);return this.refresh(0,this.rows-1),t}deregisterCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");this._characterJoinerService.deregister(e)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(e){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e)}registerDecoration(e){return this._decorationService.registerDecoration(e)}hasSelection(){return!!this._selectionService&&this._selectionService.hasSelection}select(e,t,i){this._selectionService.setSelection(e,t,i)}getSelection(){return this._selectionService?this._selectionService.selectionText:""}getSelectionPosition(){if(this._selectionService&&this._selectionService.hasSelection)return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){var e;null==(e=this._selectionService)||e.clearSelection()}selectAll(){var e;null==(e=this._selectionService)||e.selectAll()}selectLines(e,t){var i;null==(i=this._selectionService)||i.selectLines(e,t)}_keyDown(e){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&!1===this._customKeyEventHandler(e))return!1;let t=this.browser.isMac&&this.options.macOptionIsMeta&&e.altKey;if(!t&&!this._compositionHelper.keydown(e))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(!0),!1;!t&&("Dead"===e.key||"AltGraph"===e.key)&&(this._unprocessedDeadKey=!0);let i=function(e,t,i,s){var r;let n={type:0,cancel:!1,key:void 0},o=(e.shiftKey?1:0)|(e.altKey?2:0)|(e.ctrlKey?4:0)|(e.metaKey?8:0);switch(e.keyCode){case 0:"UIKeyInputUpArrow"===e.key?n.key=t?Gl.ESC+"OA":Gl.ESC+"[A":"UIKeyInputLeftArrow"===e.key?n.key=t?Gl.ESC+"OD":Gl.ESC+"[D":"UIKeyInputRightArrow"===e.key?n.key=t?Gl.ESC+"OC":Gl.ESC+"[C":"UIKeyInputDownArrow"===e.key&&(n.key=t?Gl.ESC+"OB":Gl.ESC+"[B");break;case 8:n.key=e.ctrlKey?"\b":Gl.DEL,e.altKey&&(n.key=Gl.ESC+n.key);break;case 9:if(e.shiftKey){n.key=Gl.ESC+"[Z";break}n.key=Gl.HT,n.cancel=!0;break;case 13:n.key=e.altKey?Gl.ESC+Gl.CR:Gl.CR,n.cancel=!0;break;case 27:n.key=Gl.ESC,e.altKey&&(n.key=Gl.ESC+Gl.ESC),n.cancel=!0;break;case 37:if(e.metaKey)break;n.key=o?Gl.ESC+"[1;"+(o+1)+"D":t?Gl.ESC+"OD":Gl.ESC+"[D";break;case 39:if(e.metaKey)break;n.key=o?Gl.ESC+"[1;"+(o+1)+"C":t?Gl.ESC+"OC":Gl.ESC+"[C";break;case 38:if(e.metaKey)break;n.key=o?Gl.ESC+"[1;"+(o+1)+"A":t?Gl.ESC+"OA":Gl.ESC+"[A";break;case 40:if(e.metaKey)break;n.key=o?Gl.ESC+"[1;"+(o+1)+"B":t?Gl.ESC+"OB":Gl.ESC+"[B";break;case 45:!e.shiftKey&&!e.ctrlKey&&(n.key=Gl.ESC+"[2~");break;case 46:n.key=o?Gl.ESC+"[3;"+(o+1)+"~":Gl.ESC+"[3~";break;case 36:n.key=o?Gl.ESC+"[1;"+(o+1)+"H":t?Gl.ESC+"OH":Gl.ESC+"[H";break;case 35:n.key=o?Gl.ESC+"[1;"+(o+1)+"F":t?Gl.ESC+"OF":Gl.ESC+"[F";break;case 33:e.shiftKey?n.type=2:e.ctrlKey?n.key=Gl.ESC+"[5;"+(o+1)+"~":n.key=Gl.ESC+"[5~";break;case 34:e.shiftKey?n.type=3:e.ctrlKey?n.key=Gl.ESC+"[6;"+(o+1)+"~":n.key=Gl.ESC+"[6~";break;case 112:n.key=o?Gl.ESC+"[1;"+(o+1)+"P":Gl.ESC+"OP";break;case 113:n.key=o?Gl.ESC+"[1;"+(o+1)+"Q":Gl.ESC+"OQ";break;case 114:n.key=o?Gl.ESC+"[1;"+(o+1)+"R":Gl.ESC+"OR";break;case 115:n.key=o?Gl.ESC+"[1;"+(o+1)+"S":Gl.ESC+"OS";break;case 116:n.key=o?Gl.ESC+"[15;"+(o+1)+"~":Gl.ESC+"[15~";break;case 117:n.key=o?Gl.ESC+"[17;"+(o+1)+"~":Gl.ESC+"[17~";break;case 118:n.key=o?Gl.ESC+"[18;"+(o+1)+"~":Gl.ESC+"[18~";break;case 119:n.key=o?Gl.ESC+"[19;"+(o+1)+"~":Gl.ESC+"[19~";break;case 120:n.key=o?Gl.ESC+"[20;"+(o+1)+"~":Gl.ESC+"[20~";break;case 121:n.key=o?Gl.ESC+"[21;"+(o+1)+"~":Gl.ESC+"[21~";break;case 122:n.key=o?Gl.ESC+"[23;"+(o+1)+"~":Gl.ESC+"[23~";break;case 123:n.key=o?Gl.ESC+"[24;"+(o+1)+"~":Gl.ESC+"[24~";break;default:if(!e.ctrlKey||e.shiftKey||e.altKey||e.metaKey)if(i&&!s||!e.altKey||e.metaKey)!i||e.altKey||e.ctrlKey||e.shiftKey||!e.metaKey?e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.keyCode>=48&&1===e.key.length?n.key=e.key:e.key&&e.ctrlKey&&("_"===e.key&&(n.key=Gl.US),"@"===e.key&&(n.key=Gl.NUL)):65===e.keyCode&&(n.type=1);else{let t=null==(r=Wd[e.keyCode])?void 0:r[e.shiftKey?1:0];if(t)n.key=Gl.ESC+t;else if(e.keyCode>=65&&e.keyCode<=90){let t=e.ctrlKey?e.keyCode-64:e.keyCode+32,i=String.fromCharCode(t);e.shiftKey&&(i=i.toUpperCase()),n.key=Gl.ESC+i}else if(32===e.keyCode)n.key=Gl.ESC+(e.ctrlKey?Gl.NUL:" ");else if("Dead"===e.key&&e.code.startsWith("Key")){let t=e.code.slice(3,4);e.shiftKey||(t=t.toLowerCase()),n.key=Gl.ESC+t,n.cancel=!0}}else e.keyCode>=65&&e.keyCode<=90?n.key=String.fromCharCode(e.keyCode-64):32===e.keyCode?n.key=Gl.NUL:e.keyCode>=51&&e.keyCode<=55?n.key=String.fromCharCode(e.keyCode-51+27):56===e.keyCode?n.key=Gl.DEL:219===e.keyCode?n.key=Gl.ESC:220===e.keyCode?n.key=Gl.FS:221===e.keyCode&&(n.key=Gl.GS)}return n}(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),3===i.type||2===i.type){let t=this.rows-1;return this.scrollLines(2===i.type?-t:t),this.cancel(e,!0)}return 1===i.type&&this.selectAll(),!!(this._isThirdLevelShift(this.browser,e)||(i.cancel&&this.cancel(e,!0),!i.key)||e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&1===e.key.length&&e.key.charCodeAt(0)>=65&&e.key.charCodeAt(0)<=90)||(this._unprocessedDeadKey?(this._unprocessedDeadKey=!1,!0):((i.key===Gl.ETX||i.key===Gl.CR)&&(this.textarea.value=""),this._onKey.fire({key:i.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(i.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey?this.cancel(e,!0):void(this._keyDownHandled=!0)))}_isThirdLevelShift(e,t){let i=e.isMac&&!this.options.macOptionIsMeta&&t.altKey&&!t.ctrlKey&&!t.metaKey||e.isWindows&&t.altKey&&t.ctrlKey&&!t.metaKey||e.isWindows&&t.getModifierState("AltGraph");return"keypress"===t.type?i:i&&(!t.keyCode||t.keyCode>47)}_keyUp(e){var t;this._keyDownSeen=!1,(!this._customKeyEventHandler||!1!==this._customKeyEventHandler(e))&&(16===(t=e).keyCode||17===t.keyCode||18===t.keyCode||this.focus(),this.updateCursorStyle(e),this._keyPressHandled=!1)}_keyPress(e){let t;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&!1===this._customKeyEventHandler(e))return!1;if(this.cancel(e),e.charCode)t=e.charCode;else if(null===e.which||void 0===e.which)t=e.keyCode;else{if(0===e.which||0===e.charCode)return!1;t=e.which}return!(!t||(e.altKey||e.ctrlKey||e.metaKey)&&!this._isThirdLevelShift(this.browser,e))&&(t=String.fromCharCode(t),this._onKey.fire({key:t,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(t,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,!0)}_inputEvent(e){if(e.data&&"insertText"===e.inputType&&(!e.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;let t=e.data;return this.coreService.triggerDataEvent(t,!0),this.cancel(e),!0}return!1}resize(e,t){e!==this.cols||t!==this.rows?super.resize(e,t):this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure()}_afterResize(e,t){var i;null==(i=this._charSizeService)||i.measure()}clear(){if(0!==this.buffer.ybase||0!==this.buffer.y){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let e=1;e<this.rows;e++)this.buffer.lines.push(this.buffer.getBlankLine(Th));this._onScroll.fire({position:this.buffer.ydisp}),this.refresh(0,this.rows-1)}}reset(){var e;this.options.rows=this.rows,this.options.cols=this.cols;let t=this._customKeyEventHandler;this._setup(),super.reset(),null==(e=this._selectionService)||e.reset(),this._decorationService.reset(),this._customKeyEventHandler=t,this.refresh(0,this.rows-1)}clearTextureAtlas(){var e;null==(e=this._renderService)||e.clearTextureAtlas()}_reportFocus(){var e;(null==(e=this.element)?void 0:e.classList.contains("focus"))?this.coreService.triggerDataEvent(Gl.ESC+"[I"):this.coreService.triggerDataEvent(Gl.ESC+"[O")}_reportWindowsOptions(e){if(this._renderService)switch(e){case 0:let e=this._renderService.dimensions.css.canvas.width.toFixed(0),t=this._renderService.dimensions.css.canvas.height.toFixed(0);this.coreService.triggerDataEvent(`${Gl.ESC}[4;${t};${e}t`);break;case 1:let i=this._renderService.dimensions.css.cell.width.toFixed(0),s=this._renderService.dimensions.css.cell.height.toFixed(0);this.coreService.triggerDataEvent(`${Gl.ESC}[6;${s};${i}t`)}}cancel(e,t){if(this.options.cancelEvents||t)return e.preventDefault(),e.stopPropagation(),!1}};var Qd=class{constructor(){this._addons=[]}dispose(){for(let e=this._addons.length-1;e>=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){let i={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(i),t.dispose=()=>this._wrappedAddonDispose(i),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let i=0;i<this._addons.length;i++)if(this._addons[i]===e){t=i;break}if(-1===t)throw new Error("Could not dispose an addon that has not been loaded");e.isDisposed=!0,e.dispose.apply(e.instance),this._addons.splice(t,1)}},eu=class{constructor(e){this._line=e}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(e,t){if(!(e<0||e>=this._line.length))return t?(this._line.loadCell(e,t),t):this._line.loadCell(e,new oo)}translateToString(e,t,i){return this._line.translateToString(e,t,i)}},tu=class{constructor(e,t){this._buffer=e,this.type=t}init(e){return this._buffer=e,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(e){let t=this._buffer.lines.get(e);if(t)return new eu(t)}getNullCell(){return new oo}},iu=class extends qo{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new da),this.onBufferChange=this._onBufferChange.event,this._normal=new tu(this._core.buffers.normal,"normal"),this._alternate=new tu(this._core.buffers.alt,"alternate"),this._core.buffers.onBufferActivate(()=>this._onBufferChange.fire(this.active))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw new Error("Active buffer is neither normal nor alternate")}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}},su=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,e=>t(e.toArray()))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,(e,i)=>t(e,i.toArray()))}addDcsHandler(e,t){return this.registerDcsHandler(e,t)}registerEscHandler(e,t){return this._core.registerEscHandler(e,t)}addEscHandler(e,t){return this.registerEscHandler(e,t)}registerOscHandler(e,t){return this._core.registerOscHandler(e,t)}addOscHandler(e,t){return this.registerOscHandler(e,t)}},ru=class{constructor(e){this._core=e}register(e){this._core.unicodeService.register(e)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(e){this._core.unicodeService.activeVersion=e}},nu=["cols","rows"],ou=0,au=class extends qo{constructor(e){super(),this._core=this._register(new Jd(e)),this._addonManager=this._register(new Qd),this._publicOptions={...this._core.options};let t=e=>this._core.options[e],i=(e,t)=>{this._checkReadonlyOptions(e),this._core.options[e]=t};for(let s in this._core.options){let e={get:t.bind(this,s),set:i.bind(this,s)};Object.defineProperty(this._publicOptions,s,e)}}_checkReadonlyOptions(e){if(nu.includes(e))throw new Error(`Option "${e}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw new Error("You must set the allowProposedApi option to true to use proposed API")}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||(this._parser=new su(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new ru(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||(this._buffer=this._register(new iu(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let e=this._core.coreService.decPrivateModes,t="none";switch(this._core.coreMouseService.activeProtocol){case"X10":t="x10";break;case"VT200":t="vt200";break;case"DRAG":t="drag";break;case"ANY":t="any"}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:t,originMode:e.origin,reverseWraparoundMode:e.reverseWraparound,sendFocusMode:e.sendFocus,synchronizedOutputMode:e.synchronizedOutput,wraparoundMode:e.wraparound}}get options(){return this._publicOptions}set options(e){for(let t in e)this._publicOptions[t]=e[t]}blur(){this._core.blur()}focus(){this._core.focus()}input(e,t=!0){this._core.input(e,t)}resize(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)}open(e){this._core.open(e)}attachCustomKeyEventHandler(e){this._core.attachCustomKeyEventHandler(e)}attachCustomWheelEventHandler(e){this._core.attachCustomWheelEventHandler(e)}registerLinkProvider(e){return this._core.registerLinkProvider(e)}registerCharacterJoiner(e){return this._checkProposedApi(),this._core.registerCharacterJoiner(e)}deregisterCharacterJoiner(e){this._checkProposedApi(),this._core.deregisterCharacterJoiner(e)}registerMarker(e=0){return this._verifyIntegers(e),this._core.registerMarker(e)}registerDecoration(e){return this._checkProposedApi(),this._verifyPositiveIntegers(e.x??0,e.width??0,e.height??0),this._core.registerDecoration(e)}hasSelection(){return this._core.hasSelection()}select(e,t,i){this._verifyIntegers(e,t,i),this._core.select(e,t,i)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(e,t){this._verifyIntegers(e,t),this._core.selectLines(e,t)}dispose(){super.dispose()}scrollLines(e){this._verifyIntegers(e),this._core.scrollLines(e)}scrollPages(e){this._verifyIntegers(e),this._core.scrollPages(e)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(e){this._verifyIntegers(e),this._core.scrollToLine(e)}clear(){this._core.clear()}write(e,t){this._core.write(e,t)}writeln(e,t){this._core.write(e),this._core.write("\r\n",t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return Un()},set promptLabel(e){Vn(e)},get tooMuchOutput(){return Yn()},set tooMuchOutput(e){Xn(e)}}}_verifyIntegers(...e){for(ou of e)if(ou===1/0||isNaN(ou)||ou%1!=0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...e){for(ou of e)if(ou&&(ou===1/0||isNaN(ou)||ou%1!=0||ou<0))throw new Error("This API only accepts positive integers")}},lu=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){var e;if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let t=this._terminal._core._renderService.dimensions;if(0===t.css.cell.width||0===t.css.cell.height)return;let i=0===this._terminal.options.scrollback?0:(null==(e=this._terminal.options.overviewRuler)?void 0:e.width)||14,s=window.getComputedStyle(this._terminal.element.parentElement),r=parseInt(s.getPropertyValue("height")),n=Math.max(0,parseInt(s.getPropertyValue("width"))),o=window.getComputedStyle(this._terminal.element),a=r-(parseInt(o.getPropertyValue("padding-top"))+parseInt(o.getPropertyValue("padding-bottom"))),l=n-(parseInt(o.getPropertyValue("padding-right"))+parseInt(o.getPropertyValue("padding-left")))-i;return{cols:Math.max(2,Math.floor(l/t.css.cell.width)),rows:Math.max(1,Math.floor(a/t.css.cell.height))}}},cu=new class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?_u.isErrorNoTelemetry(e)?new _u(e.message+"\n\n"+e.stack):new Error(e.message+"\n\n"+e.stack):e},0)}}addListener(e){return this.listeners.push(e),()=>{this._removeListener(e)}}emit(e){this.listeners.forEach(t=>{t(e)})}_removeListener(e){this.listeners.splice(this.listeners.indexOf(e),1)}setUnexpectedErrorHandler(e){this.unexpectedErrorHandler=e}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(e){this.unexpectedErrorHandler(e),this.emit(e)}onUnexpectedExternalError(e){this.unexpectedErrorHandler(e)}};function hu(e){(function(e){return e instanceof mu||e instanceof Error&&e.name===du&&e.message===du})(e)||cu.onUnexpectedError(e)}var du="Canceled";var uu,fu,pu,mu=class extends Error{constructor(){super(du),this.name=this.message}},_u=class e extends Error{constructor(e){super(e),this.name="CodeExpectedError"}static fromError(t){if(t instanceof e)return t;let i=new e;return i.message=t.message,i.stack=t.stack,i}static isErrorNoTelemetry(e){return"CodeExpectedError"===e.name}};function gu(e,t){let i,s=this,r=!1;return function(){return r||(r=!0,t||(i=e.apply(s,arguments))),i}}function vu(e){if(pu.is(e)){let t=[];for(let i of e)if(i)try{i.dispose()}catch(Nl){t.push(Nl)}if(1===t.length)throw t[0];if(t.length>1)throw new AggregateError(t,"Encountered errors while disposing of store");return Array.isArray(e)?[]:e}if(e)return e.dispose(),e}function yu(...e){return xu(()=>vu(e))}function xu(e){return{dispose:gu(()=>{e()})}}(fu=uu||(uu={})).isLessThan=function(e){return e<0},fu.isLessThanOrEqual=function(e){return e<=0},fu.isGreaterThan=function(e){return e>0},fu.isNeitherLessOrGreaterThan=function(e){return 0===e},fu.greaterThan=1,fu.lessThan=-1,fu.neitherLessOrGreaterThan=0,(e=>{function t(e){return e&&"object"==typeof e&&"function"==typeof e[Symbol.iterator]}e.is=t;let i=Object.freeze([]);function*s(e){yield e}e.empty=function(){return i},e.single=s,e.wrap=function(e){return t(e)?e:s(e)},e.from=function(e){return e||i},e.reverse=function*(e){for(let t=e.length-1;t>=0;t--)yield e[t]},e.isEmpty=function(e){return!e||!0===e[Symbol.iterator]().next().done},e.first=function(e){return e[Symbol.iterator]().next().value},e.some=function(e,t){let i=0;for(let s of e)if(t(s,i++))return!0;return!1},e.find=function(e,t){for(let i of e)if(t(i))return i},e.filter=function*(e,t){for(let i of e)t(i)&&(yield i)},e.map=function*(e,t){let i=0;for(let s of e)yield t(s,i++)},e.flatMap=function*(e,t){let i=0;for(let s of e)yield*t(s,i++)},e.concat=function*(...e){for(let t of e)yield*t},e.reduce=function(e,t,i){let s=i;for(let r of e)s=t(s,r);return s},e.slice=function*(e,t,i=e.length){for(t<0&&(t+=e.length),i<0?i+=e.length:i>e.length&&(i=e.length);t<i;t++)yield e[t]},e.consume=function(t,i=Number.POSITIVE_INFINITY){let s=[];if(0===i)return[s,t];let r=t[Symbol.iterator]();for(let n=0;n<i;n++){let t=r.next();if(t.done)return[s,e.empty()];s.push(t.value)}return[s,{[Symbol.iterator]:()=>r}]},e.asyncToArray=async function(e){let t=[];for await(let i of e)t.push(i);return Promise.resolve(t)}})(pu||(pu={}));var bu=class e{constructor(){this._toDispose=new Set,this._isDisposed=!1}dispose(){this._isDisposed||(this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(0!==this._toDispose.size)try{vu(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw new Error("Cannot register a disposable on itself!");return this._isDisposed?e.DISABLE_DISPOSED_WARNING||console.warn(new Error("Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!").stack):this._toDispose.add(t),t}delete(e){if(e){if(e===this)throw new Error("Cannot dispose a disposable on itself!");this._toDispose.delete(e),e.dispose()}}deleteAndLeak(e){e&&this._toDispose.has(e)&&this._toDispose.delete(e)}};bu.DISABLE_DISPOSED_WARNING=!1;var wu=bu,Su=class{constructor(){this._store=new wu,this._store}dispose(){this._store.dispose()}_register(e){if(e===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(e)}};Su.None=Object.freeze({dispose(){}});var Cu,ku=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(e){var t;this._isDisposed||e===this._value||(null==(t=this._value)||t.dispose(),this._value=e)}clear(){this.value=void 0}dispose(){var e;this._isDisposed=!0,null==(e=this._value)||e.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e}},Eu=globalThis.performance&&"function"==typeof globalThis.performance.now,Nu=class e{static create(t){return new e(t)}constructor(e){this._now=Eu&&!1===e?Date.now:globalThis.performance.now.bind(globalThis.performance),this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=this._now(),this._stopTime=-1}elapsed(){return-1!==this._stopTime?this._stopTime-this._startTime:this._now()-this._startTime}};(e=>{function t(e){return(t,i=null,s)=>{let r,n=!1;return r=e(e=>{if(!n)return r?r.dispose():n=!0,t.call(i,e)},null,s),n&&r.dispose(),r}}function i(e,t,i){return r((i,s=null,r)=>e(e=>i.call(s,t(e)),null,r),i)}function s(e,t,i){return r((i,s=null,r)=>e(e=>t(e)&&i.call(s,e),null,r),i)}function r(e,t){let i,s=new Au({onWillAddFirstListener(){i=e(s.fire,s)},onDidRemoveLastListener(){null==i||i.dispose()}});return null==t||t.add(s),s.event}function n(e,t,i=100,s=!1,r=!1,n,o){let a,l,c,h,d=0,u=new Au({leakWarningThreshold:n,onWillAddFirstListener(){a=e(e=>{d++,l=t(l,e),s&&!c&&(u.fire(l),l=void 0),h=()=>{let e=l;l=void 0,c=void 0,(!s||d>1)&&u.fire(e),d=0},"number"==typeof i?(clearTimeout(c),c=setTimeout(h,i)):void 0===c&&(c=0,queueMicrotask(h))})},onWillRemoveListener(){r&&d>0&&(null==h||h())},onDidRemoveLastListener(){h=void 0,a.dispose()}});return null==o||o.add(u),u.event}e.None=()=>Su.None,e.defer=function(e,t){return n(e,()=>{},0,void 0,!0,void 0,t)},e.once=t,e.map=i,e.forEach=function(e,t,i){return r((i,s=null,r)=>e(e=>{t(e),i.call(s,e)},null,r),i)},e.filter=s,e.signal=function(e){return e},e.any=function(...e){return(t,i=null,s)=>{let r=yu(...e.map(e=>e(e=>t.call(i,e))));return function(e,t){return t instanceof Array?t.push(e):t&&t.add(e),e}(r,s)}},e.reduce=function(e,t,s,r){let n=s;return i(e,e=>(n=t(n,e),n),r)},e.debounce=n,e.accumulate=function(t,i=0,s){return e.debounce(t,(e,t)=>e?(e.push(t),e):[t],i,void 0,!0,void 0,s)},e.latch=function(e,t=(e,t)=>e===t,i){let r,n=!0;return s(e,e=>{let i=n||!t(e,r);return n=!1,r=e,i},i)},e.split=function(t,i,s){return[e.filter(t,i,s),e.filter(t,e=>!i(e),s)]},e.buffer=function(e,t=!1,i=[],s){let r=i.slice(),n=e(e=>{r?r.push(e):a.fire(e)});s&&s.add(n);let o=()=>{null==r||r.forEach(e=>a.fire(e)),r=null},a=new Au({onWillAddFirstListener(){n||(n=e(e=>a.fire(e)),s&&s.add(n))},onDidAddFirstListener(){r&&(t?setTimeout(o):o())},onDidRemoveLastListener(){n&&n.dispose(),n=null}});return s&&s.add(a),a.event},e.chain=function(e,t){return(i,s,r)=>{let n=t(new a);return e(function(e){let t=n.evaluate(e);t!==o&&i.call(s,t)},void 0,r)}};let o=Symbol("HaltChainable");class a{constructor(){this.steps=[]}map(e){return this.steps.push(e),this}forEach(e){return this.steps.push(t=>(e(t),t)),this}filter(e){return this.steps.push(t=>e(t)?t:o),this}reduce(e,t){let i=t;return this.steps.push(t=>(i=e(i,t),i)),this}latch(e=(e,t)=>e===t){let t,i=!0;return this.steps.push(s=>{let r=i||!e(s,t);return i=!1,t=s,r?s:o}),this}evaluate(e){for(let t of this.steps)if((e=t(e))===o)break;return e}}e.fromNodeEventEmitter=function(e,t,i=e=>e){let s=(...e)=>r.fire(i(...e)),r=new Au({onWillAddFirstListener:()=>e.on(t,s),onDidRemoveLastListener:()=>e.removeListener(t,s)});return r.event},e.fromDOMEventEmitter=function(e,t,i=e=>e){let s=(...e)=>r.fire(i(...e)),r=new Au({onWillAddFirstListener:()=>e.addEventListener(t,s),onDidRemoveLastListener:()=>e.removeEventListener(t,s)});return r.event},e.toPromise=function(e){return new Promise(i=>t(e)(i))},e.fromPromise=function(e){let t=new Au;return e.then(e=>{t.fire(e)},()=>{t.fire(void 0)}).finally(()=>{t.dispose()}),t.event},e.forward=function(e,t){return e(e=>t.fire(e))},e.runAndSubscribe=function(e,t,i){return t(i),e(e=>t(e))};class l{constructor(e,t){this._observable=e,this._counter=0,this._hasChanged=!1;let i={onWillAddFirstListener:()=>{e.addObserver(this)},onDidRemoveLastListener:()=>{e.removeObserver(this)}};this.emitter=new Au(i),t&&t.add(this.emitter)}beginUpdate(e){this._counter++}handlePossibleChange(e){}handleChange(e,t){this._hasChanged=!0}endUpdate(e){this._counter--,0===this._counter&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}e.fromObservable=function(e,t){return new l(e,t).emitter.event},e.fromObservableLight=function(e){return(t,i,s)=>{let r=0,n=!1,o={beginUpdate(){r++},endUpdate(){r--,0===r&&(e.reportChanges(),n&&(n=!1,t.call(i)))},handlePossibleChange(){},handleChange(){n=!0}};e.addObserver(o),e.reportChanges();let a={dispose(){e.removeObserver(o)}};return s instanceof wu?s.add(a):Array.isArray(s)&&s.push(a),a}}})(Cu||(Cu={}));var Mu=class e{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${e._idPool++}`,e.all.add(this)}start(e){this._stopWatch=new Nu,this.listenerCount=e}stop(){if(this._stopWatch){let e=this._stopWatch.elapsed();this.durations.push(e),this.elapsedOverall+=e,this.invocationCount+=1,this._stopWatch=void 0}}};Mu.all=new Set,Mu._idPool=0;var ju=Mu,Du=class e{constructor(t,i,s=(e._idPool++).toString(16).padStart(3,"0")){this._errorHandler=t,this.threshold=i,this.name=s,this._warnCountdown=0}dispose(){var e;null==(e=this._stacks)||e.clear()}check(e,t){let i=this.threshold;if(i<=0||t<i)return;this._stacks||(this._stacks=new Map);let s=this._stacks.get(e.value)||0;if(this._stacks.set(e.value,s+1),this._warnCountdown-=1,this._warnCountdown<=0){this._warnCountdown=.5*i;let[e,s]=this.getMostFrequentStack(),r=`[${this.name}] potential listener LEAK detected, having ${t} listeners already. MOST frequent listener (${s}):`;console.warn(r),console.warn(e);let n=new Iu(r,e);this._errorHandler(n)}return()=>{let t=this._stacks.get(e.value)||0;this._stacks.set(e.value,t-1)}}getMostFrequentStack(){if(!this._stacks)return;let e,t=0;for(let[i,s]of this._stacks)(!e||t<s)&&(e=[i,s],t=s);return e}};Du._idPool=1;var Ru,Pu=Du,Lu=class e{constructor(e){this.value=e}static create(){let t=new Error;return new e(t.stack??"")}print(){console.warn(this.value.split("\n").slice(2).join("\n"))}},Iu=class extends Error{constructor(e,t){super(e),this.name="ListenerLeakError",this.stack=t}},Tu=class extends Error{constructor(e,t){super(e),this.name="ListenerRefusalError",this.stack=t}},Bu=0,Ou=class{constructor(e){this.value=e,this.id=Bu++}},Au=class{constructor(e){var t,i,s,r;this._size=0,this._options=e,this._leakageMon=(null==(t=this._options)?void 0:t.leakWarningThreshold)?new Pu((null==e?void 0:e.onListenerError)??hu,(null==(i=this._options)?void 0:i.leakWarningThreshold)??-1):void 0,this._perfMon=(null==(s=this._options)?void 0:s._profName)?new ju(this._options._profName):void 0,this._deliveryQueue=null==(r=this._options)?void 0:r.deliveryQueue}dispose(){var e,t,i,s;this._disposed||(this._disposed=!0,(null==(e=this._deliveryQueue)?void 0:e.current)===this&&this._deliveryQueue.reset(),this._listeners&&(this._listeners=void 0,this._size=0),null==(i=null==(t=this._options)?void 0:t.onDidRemoveLastListener)||i.call(t),null==(s=this._leakageMon)||s.dispose())}get event(){return this._event??(this._event=(e,t,i)=>{var s,r,n,o,a;if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let e=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(e);let t=this._leakageMon.getMostFrequentStack()??["UNKNOWN stack",-1],i=new Tu(`${e}. HINT: Stack shows most frequent listener (${t[1]}-times)`,t[0]);return((null==(s=this._options)?void 0:s.onListenerError)||hu)(i),Su.None}if(this._disposed)return Su.None;t&&(e=e.bind(t));let l,c=new Ou(e);this._leakageMon&&this._size>=Math.ceil(.2*this._leakageMon.threshold)&&(c.stack=Lu.create(),l=this._leakageMon.check(c.stack,this._size+1)),this._listeners?this._listeners instanceof Ou?(this._deliveryQueue??(this._deliveryQueue=new zu),this._listeners=[this._listeners,c]):this._listeners.push(c):(null==(n=null==(r=this._options)?void 0:r.onWillAddFirstListener)||n.call(r,this),this._listeners=c,null==(a=null==(o=this._options)?void 0:o.onDidAddFirstListener)||a.call(o,this)),this._size++;let h=xu(()=>{null==l||l(),this._removeListener(c)});return i instanceof wu?i.add(h):Array.isArray(i)&&i.push(h),h}),this._event}_removeListener(e){var t,i,s,r;if(null==(i=null==(t=this._options)?void 0:t.onWillRemoveListener)||i.call(t,this),!this._listeners)return;if(1===this._size)return this._listeners=void 0,null==(r=null==(s=this._options)?void 0:s.onDidRemoveLastListener)||r.call(s,this),void(this._size=0);let n=this._listeners,o=n.indexOf(e);if(-1===o)throw console.log("disposed?",this._disposed),console.log("size?",this._size),console.log("arr?",JSON.stringify(this._listeners)),new Error("Attempted to dispose unknown listener");this._size--,n[o]=void 0;let a=this._deliveryQueue.current===this;if(2*this._size<=n.length){let e=0;for(let t=0;t<n.length;t++)n[t]?n[e++]=n[t]:a&&(this._deliveryQueue.end--,e<this._deliveryQueue.i&&this._deliveryQueue.i--);n.length=e}}_deliver(e,t){var i;if(!e)return;let s=(null==(i=this._options)?void 0:i.onListenerError)||hu;if(s)try{e.value(t)}catch(Pa){s(Pa)}else e.value(t)}_deliverQueue(e){let t=e.current._listeners;for(;e.i<e.end;)this._deliver(t[e.i++],e.value);e.reset()}fire(e){var t,i,s,r;if((null==(t=this._deliveryQueue)?void 0:t.current)&&(this._deliverQueue(this._deliveryQueue),null==(i=this._perfMon)||i.stop()),null==(s=this._perfMon)||s.start(this._size),this._listeners)if(this._listeners instanceof Ou)this._deliver(this._listeners,e);else{let t=this._deliveryQueue;t.enqueue(this,e,this._listeners.length),this._deliverQueue(t)}null==(r=this._perfMon)||r.stop()}hasListeners(){return this._size>0}},zu=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,i){this.i=0,this.end=i,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},$u=Object.freeze(function(e,t){let i=setTimeout(e.bind(t),0);return{dispose(){clearTimeout(i)}}});(e=>{e.isCancellationToken=function(t){return t===e.None||t===e.Cancelled||t instanceof Fu||!(!t||"object"!=typeof t)&&("boolean"==typeof t.isCancellationRequested&&"function"==typeof t.onCancellationRequested)},e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:Cu.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:$u})})(Ru||(Ru={}));var Hu,Wu,Fu=class{constructor(){this._isCancelled=!1,this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?$u:(this._emitter||(this._emitter=new Au),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}},Ku="en",Uu=Ku,Vu=globalThis;typeof Vu.vscode<"u"&&typeof Vu.vscode.process<"u"?Wu=Vu.vscode.process:typeof process<"u"&&"string"==typeof(null==(s=null==process?void 0:process.versions)?void 0:s.node)&&(Wu=process);var qu="string"==typeof(null==(r=null==Wu?void 0:Wu.versions)?void 0:r.electron)&&"renderer"===(null==Wu?void 0:Wu.type);if("object"==typeof Wu){Wu.platform,Wu.platform,"linux"===Wu.platform&&!!Wu.env.SNAP&&Wu.env.SNAP_REVISION,!!Wu.env.CI||Wu.env.BUILD_ARTIFACTSTAGINGDIRECTORY,Uu=Ku;let e=Wu.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);t.userLocale,t.osLocale,Uu=t.resolvedLanguage||Ku,null==(n=t.languagePack)?void 0:n.translationsConfigFile}catch{}}else"object"!=typeof navigator||qu?console.error("Unable to resolve platform."):((Hu=navigator.userAgent).indexOf("Windows"),Hu.indexOf("Macintosh"),(Hu.indexOf("Macintosh")>=0||Hu.indexOf("iPad")>=0||Hu.indexOf("iPhone")>=0)&&!!navigator.maxTouchPoints&&navigator.maxTouchPoints,Hu.indexOf("Linux")>=0,null==Hu||Hu.indexOf("Mobi"),Uu=globalThis._VSCODE_NLS_LANGUAGE||Ku,navigator.language.toLowerCase());var Yu,Xu=Hu,Gu=Uu;(e=>{e.value=function(){return Gu},e.isDefaultVariant=function(){return 2===Gu.length?"en"===Gu:Gu.length>=3&&("e"===Gu[0]&&"n"===Gu[1]&&"-"===Gu[2])},e.isDefault=function(){return"en"===Gu}})(Yu||(Yu={}));var Zu="function"==typeof Vu.postMessage&&!Vu.importScripts;(()=>{if(Zu){let e=[];Vu.addEventListener("message",t=>{if(t.data&&t.data.vscodeScheduleAsyncWork)for(let i=0,s=e.length;i<s;i++){let s=e[i];if(s.id===t.data.vscodeScheduleAsyncWork)return e.splice(i,1),void s.callback()}});let t=0;return i=>{let s=++t;e.push({id:s,callback:i}),Vu.postMessage({vscodeScheduleAsyncWork:s},"*")}}})();var Ju,Qu,ef=!!(Xu&&Xu.indexOf("Chrome")>=0);function tf(e,t=0,i){let s=setTimeout(()=>{e()},t);return xu(()=>{clearTimeout(s)})}Xu&&Xu.indexOf("Firefox"),!ef&&Xu&&Xu.indexOf("Safari"),Xu&&Xu.indexOf("Edg/"),Xu&&Xu.indexOf("Android"),(Qu=Ju||(Ju={})).settled=async function(e){let t,i=await Promise.all(e.map(e=>e.then(e=>e,e=>{t||(t=e)})));if(typeof t<"u")throw t;return i},Qu.withAsyncBody=function(e){return new Promise(async(t,i)=>{try{await e(t,i)}catch(s){i(s)}})};var sf=class e{static fromArray(t){return new e(e=>{e.emitMany(t)})}static fromPromise(t){return new e(async e=>{e.emitMany(await t)})}static fromPromises(t){return new e(async e=>{await Promise.all(t.map(async t=>e.emitOne(await t)))})}static merge(t){return new e(async e=>{await Promise.all(t.map(async t=>{for await(let i of t)e.emitOne(i)}))})}constructor(e,t){this._state=0,this._results=[],this._error=null,this._onReturn=t,this._onStateChanged=new Au,queueMicrotask(async()=>{let t={emitOne:e=>this.emitOne(e),emitMany:e=>this.emitMany(e),reject:e=>this.reject(e)};try{await Promise.resolve(e(t)),this.resolve()}catch(Pa){this.reject(Pa)}finally{t.emitOne=void 0,t.emitMany=void 0,t.reject=void 0}})}[Symbol.asyncIterator](){let e=0;return{next:async()=>{for(;;){if(2===this._state)throw this._error;if(e<this._results.length)return{done:!1,value:this._results[e++]};if(1===this._state)return{done:!0,value:void 0};await Cu.toPromise(this._onStateChanged.event)}},return:async()=>{var e;return null==(e=this._onReturn)||e.call(this),{done:!0,value:void 0}}}}static map(t,i){return new e(async e=>{for await(let s of t)e.emitOne(i(s))})}map(t){return e.map(this,t)}static filter(t,i){return new e(async e=>{for await(let s of t)i(s)&&e.emitOne(s)})}filter(t){return e.filter(this,t)}static coalesce(t){return e.filter(t,e=>!!e)}coalesce(){return e.coalesce(this)}static async toPromise(e){let t=[];for await(let i of e)t.push(i);return t}toPromise(){return e.toPromise(this)}emitOne(e){0===this._state&&(this._results.push(e),this._onStateChanged.fire())}emitMany(e){0===this._state&&(this._results=this._results.concat(e),this._onStateChanged.fire())}resolve(){0===this._state&&(this._state=1,this._onStateChanged.fire())}reject(e){0===this._state&&(this._state=2,this._error=e,this._onStateChanged.fire())}};sf.EMPTY=sf.fromArray([]);var rf=class extends Su{constructor(e){super(),this._terminal=e,this._linesCacheTimeout=this._register(new ku),this._linesCacheDisposables=this._register(new ku),this._register(xu(()=>this._destroyLinesCache()))}initLinesCache(){this._linesCache||(this._linesCache=new Array(this._terminal.buffer.active.length),this._linesCacheDisposables.value=yu(this._terminal.onLineFeed(()=>this._destroyLinesCache()),this._terminal.onCursorMove(()=>this._destroyLinesCache()),this._terminal.onResize(()=>this._destroyLinesCache()))),this._linesCacheTimeout.value=tf(()=>this._destroyLinesCache(),15e3)}_destroyLinesCache(){this._linesCache=void 0,this._linesCacheDisposables.clear(),this._linesCacheTimeout.clear()}getLineFromCache(e){var t;return null==(t=this._linesCache)?void 0:t[e]}setLineInCache(e,t){this._linesCache&&(this._linesCache[e]=t)}translateBufferLineToStringWithWrap(e,t){var i;let s=[],r=[0],n=this._terminal.buffer.active.getLine(e);for(;n;){let o=this._terminal.buffer.active.getLine(e+1),a=!!o&&o.isWrapped,l=n.translateToString(!a&&t);if(a&&o){let e=n.getCell(n.length-1);e&&0===e.getCode()&&1===e.getWidth()&&2===(null==(i=o.getCell(0))?void 0:i.getWidth())&&(l=l.slice(0,-1))}if(s.push(l),!a)break;r.push(r[r.length-1]+l.length),e++,n=o}return[s.join(""),r]}},nf=class{get cachedSearchTerm(){return this._cachedSearchTerm}set cachedSearchTerm(e){this._cachedSearchTerm=e}get lastSearchOptions(){return this._lastSearchOptions}set lastSearchOptions(e){this._lastSearchOptions=e}isValidSearchTerm(e){return!!(e&&e.length>0)}didOptionsChange(e){return!this._lastSearchOptions||!!e&&(this._lastSearchOptions.caseSensitive!==e.caseSensitive||this._lastSearchOptions.regex!==e.regex||this._lastSearchOptions.wholeWord!==e.wholeWord)}shouldUpdateHighlighting(e,t){return!!(null==t?void 0:t.decorations)&&(void 0===this._cachedSearchTerm||e!==this._cachedSearchTerm||this.didOptionsChange(t))}clearCachedTerm(){this._cachedSearchTerm=void 0}reset(){this._cachedSearchTerm=void 0,this._lastSearchOptions=void 0}},of=class{constructor(e,t){this._terminal=e,this._lineCache=t}find(e,t,i,s){if(!e||0===e.length)return void this._terminal.clearSelection();if(i>this._terminal.cols)throw new Error(`Invalid col: ${i} to search in terminal of ${this._terminal.cols} cols`);this._lineCache.initLinesCache();let r={startRow:t,startCol:i},n=this._findInLine(e,r,s);if(!n)for(let o=t+1;o<this._terminal.buffer.active.baseY+this._terminal.rows&&(r.startRow=o,r.startCol=0,n=this._findInLine(e,r,s),!n);o++);return n}findNextWithSelection(e,t,i){if(!e||0===e.length)return void this._terminal.clearSelection();let s=this._terminal.getSelectionPosition();this._terminal.clearSelection();let r=0,n=0;s&&(i===e?(r=s.end.x,n=s.end.y):(r=s.start.x,n=s.start.y)),this._lineCache.initLinesCache();let o={startRow:n,startCol:r},a=this._findInLine(e,o,t);if(!a)for(let l=n+1;l<this._terminal.buffer.active.baseY+this._terminal.rows&&(o.startRow=l,o.startCol=0,a=this._findInLine(e,o,t),!a);l++);if(!a&&0!==n)for(let l=0;l<n&&(o.startRow=l,o.startCol=0,a=this._findInLine(e,o,t),!a);l++);return!a&&s&&(o.startRow=s.start.y,o.startCol=0,a=this._findInLine(e,o,t)),a}findPreviousWithSelection(e,t,i){if(!e||0===e.length)return void this._terminal.clearSelection();let s=this._terminal.getSelectionPosition();this._terminal.clearSelection();let r=this._terminal.buffer.active.baseY+this._terminal.rows-1,n=this._terminal.cols,o=!0;this._lineCache.initLinesCache();let a,l={startRow:r,startCol:n};if(s&&(l.startRow=r=s.start.y,l.startCol=n=s.start.x,i!==e&&(a=this._findInLine(e,l,t,!1),a||(l.startRow=r=s.end.y,l.startCol=n=s.end.x))),a||(a=this._findInLine(e,l,t,o)),!a){l.startCol=Math.max(l.startCol,this._terminal.cols);for(let i=r-1;i>=0&&(l.startRow=i,a=this._findInLine(e,l,t,o),!a);i--);}if(!a&&r!==this._terminal.buffer.active.baseY+this._terminal.rows-1)for(let c=this._terminal.buffer.active.baseY+this._terminal.rows-1;c>=r&&(l.startRow=c,a=this._findInLine(e,l,t,o),!a);c--);return a}_isWholeWord(e,t,i){return(0===e||" ~!@#$%^&*()+`-=[]{}|\\;:\"',./<>?".includes(t[e-1]))&&(e+i.length===t.length||" ~!@#$%^&*()+`-=[]{}|\\;:\"',./<>?".includes(t[e+i.length]))}_findInLine(e,t,i={},s=!1){var r;let n=t.startRow,o=t.startCol;if(null==(r=this._terminal.buffer.active.getLine(n))?void 0:r.isWrapped)return s?void(t.startCol+=this._terminal.cols):(t.startRow--,t.startCol+=this._terminal.cols,this._findInLine(e,t,i));let a=this._lineCache.getLineFromCache(n);a||(a=this._lineCache.translateBufferLineToStringWithWrap(n,!0),this._lineCache.setLineInCache(n,a));let[l,c]=a,h=this._bufferColsToStringOffset(n,o),d=e,u=l;i.regex||(d=i.caseSensitive?e:e.toLowerCase(),u=i.caseSensitive?l:l.toLowerCase());let f=-1;if(i.regex){let t,r=RegExp(d,i.caseSensitive?"g":"gi");if(s)for(;t=r.exec(u.slice(0,h));)f=r.lastIndex-t[0].length,e=t[0],r.lastIndex-=e.length-1;else t=r.exec(u.slice(h)),t&&t[0].length>0&&(f=h+(r.lastIndex-t[0].length),e=t[0])}else s?h-d.length>=0&&(f=u.lastIndexOf(d,h-d.length)):f=u.indexOf(d,h);if(f>=0){if(i.wholeWord&&!this._isWholeWord(f,u,e))return;let t=0;for(;t<c.length-1&&f>=c[t+1];)t++;let s=t;for(;s<c.length-1&&f+e.length>=c[s+1];)s++;let r=f-c[t],o=f+e.length-c[s],a=this._stringLengthToBufferSize(n+t,r);return{term:e,col:a,row:n+t,size:this._stringLengthToBufferSize(n+s,o)-a+this._terminal.cols*(s-t)}}}_stringLengthToBufferSize(e,t){let i=this._terminal.buffer.active.getLine(e);if(!i)return 0;for(let s=0;s<t;s++){let e=i.getCell(s);if(!e)break;let r=e.getChars();r.length>1&&(t-=r.length-1);let n=i.getCell(s+1);n&&0===n.getWidth()&&t++}return t}_bufferColsToStringOffset(e,t){let i=e,s=0,r=this._terminal.buffer.active.getLine(i);for(;t>0&&r;){for(let e=0;e<t&&e<this._terminal.cols;e++){let t=r.getCell(e);if(!t)break;t.getWidth()&&(s+=0===t.getCode()?1:t.getChars().length)}if(i++,r=this._terminal.buffer.active.getLine(i),r&&!r.isWrapped)break;t-=this._terminal.cols}return s}},af=class extends Su{constructor(e){super(),this._terminal=e,this._highlightDecorations=[],this._highlightedLines=new Set,this._register(xu(()=>this.clearHighlightDecorations()))}createHighlightDecorations(e,t){this.clearHighlightDecorations();for(let i of e){let e=this._createResultDecorations(i,t,!1);if(e)for(let t of e)this._storeDecoration(t,i)}}createActiveDecoration(e,t){let i=this._createResultDecorations(e,t,!0);if(i)return{decorations:i,match:e,dispose(){vu(i)}}}clearHighlightDecorations(){vu(this._highlightDecorations),this._highlightDecorations=[],this._highlightedLines.clear()}_storeDecoration(e,t){this._highlightedLines.add(e.marker.line),this._highlightDecorations.push({decoration:e,match:t,dispose(){e.dispose()}})}_applyStyles(e,t,i){e.classList.contains("xterm-find-result-decoration")||(e.classList.add("xterm-find-result-decoration"),t&&(e.style.outline=`1px solid ${t}`)),i&&e.classList.add("xterm-find-active-result-decoration")}_createResultDecorations(e,t,i){let s=[],r=e.col,n=e.size,o=-this._terminal.buffer.active.baseY-this._terminal.buffer.active.cursorY+e.row;for(;n>0;){let e=Math.min(this._terminal.cols-r,n);s.push([o,r,e]),r=0,n-=e,o++}let a=[];for(let l of s){let e=this._terminal.registerMarker(l[0]),s=this._terminal.registerDecoration({marker:e,x:l[1],width:l[2],backgroundColor:i?t.activeMatchBackground:t.matchBackground,overviewRulerOptions:this._highlightedLines.has(e.line)?void 0:{color:i?t.activeMatchColorOverviewRuler:t.matchOverviewRuler,position:"center"}});if(s){let r=[];r.push(e),r.push(s.onRender(e=>this._applyStyles(e,i?t.activeMatchBorder:t.matchBorder,!1))),r.push(s.onDispose(()=>vu(r))),a.push(s)}}return 0===a.length?void 0:a}},lf=class extends Su{constructor(){super(...arguments),this._searchResults=[],this._onDidChangeResults=this._register(new Au)}get onDidChangeResults(){return this._onDidChangeResults.event}get searchResults(){return this._searchResults}get selectedDecoration(){return this._selectedDecoration}set selectedDecoration(e){this._selectedDecoration=e}updateResults(e,t){this._searchResults=e.slice(0,t)}clearResults(){this._searchResults=[]}clearSelectedDecoration(){this._selectedDecoration&&(this._selectedDecoration.dispose(),this._selectedDecoration=void 0)}findResultIndex(e){for(let t=0;t<this._searchResults.length;t++){let i=this._searchResults[t];if(i.row===e.row&&i.col===e.col&&i.size===e.size)return t}return-1}fireResultsChanged(e){if(!e)return;let t=-1;this._selectedDecoration&&(t=this.findResultIndex(this._selectedDecoration.match)),this._onDidChangeResults.fire({resultIndex:t,resultCount:this._searchResults.length})}reset(){this.clearSelectedDecoration(),this.clearResults()}},cf=class extends Su{constructor(e){super(),this._highlightTimeout=this._register(new ku),this._lineCache=this._register(new ku),this._state=new nf,this._resultTracker=this._register(new lf),this._highlightLimit=(null==e?void 0:e.highlightLimit)??1e3}get onDidChangeResults(){return this._resultTracker.onDidChangeResults}activate(e){this._terminal=e,this._lineCache.value=new rf(e),this._engine=new of(e,this._lineCache.value),this._decorationManager=new af(e),this._register(this._terminal.onWriteParsed(()=>this._updateMatches())),this._register(this._terminal.onResize(()=>this._updateMatches())),this._register(xu(()=>this.clearDecorations()))}_updateMatches(){var e;this._highlightTimeout.clear(),this._state.cachedSearchTerm&&(null==(e=this._state.lastSearchOptions)?void 0:e.decorations)&&(this._highlightTimeout.value=tf(()=>{let e=this._state.cachedSearchTerm;this._state.clearCachedTerm(),this.findPrevious(e,{...this._state.lastSearchOptions,incremental:!0},{noScroll:!0})},200))}clearDecorations(e){var t;this._resultTracker.clearSelectedDecoration(),null==(t=this._decorationManager)||t.clearHighlightDecorations(),this._resultTracker.clearResults(),e||this._state.clearCachedTerm()}clearActiveDecoration(){this._resultTracker.clearSelectedDecoration()}findNext(e,t,i){if(!this._terminal||!this._engine)throw new Error("Cannot use addon until it has been loaded");this._state.lastSearchOptions=t,this._state.shouldUpdateHighlighting(e,t)&&this._highlightAllMatches(e,t);let s=this._findNextAndSelect(e,t,i);return this._fireResults(t),this._state.cachedSearchTerm=e,s}_highlightAllMatches(e,t){if(!this._terminal||!this._engine||!this._decorationManager)throw new Error("Cannot use addon until it has been loaded");if(!this._state.isValidSearchTerm(e))return void this.clearDecorations();this.clearDecorations(!0);let i,s=[],r=this._engine.find(e,0,0,t);for(;r&&((null==i?void 0:i.row)!==r.row||(null==i?void 0:i.col)!==r.col)&&!(s.length>=this._highlightLimit);)i=r,s.push(i),r=this._engine.find(e,i.col+i.term.length>=this._terminal.cols?i.row+1:i.row,i.col+i.term.length>=this._terminal.cols?0:i.col+1,t);this._resultTracker.updateResults(s,this._highlightLimit),t.decorations&&this._decorationManager.createHighlightDecorations(s,t.decorations)}_findNextAndSelect(e,t,i){if(!this._terminal||!this._engine)return!1;if(!this._state.isValidSearchTerm(e))return this._terminal.clearSelection(),this.clearDecorations(),!1;let s=this._engine.findNextWithSelection(e,t,this._state.cachedSearchTerm);return this._selectResult(s,null==t?void 0:t.decorations,null==i?void 0:i.noScroll)}findPrevious(e,t,i){if(!this._terminal||!this._engine)throw new Error("Cannot use addon until it has been loaded");this._state.lastSearchOptions=t,this._state.shouldUpdateHighlighting(e,t)&&this._highlightAllMatches(e,t);let s=this._findPreviousAndSelect(e,t,i);return this._fireResults(t),this._state.cachedSearchTerm=e,s}_fireResults(e){this._resultTracker.fireResultsChanged(!!(null==e?void 0:e.decorations))}_findPreviousAndSelect(e,t,i){if(!this._terminal||!this._engine)return!1;if(!this._state.isValidSearchTerm(e))return this._terminal.clearSelection(),this.clearDecorations(),!1;let s=this._engine.findPreviousWithSelection(e,t,this._state.cachedSearchTerm);return this._selectResult(s,null==t?void 0:t.decorations,null==i?void 0:i.noScroll)}_selectResult(e,t,i){if(!this._terminal||!this._decorationManager)return!1;if(this._resultTracker.clearSelectedDecoration(),!e)return this._terminal.clearSelection(),!1;if(this._terminal.select(e.col,e.row,e.size),t){let i=this._decorationManager.createActiveDecoration(e,t);i&&(this._resultTracker.selectedDecoration=i)}if(!i&&(e.row>=this._terminal.buffer.active.viewportY+this._terminal.rows||e.row<this._terminal.buffer.active.viewportY)){let t=e.row-this._terminal.buffer.active.viewportY;t-=Math.floor(this._terminal.rows/2),this._terminal.scrollLines(t)}return!0}};const hf={background:"#09090b",foreground:"#e4e4e7",cursor:"#a1a1aa",cursorAccent:"#09090b",selectionBackground:"#3f3f46",black:"#18181b",brightBlack:"#3f3f46",red:"#ef4444",brightRed:"#f87171",green:"#22c55e",brightGreen:"#4ade80",yellow:"#eab308",brightYellow:"#facc15",blue:"#3b82f6",brightBlue:"#60a5fa",magenta:"#a855f7",brightMagenta:"#c084fc",cyan:"#06b6d4",brightCyan:"#22d3ee",white:"#e4e4e7",brightWhite:"#f4f4f5"},df={background:"#ffffff",foreground:"#1c1c1c",cursor:"#6b7280",cursorAccent:"#ffffff",selectionBackground:"#d1d5db",black:"#1c1c1c",brightBlack:"#6b7280",red:"#dc2626",brightRed:"#ef4444",green:"#16a34a",brightGreen:"#22c55e",yellow:"#ca8a04",brightYellow:"#eab308",blue:"#2563eb",brightBlue:"#3b82f6",magenta:"#9333ea",brightMagenta:"#a855f7",cyan:"#0891b2",brightCyan:"#06b6d4",white:"#e5e7eb",brightWhite:"#f9fafb"},uf=h.forwardRef(({onInput:e,onResize:t,onReady:i,cliTool:s="claude"},r)=>{const n=h.useRef(null),o=h.useRef(null),a=h.useRef(null),l=h.useRef(null),c=h.useRef(e),u=h.useRef(t),f=h.useRef(i),p=h.useRef(!1),m=h.useRef(null);c.current=e,u.current=t,f.current=i;const{resolved:g}=d();return h.useImperativeHandle(r,()=>({write:e=>{var t;null==(t=o.current)||t.write(e)},reset:()=>{const e=o.current;e&&(e.reset(),e.clear())},search:(e,t)=>{var i;return(null==(i=l.current)?void 0:i.findNext(e,t))??!1},searchNext:(e,t)=>{var i;return(null==(i=l.current)?void 0:i.findNext(e,t))??!1},searchPrevious:(e,t)=>{var i;return(null==(i=l.current)?void 0:i.findPrevious(e,t))??!1},clearSearch:()=>{var e;null==(e=l.current)||e.clearDecorations()}})),h.useEffect(()=>{if(!n.current)return;const e=new au({theme:"dark"===g?hf:df,fontFamily:'"JetBrains Mono", "Fira Code", "Cascadia Code", Menlo, Consolas, monospace',fontSize:13,lineHeight:1.5,cursorBlink:!0,convertEol:!1,scrollback:5e3,allowProposedApi:!0}),t=new lu;e.loadAddon(t);const i=new cf;e.loadAddon(i),l.current=i,e.open(n.current),requestAnimationFrame(()=>{var i;t.fit();const{cols:s,rows:r}=e;p.current||(p.current=!0,null==(i=f.current)||i.call(f,s,r)),u.current(s,r)}),o.current=e,a.current=t,m.current=g,e.onData(e=>{c.current(e)});const s=new ResizeObserver(()=>{requestAnimationFrame(()=>{n.current&&null!==n.current.offsetParent&&(t.fit(),u.current(e.cols,e.rows))})});return s.observe(n.current),()=>{s.disconnect(),e.dispose(),o.current=null,a.current=null,l.current=null}},[]),h.useEffect(()=>{const e=o.current;if(e&&m.current!==g)if(m.current=g,e.options.theme="dark"===g?hf:df,"claude"===s){const e="dark"===g?"dark":"light";c.current(`/theme ${e}\r`)}else if("gemini"===s){const e="dark"===g?"dark":"light";c.current(`/settings theme ${e}\r`)}else if("codex"===s){const e="dark"===g?"dark":"light";c.current(`/theme ${e}\r`)}},[g,s]),_.jsx("div",{ref:n,className:"h-full w-full bg-background",style:{overflow:"hidden",padding:"4px"}})});function ff({onSearch:e,onSearchNext:t,onSearchPrev:i,onClear:s,onClose:r}){const[n,o]=h.useState(""),[a,l]=h.useState(!1),[c,d]=h.useState(!1),u=h.useRef(null);h.useEffect(()=>{var e;null==(e=u.current)||e.focus()},[]);const f=h.useMemo(()=>({caseSensitive:a,regex:c}),[a,c]);return _.jsxs("div",{className:"absolute top-2 right-2 z-20 flex items-center gap-1 bg-background border border-border rounded-md shadow-sm px-2 py-1",children:[_.jsx(oi,{className:"h-3.5 w-3.5 text-muted-foreground flex-shrink-0"}),_.jsx(q,{ref:u,value:n,onChange:t=>{return i=t.target.value,o(i),void(i?e(i,f):s());var i},onKeyDown:e=>{if("Enter"===e.key){if(!n)return;e.shiftKey?i(n,f):t(n,f)}"Escape"===e.key&&(s(),r())},placeholder:"搜索...",className:"h-6 w-44 text-xs border-0 p-0 focus-visible:ring-0 bg-transparent"}),_.jsx("button",{title:"区分大小写",onClick:()=>{const t=!a;l(t),n&&e(n,{...f,caseSensitive:t})},className:g("text-[10px] px-1 rounded font-mono transition-colors",a?"bg-accent text-foreground font-medium":"text-muted-foreground hover:text-foreground"),children:"Aa"}),_.jsx("button",{title:"正则表达式",onClick:()=>{const t=!c;d(t),n&&e(n,{...f,regex:t})},className:g("text-[10px] px-1 rounded font-mono transition-colors",c?"bg-accent text-foreground font-medium":"text-muted-foreground hover:text-foreground"),children:".*"}),_.jsx(K,{variant:"ghost",size:"icon",className:"h-5 w-5",onClick:()=>{n&&i(n,f)},disabled:!n,children:_.jsx(ni,{className:"h-3 w-3"})}),_.jsx(K,{variant:"ghost",size:"icon",className:"h-5 w-5",onClick:()=>{n&&t(n,f)},disabled:!n,children:_.jsx(ii,{className:"h-3 w-3"})}),_.jsx(K,{variant:"ghost",size:"icon",className:"h-5 w-5",onClick:()=>{s(),r()},children:_.jsx(S,{className:"h-3 w-3"})})]})}uf.displayName="WebTerminal";const pf=h.forwardRef(({projectId:e,project:t,onStatusChange:i,onChatMessage:s,onWsConnected:r,onWsDisconnected:n,onApprovalRequest:o,onApprovalResolved:a,onSemanticUpdate:l},c)=>{const d=h.useRef([]),[u,f]=h.useState(!1),[p,m]=h.useState(null),g=h.useRef(null),v=h.useRef(null),y=h.useRef(null),x=h.useRef(null),b=h.useCallback(e=>{var t;null==(t=g.current)||t.write(e)},[]),w=h.useCallback(()=>{var e;const t=v.current;t&&y.current&&y.current(t.cols,t.rows),null==(e=x.current)||e.call(x)},[]),S=h.useCallback(()=>{var e;null==(e=g.current)||e.reset()},[]),{subscribeTerminal:C,sendTerminalInput:k,sendTerminalResize:E,subscribeChatMessages:N}=ct(e,{onTerminalData:b,onTerminalReset:S,onStatus:i,onConnected:()=>{d.current=[],null==r||r(),w()},onDisconnected:()=>{null==n||n()},onChatMessage:e=>{d.current.push(e),null==s||s(e)},onApprovalRequest:e=>null==o?void 0:o(e),onApprovalResolved:e=>null==a?void 0:a(e),onContextUpdate:e=>m(e),onSemanticUpdate:e=>null==l?void 0:l(e)});h.useEffect(()=>{y.current=C},[C]),h.useEffect(()=>{x.current=N},[N]),h.useEffect(()=>{const e=e=>{(e.ctrlKey||e.metaKey)&&"f"===e.key&&(e.preventDefault(),f(e=>!e))};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[]);const M=h.useCallback((e,t)=>{v.current={cols:e,rows:t},w()},[w]);return h.useImperativeHandle(c,()=>({sendTerminalInput:k}),[k]),_.jsxs("div",{className:"flex-1 overflow-hidden min-w-0 flex flex-col",children:[_.jsxs("div",{className:"relative flex-1 min-h-0",children:[_.jsx(uf,{ref:g,onInput:k,onResize:(e,t)=>{v.current={cols:e,rows:t},E(e,t)},onReady:M,cliTool:null==t?void 0:t.cliTool}),u&&_.jsx(ff,{onSearch:(e,t)=>{var i;return(null==(i=g.current)?void 0:i.search(e,t))??!1},onSearchNext:(e,t)=>{var i;return(null==(i=g.current)?void 0:i.searchNext(e,t))??!1},onSearchPrev:(e,t)=>{var i;return(null==(i=g.current)?void 0:i.searchPrevious(e,t))??!1},onClear:()=>{var e;return null==(e=g.current)?void 0:e.clearSearch()},onClose:()=>f(!1)})]}),_.jsxs("div",{className:"flex-shrink-0 flex items-center px-3 h-7 border-t border-border bg-muted/30 gap-3",children:[_.jsx(ht,{}),p&&_.jsxs("div",{className:"flex items-center gap-1.5 text-xs",children:[_.jsx("span",{className:"text-muted-foreground",children:"上下文"}),_.jsx("div",{className:"w-20 h-1.5 bg-muted rounded-full overflow-hidden",children:_.jsx("div",{className:"h-full rounded-full transition-all "+(p.usedPercentage<50?"bg-green-500":p.usedPercentage<80?"bg-yellow-500":"bg-red-500"),style:{width:`${Math.min(p.usedPercentage,100)}%`}})}),_.jsxs("span",{className:"font-medium "+(p.usedPercentage<50?"text-green-500":p.usedPercentage<80?"text-yellow-500":"text-red-500"),children:[Math.round(p.usedPercentage),"%"]}),_.jsx("span",{className:"text-muted-foreground/50",children:p.contextWindowSize>=1e6?`${(p.contextWindowSize/1e6).toFixed(0)}M`:`${Math.round(p.contextWindowSize/1e3)}K`})]})]})]})});pf.displayName="TerminalView";const mf=new Set(["png","jpg","jpeg","gif","webp","svg","bmp","ico","avif","tiff","tif"]),_f=new Set(["js","jsx","ts","tsx","py","rb","go","rs","java","kt","swift","c","cpp","h","cs","php","sh","bash","zsh","yaml","yml","json","toml","html","htm","xml","css","scss","less","sql","graphql","gql","r","lua","dart","zig"]);function gf({projectId:e}){const t=D(t=>t.get(e).filePreviews),i=D(t=>t.get(e).activePreviewPath),s=D(e=>e.setActivePreview),r=D(e=>e.closeFilePreview),n=D(e=>e.minimizeFilePreview);return 0===t.length?null:_.jsx("div",{className:"absolute top-2 left-1/2 -translate-x-1/2 z-[60] pointer-events-auto",onContextMenu:e=>e.preventDefault(),children:_.jsx("div",{className:"flex items-center gap-1 rounded-full border border-border bg-background/85 backdrop-blur-sm shadow-sm px-1.5 py-1",children:t.map(t=>{const o=function(e){if(e.endsWith("/.notebook/graph.yaml"))return wi;const t=function(e){const t=e.split("/").pop()??"",i=t.toLowerCase();if("dockerfile"===i)return"dockerfile";if("makefile"===i)return"makefile";const s=t.lastIndexOf(".");return s>=0?t.slice(s+1).toLowerCase():""}(e);return mf.has(t)?Pt:"pdf"===t?wt:"xlsx"===t||"xls"===t?mi:"pptx"===t?Ei:"docx"===t||"md"===t?wt:_f.has(t)?ui:dt}(t.path),a=t.path===i&&!t.minimized;return _.jsxs("div",{className:g("group flex items-center gap-1 rounded-full pl-1.5 pr-1 py-0.5 max-w-[180px] cursor-pointer transition-colors",a?"bg-accent text-accent-foreground":"hover:bg-muted text-muted-foreground"),onClick:()=>{a?n(e,t.path):s(e,t.path)},title:t.path,children:[_.jsx(o,{className:"size-3.5 flex-shrink-0"}),_.jsx("span",{className:"text-xs truncate min-w-0",children:(l=t.path,l.split("/").pop()??l)}),_.jsx("button",{className:"flex-shrink-0 size-4 rounded-full flex items-center justify-center opacity-60 hover:opacity-100 hover:bg-background/60 transition-opacity",onClick:i=>{i.stopPropagation(),r(e,t.path)},title:"关闭",children:_.jsx(S,{className:"size-3"})})]},t.path);var l})})})}function vf(e){if("string"==typeof e||"number"==typeof e)return""+e;let t="";if(Array.isArray(e))for(let i,s=0;s<e.length;s++)""!==(i=vf(e[s]))&&(t+=(t&&" ")+i);else for(let i in e)e[i]&&(t+=(t&&" ")+i);return t}var yf={exports:{}},xf={},bf=h,wf=ut;var Sf="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},Cf=wf.useSyncExternalStore,kf=bf.useRef,Ef=bf.useEffect,Nf=bf.useMemo,Mf=bf.useDebugValue;xf.useSyncExternalStoreWithSelector=function(e,t,i,s,r){var n=kf(null);if(null===n.current){var o={hasValue:!1,value:null};n.current=o}else o=n.current;n=Nf(function(){function e(e){if(!l){if(l=!0,n=e,e=s(e),void 0!==r&&o.hasValue){var t=o.value;if(r(t,e))return a=t}return a=e}if(t=a,Sf(n,e))return t;var i=s(e);return void 0!==r&&r(t,i)?(n=e,t):(n=e,a=i)}var n,a,l=!1,c=void 0===i?null:i;return[function(){return e(t())},null===c?void 0:function(){return e(c())}]},[t,i,s,r]);var a=Cf(e,n[0],n[1]);return Ef(function(){o.hasValue=!0,o.value=a},[a]),Mf(a),a},yf.exports=xf;const jf=ft(yf.exports),Df={},Rf=e=>{let t;const i=new Set,s=(e,s)=>{const r="function"==typeof e?e(t):e;if(!Object.is(r,t)){const e=t;t=(null!=s?s:"object"!=typeof r||null===r)?r:Object.assign({},t,r),i.forEach(i=>i(t,e))}},r=()=>t,n={setState:s,getState:r,getInitialState:()=>o,subscribe:e=>(i.add(e),()=>i.delete(e)),destroy:()=>{"production"!==(Df?"production":void 0)&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),i.clear()}},o=t=e(s,r,n);return n},{useDebugValue:Pf}=N,{useSyncExternalStoreWithSelector:Lf}=jf,If=e=>e;function Tf(e,t=If,i){const s=Lf(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,i);return Pf(s),s}const Bf=(e,t)=>{const i=(e=>e?Rf(e):Rf)(e),s=(e,s=t)=>Tf(i,e,s);return Object.assign(s,i),s};function Of(e,t){if(Object.is(e,t))return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(const[i,s]of e)if(!Object.is(s,t.get(i)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(const i of e)if(!t.has(i))return!1;return!0}const i=Object.keys(e);if(i.length!==Object.keys(t).length)return!1;for(const s of i)if(!Object.prototype.hasOwnProperty.call(t,s)||!Object.is(e[s],t[s]))return!1;return!0}var Af={value:()=>{}};function zf(){for(var e,t=0,i=arguments.length,s={};t<i;++t){if(!(e=arguments[t]+"")||e in s||/[\s.]/.test(e))throw new Error("illegal type: "+e);s[e]=[]}return new $f(s)}function $f(e){this._=e}function Hf(e,t){for(var i,s=0,r=e.length;s<r;++s)if((i=e[s]).name===t)return i.value}function Wf(e,t,i){for(var s=0,r=e.length;s<r;++s)if(e[s].name===t){e[s]=Af,e=e.slice(0,s).concat(e.slice(s+1));break}return null!=i&&e.push({name:t,value:i}),e}$f.prototype=zf.prototype={constructor:$f,on:function(e,t){var i,s,r=this._,n=(s=r,(e+"").trim().split(/^|\s+/).map(function(e){var t="",i=e.indexOf(".");if(i>=0&&(t=e.slice(i+1),e=e.slice(0,i)),e&&!s.hasOwnProperty(e))throw new Error("unknown type: "+e);return{type:e,name:t}})),o=-1,a=n.length;if(!(arguments.length<2)){if(null!=t&&"function"!=typeof t)throw new Error("invalid callback: "+t);for(;++o<a;)if(i=(e=n[o]).type)r[i]=Wf(r[i],e.name,t);else if(null==t)for(i in r)r[i]=Wf(r[i],e.name,null);return this}for(;++o<a;)if((i=(e=n[o]).type)&&(i=Hf(r[i],e.name)))return i},copy:function(){var e={},t=this._;for(var i in t)e[i]=t[i].slice();return new $f(e)},call:function(e,t){if((i=arguments.length-2)>0)for(var i,s,r=new Array(i),n=0;n<i;++n)r[n]=arguments[n+2];if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(n=0,i=(s=this._[e]).length;n<i;++n)s[n].value.apply(t,r)},apply:function(e,t,i){if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(var s=this._[e],r=0,n=s.length;r<n;++r)s[r].value.apply(t,i)}};var Ff="http://www.w3.org/1999/xhtml";const Kf={svg:"http://www.w3.org/2000/svg",xhtml:Ff,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function Uf(e){var t=e+="",i=t.indexOf(":");return i>=0&&"xmlns"!==(t=e.slice(0,i))&&(e=e.slice(i+1)),Kf.hasOwnProperty(t)?{space:Kf[t],local:e}:e}function Vf(e){return function(){var t=this.ownerDocument,i=this.namespaceURI;return i===Ff&&t.documentElement.namespaceURI===Ff?t.createElement(e):t.createElementNS(i,e)}}function qf(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function Yf(e){var t=Uf(e);return(t.local?qf:Vf)(t)}function Xf(){}function Gf(e){return null==e?Xf:function(){return this.querySelector(e)}}function Zf(){return[]}function Jf(e){return null==e?Zf:function(){return this.querySelectorAll(e)}}function Qf(e){return function(){return null==(t=e.apply(this,arguments))?[]:Array.isArray(t)?t:Array.from(t);var t}}function ep(e){return function(){return this.matches(e)}}function tp(e){return function(t){return t.matches(e)}}var ip=Array.prototype.find;function sp(){return this.firstElementChild}var rp=Array.prototype.filter;function np(){return Array.from(this.children)}function op(e){return new Array(e.length)}function ap(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}function lp(e,t,i,s,r,n){for(var o,a=0,l=t.length,c=n.length;a<c;++a)(o=t[a])?(o.__data__=n[a],s[a]=o):i[a]=new ap(e,n[a]);for(;a<l;++a)(o=t[a])&&(r[a]=o)}function cp(e,t,i,s,r,n,o){var a,l,c,h=new Map,d=t.length,u=n.length,f=new Array(d);for(a=0;a<d;++a)(l=t[a])&&(f[a]=c=o.call(l,l.__data__,a,t)+"",h.has(c)?r[a]=l:h.set(c,l));for(a=0;a<u;++a)c=o.call(e,n[a],a,n)+"",(l=h.get(c))?(s[a]=l,l.__data__=n[a],h.delete(c)):i[a]=new ap(e,n[a]);for(a=0;a<d;++a)(l=t[a])&&h.get(f[a])===l&&(r[a]=l)}function hp(e){return e.__data__}function dp(e){return"object"==typeof e&&"length"in e?e:Array.from(e)}function up(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function fp(e){return function(){this.removeAttribute(e)}}function pp(e){return function(){this.removeAttributeNS(e.space,e.local)}}function mp(e,t){return function(){this.setAttribute(e,t)}}function _p(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function gp(e,t){return function(){var i=t.apply(this,arguments);null==i?this.removeAttribute(e):this.setAttribute(e,i)}}function vp(e,t){return function(){var i=t.apply(this,arguments);null==i?this.removeAttributeNS(e.space,e.local):this.setAttributeNS(e.space,e.local,i)}}function yp(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function xp(e){return function(){this.style.removeProperty(e)}}function bp(e,t,i){return function(){this.style.setProperty(e,t,i)}}function wp(e,t,i){return function(){var s=t.apply(this,arguments);null==s?this.style.removeProperty(e):this.style.setProperty(e,s,i)}}function Sp(e,t){return e.style.getPropertyValue(t)||yp(e).getComputedStyle(e,null).getPropertyValue(t)}function Cp(e){return function(){delete this[e]}}function kp(e,t){return function(){this[e]=t}}function Ep(e,t){return function(){var i=t.apply(this,arguments);null==i?delete this[e]:this[e]=i}}function Np(e){return e.trim().split(/^|\s+/)}function Mp(e){return e.classList||new jp(e)}function jp(e){this._node=e,this._names=Np(e.getAttribute("class")||"")}function Dp(e,t){for(var i=Mp(e),s=-1,r=t.length;++s<r;)i.add(t[s])}function Rp(e,t){for(var i=Mp(e),s=-1,r=t.length;++s<r;)i.remove(t[s])}function Pp(e){return function(){Dp(this,e)}}function Lp(e){return function(){Rp(this,e)}}function Ip(e,t){return function(){(t.apply(this,arguments)?Dp:Rp)(this,e)}}function Tp(){this.textContent=""}function Bp(e){return function(){this.textContent=e}}function Op(e){return function(){var t=e.apply(this,arguments);this.textContent=null==t?"":t}}function Ap(){this.innerHTML=""}function zp(e){return function(){this.innerHTML=e}}function $p(e){return function(){var t=e.apply(this,arguments);this.innerHTML=null==t?"":t}}function Hp(){this.nextSibling&&this.parentNode.appendChild(this)}function Wp(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function Fp(){return null}function Kp(){var e=this.parentNode;e&&e.removeChild(this)}function Up(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function Vp(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function qp(e){return function(){var t=this.__on;if(t){for(var i,s=0,r=-1,n=t.length;s<n;++s)i=t[s],e.type&&i.type!==e.type||i.name!==e.name?t[++r]=i:this.removeEventListener(i.type,i.listener,i.options);++r?t.length=r:delete this.__on}}}function Yp(e,t,i){return function(){var s,r=this.__on,n=function(e){return function(t){e.call(this,t,this.__data__)}}(t);if(r)for(var o=0,a=r.length;o<a;++o)if((s=r[o]).type===e.type&&s.name===e.name)return this.removeEventListener(s.type,s.listener,s.options),this.addEventListener(s.type,s.listener=n,s.options=i),void(s.value=t);this.addEventListener(e.type,n,i),s={type:e.type,name:e.name,value:t,listener:n,options:i},r?r.push(s):this.__on=[s]}}function Xp(e,t,i){var s=yp(e),r=s.CustomEvent;"function"==typeof r?r=new r(t,i):(r=s.document.createEvent("Event"),i?(r.initEvent(t,i.bubbles,i.cancelable),r.detail=i.detail):r.initEvent(t,!1,!1)),e.dispatchEvent(r)}function Gp(e,t){return function(){return Xp(this,e,t)}}function Zp(e,t){return function(){return Xp(this,e,t.apply(this,arguments))}}ap.prototype={constructor:ap,appendChild:function(e){return this._parent.insertBefore(e,this._next)},insertBefore:function(e,t){return this._parent.insertBefore(e,t)},querySelector:function(e){return this._parent.querySelector(e)},querySelectorAll:function(e){return this._parent.querySelectorAll(e)}},jp.prototype={add:function(e){this._names.indexOf(e)<0&&(this._names.push(e),this._node.setAttribute("class",this._names.join(" ")))},remove:function(e){var t=this._names.indexOf(e);t>=0&&(this._names.splice(t,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(e){return this._names.indexOf(e)>=0}};var Jp=[null];function Qp(e,t){this._groups=e,this._parents=t}function em(){return new Qp([[document.documentElement]],Jp)}function tm(e){return"string"==typeof e?new Qp([[document.querySelector(e)]],[document.documentElement]):new Qp([[e]],Jp)}function im(e,t){if(e=function(e){let t;for(;t=e.sourceEvent;)e=t;return e}(e),void 0===t&&(t=e.currentTarget),t){var i=t.ownerSVGElement||t;if(i.createSVGPoint){var s=i.createSVGPoint();return s.x=e.clientX,s.y=e.clientY,[(s=s.matrixTransform(t.getScreenCTM().inverse())).x,s.y]}if(t.getBoundingClientRect){var r=t.getBoundingClientRect();return[e.clientX-r.left-t.clientLeft,e.clientY-r.top-t.clientTop]}}return[e.pageX,e.pageY]}Qp.prototype=em.prototype={constructor:Qp,select:function(e){"function"!=typeof e&&(e=Gf(e));for(var t=this._groups,i=t.length,s=new Array(i),r=0;r<i;++r)for(var n,o,a=t[r],l=a.length,c=s[r]=new Array(l),h=0;h<l;++h)(n=a[h])&&(o=e.call(n,n.__data__,h,a))&&("__data__"in n&&(o.__data__=n.__data__),c[h]=o);return new Qp(s,this._parents)},selectAll:function(e){e="function"==typeof e?Qf(e):Jf(e);for(var t=this._groups,i=t.length,s=[],r=[],n=0;n<i;++n)for(var o,a=t[n],l=a.length,c=0;c<l;++c)(o=a[c])&&(s.push(e.call(o,o.__data__,c,a)),r.push(o));return new Qp(s,r)},selectChild:function(e){return this.select(null==e?sp:function(e){return function(){return ip.call(this.children,e)}}("function"==typeof e?e:tp(e)))},selectChildren:function(e){return this.selectAll(null==e?np:function(e){return function(){return rp.call(this.children,e)}}("function"==typeof e?e:tp(e)))},filter:function(e){"function"!=typeof e&&(e=ep(e));for(var t=this._groups,i=t.length,s=new Array(i),r=0;r<i;++r)for(var n,o=t[r],a=o.length,l=s[r]=[],c=0;c<a;++c)(n=o[c])&&e.call(n,n.__data__,c,o)&&l.push(n);return new Qp(s,this._parents)},data:function(e,t){if(!arguments.length)return Array.from(this,hp);var i,s=t?cp:lp,r=this._parents,n=this._groups;"function"!=typeof e&&(i=e,e=function(){return i});for(var o=n.length,a=new Array(o),l=new Array(o),c=new Array(o),h=0;h<o;++h){var d=r[h],u=n[h],f=u.length,p=dp(e.call(d,d&&d.__data__,h,r)),m=p.length,_=l[h]=new Array(m),g=a[h]=new Array(m);s(d,u,_,g,c[h]=new Array(f),p,t);for(var v,y,x=0,b=0;x<m;++x)if(v=_[x]){for(x>=b&&(b=x+1);!(y=g[b])&&++b<m;);v._next=y||null}}return(a=new Qp(a,r))._enter=l,a._exit=c,a},enter:function(){return new Qp(this._enter||this._groups.map(op),this._parents)},exit:function(){return new Qp(this._exit||this._groups.map(op),this._parents)},join:function(e,t,i){var s=this.enter(),r=this,n=this.exit();return"function"==typeof e?(s=e(s))&&(s=s.selection()):s=s.append(e+""),null!=t&&(r=t(r))&&(r=r.selection()),null==i?n.remove():i(n),s&&r?s.merge(r).order():r},merge:function(e){for(var t=e.selection?e.selection():e,i=this._groups,s=t._groups,r=i.length,n=s.length,o=Math.min(r,n),a=new Array(r),l=0;l<o;++l)for(var c,h=i[l],d=s[l],u=h.length,f=a[l]=new Array(u),p=0;p<u;++p)(c=h[p]||d[p])&&(f[p]=c);for(;l<r;++l)a[l]=i[l];return new Qp(a,this._parents)},selection:function(){return this},order:function(){for(var e=this._groups,t=-1,i=e.length;++t<i;)for(var s,r=e[t],n=r.length-1,o=r[n];--n>=0;)(s=r[n])&&(o&&4^s.compareDocumentPosition(o)&&o.parentNode.insertBefore(s,o),o=s);return this},sort:function(e){function t(t,i){return t&&i?e(t.__data__,i.__data__):!t-!i}e||(e=up);for(var i=this._groups,s=i.length,r=new Array(s),n=0;n<s;++n){for(var o,a=i[n],l=a.length,c=r[n]=new Array(l),h=0;h<l;++h)(o=a[h])&&(c[h]=o);c.sort(t)}return new Qp(r,this._parents).order()},call:function(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this},nodes:function(){return Array.from(this)},node:function(){for(var e=this._groups,t=0,i=e.length;t<i;++t)for(var s=e[t],r=0,n=s.length;r<n;++r){var o=s[r];if(o)return o}return null},size:function(){let e=0;for(const t of this)++e;return e},empty:function(){return!this.node()},each:function(e){for(var t=this._groups,i=0,s=t.length;i<s;++i)for(var r,n=t[i],o=0,a=n.length;o<a;++o)(r=n[o])&&e.call(r,r.__data__,o,n);return this},attr:function(e,t){var i=Uf(e);if(arguments.length<2){var s=this.node();return i.local?s.getAttributeNS(i.space,i.local):s.getAttribute(i)}return this.each((null==t?i.local?pp:fp:"function"==typeof t?i.local?vp:gp:i.local?_p:mp)(i,t))},style:function(e,t,i){return arguments.length>1?this.each((null==t?xp:"function"==typeof t?wp:bp)(e,t,null==i?"":i)):Sp(this.node(),e)},property:function(e,t){return arguments.length>1?this.each((null==t?Cp:"function"==typeof t?Ep:kp)(e,t)):this.node()[e]},classed:function(e,t){var i=Np(e+"");if(arguments.length<2){for(var s=Mp(this.node()),r=-1,n=i.length;++r<n;)if(!s.contains(i[r]))return!1;return!0}return this.each(("function"==typeof t?Ip:t?Pp:Lp)(i,t))},text:function(e){return arguments.length?this.each(null==e?Tp:("function"==typeof e?Op:Bp)(e)):this.node().textContent},html:function(e){return arguments.length?this.each(null==e?Ap:("function"==typeof e?$p:zp)(e)):this.node().innerHTML},raise:function(){return this.each(Hp)},lower:function(){return this.each(Wp)},append:function(e){var t="function"==typeof e?e:Yf(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})},insert:function(e,t){var i="function"==typeof e?e:Yf(e),s=null==t?Fp:"function"==typeof t?t:Gf(t);return this.select(function(){return this.insertBefore(i.apply(this,arguments),s.apply(this,arguments)||null)})},remove:function(){return this.each(Kp)},clone:function(e){return this.select(e?Vp:Up)},datum:function(e){return arguments.length?this.property("__data__",e):this.node().__data__},on:function(e,t,i){var s,r,n=function(e){return e.trim().split(/^|\s+/).map(function(e){var t="",i=e.indexOf(".");return i>=0&&(t=e.slice(i+1),e=e.slice(0,i)),{type:e,name:t}})}(e+""),o=n.length;if(!(arguments.length<2)){for(a=t?Yp:qp,s=0;s<o;++s)this.each(a(n[s],t,i));return this}var a=this.node().__on;if(a)for(var l,c=0,h=a.length;c<h;++c)for(s=0,l=a[c];s<o;++s)if((r=n[s]).type===l.type&&r.name===l.name)return l.value},dispatch:function(e,t){return this.each(("function"==typeof t?Zp:Gp)(e,t))},[Symbol.iterator]:function*(){for(var e=this._groups,t=0,i=e.length;t<i;++t)for(var s,r=e[t],n=0,o=r.length;n<o;++n)(s=r[n])&&(yield s)}};const sm={passive:!1},rm={capture:!0,passive:!1};function nm(e){e.stopImmediatePropagation()}function om(e){e.preventDefault(),e.stopImmediatePropagation()}function am(e){var t=e.document.documentElement,i=tm(e).on("dragstart.drag",om,rm);"onselectstart"in t?i.on("selectstart.drag",om,rm):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function lm(e,t){var i=e.document.documentElement,s=tm(e).on("dragstart.drag",null);t&&(s.on("click.drag",om,rm),setTimeout(function(){s.on("click.drag",null)},0)),"onselectstart"in i?s.on("selectstart.drag",null):(i.style.MozUserSelect=i.__noselect,delete i.__noselect)}const cm=e=>()=>e;function hm(e,{sourceEvent:t,subject:i,target:s,identifier:r,active:n,x:o,y:a,dx:l,dy:c,dispatch:h}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},subject:{value:i,enumerable:!0,configurable:!0},target:{value:s,enumerable:!0,configurable:!0},identifier:{value:r,enumerable:!0,configurable:!0},active:{value:n,enumerable:!0,configurable:!0},x:{value:o,enumerable:!0,configurable:!0},y:{value:a,enumerable:!0,configurable:!0},dx:{value:l,enumerable:!0,configurable:!0},dy:{value:c,enumerable:!0,configurable:!0},_:{value:h}})}function dm(e){return!e.ctrlKey&&!e.button}function um(){return this.parentNode}function fm(e,t){return null==t?{x:e.x,y:e.y}:t}function pm(){return navigator.maxTouchPoints||"ontouchstart"in this}function mm(e,t,i){e.prototype=t.prototype=i,i.constructor=e}function _m(e,t){var i=Object.create(e.prototype);for(var s in t)i[s]=t[s];return i}function gm(){}hm.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};var vm=.7,ym=1/vm,xm="\\s*([+-]?\\d+)\\s*",bm="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",wm="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",Sm=/^#([0-9a-f]{3,8})$/,Cm=new RegExp(`^rgb\\(${xm},${xm},${xm}\\)$`),km=new RegExp(`^rgb\\(${wm},${wm},${wm}\\)$`),Em=new RegExp(`^rgba\\(${xm},${xm},${xm},${bm}\\)$`),Nm=new RegExp(`^rgba\\(${wm},${wm},${wm},${bm}\\)$`),Mm=new RegExp(`^hsl\\(${bm},${wm},${wm}\\)$`),jm=new RegExp(`^hsla\\(${bm},${wm},${wm},${bm}\\)$`),Dm={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};function Rm(){return this.rgb().formatHex()}function Pm(){return this.rgb().formatRgb()}function Lm(e){var t,i;return e=(e+"").trim().toLowerCase(),(t=Sm.exec(e))?(i=t[1].length,t=parseInt(t[1],16),6===i?Im(t):3===i?new Om(t>>8&15|t>>4&240,t>>4&15|240&t,(15&t)<<4|15&t,1):8===i?Tm(t>>24&255,t>>16&255,t>>8&255,(255&t)/255):4===i?Tm(t>>12&15|t>>8&240,t>>8&15|t>>4&240,t>>4&15|240&t,((15&t)<<4|15&t)/255):null):(t=Cm.exec(e))?new Om(t[1],t[2],t[3],1):(t=km.exec(e))?new Om(255*t[1]/100,255*t[2]/100,255*t[3]/100,1):(t=Em.exec(e))?Tm(t[1],t[2],t[3],t[4]):(t=Nm.exec(e))?Tm(255*t[1]/100,255*t[2]/100,255*t[3]/100,t[4]):(t=Mm.exec(e))?Fm(t[1],t[2]/100,t[3]/100,1):(t=jm.exec(e))?Fm(t[1],t[2]/100,t[3]/100,t[4]):Dm.hasOwnProperty(e)?Im(Dm[e]):"transparent"===e?new Om(NaN,NaN,NaN,0):null}function Im(e){return new Om(e>>16&255,e>>8&255,255&e,1)}function Tm(e,t,i,s){return s<=0&&(e=t=i=NaN),new Om(e,t,i,s)}function Bm(e,t,i,s){return 1===arguments.length?function(e){return e instanceof gm||(e=Lm(e)),e?new Om((e=e.rgb()).r,e.g,e.b,e.opacity):new Om}(e):new Om(e,t,i,null==s?1:s)}function Om(e,t,i,s){this.r=+e,this.g=+t,this.b=+i,this.opacity=+s}function Am(){return`#${Wm(this.r)}${Wm(this.g)}${Wm(this.b)}`}function zm(){const e=$m(this.opacity);return`${1===e?"rgb(":"rgba("}${Hm(this.r)}, ${Hm(this.g)}, ${Hm(this.b)}${1===e?")":`, ${e})`}`}function $m(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function Hm(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function Wm(e){return((e=Hm(e))<16?"0":"")+e.toString(16)}function Fm(e,t,i,s){return s<=0?e=t=i=NaN:i<=0||i>=1?e=t=NaN:t<=0&&(e=NaN),new Um(e,t,i,s)}function Km(e){if(e instanceof Um)return new Um(e.h,e.s,e.l,e.opacity);if(e instanceof gm||(e=Lm(e)),!e)return new Um;if(e instanceof Um)return e;var t=(e=e.rgb()).r/255,i=e.g/255,s=e.b/255,r=Math.min(t,i,s),n=Math.max(t,i,s),o=NaN,a=n-r,l=(n+r)/2;return a?(o=t===n?(i-s)/a+6*(i<s):i===n?(s-t)/a+2:(t-i)/a+4,a/=l<.5?n+r:2-n-r,o*=60):a=l>0&&l<1?0:o,new Um(o,a,l,e.opacity)}function Um(e,t,i,s){this.h=+e,this.s=+t,this.l=+i,this.opacity=+s}function Vm(e){return(e=(e||0)%360)<0?e+360:e}function qm(e){return Math.max(0,Math.min(1,e||0))}function Ym(e,t,i){return 255*(e<60?t+(i-t)*e/60:e<180?i:e<240?t+(i-t)*(240-e)/60:t)}mm(gm,Lm,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:Rm,formatHex:Rm,formatHex8:function(){return this.rgb().formatHex8()},formatHsl:function(){return Km(this).formatHsl()},formatRgb:Pm,toString:Pm}),mm(Om,Bm,_m(gm,{brighter(e){return e=null==e?ym:Math.pow(ym,e),new Om(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=null==e?vm:Math.pow(vm,e),new Om(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new Om(Hm(this.r),Hm(this.g),Hm(this.b),$m(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:Am,formatHex:Am,formatHex8:function(){return`#${Wm(this.r)}${Wm(this.g)}${Wm(this.b)}${Wm(255*(isNaN(this.opacity)?1:this.opacity))}`},formatRgb:zm,toString:zm})),mm(Um,function(e,t,i,s){return 1===arguments.length?Km(e):new Um(e,t,i,null==s?1:s)},_m(gm,{brighter(e){return e=null==e?ym:Math.pow(ym,e),new Um(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=null==e?vm:Math.pow(vm,e),new Um(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=this.h%360+360*(this.h<0),t=isNaN(e)||isNaN(this.s)?0:this.s,i=this.l,s=i+(i<.5?i:1-i)*t,r=2*i-s;return new Om(Ym(e>=240?e-240:e+120,r,s),Ym(e,r,s),Ym(e<120?e+240:e-120,r,s),this.opacity)},clamp(){return new Um(Vm(this.h),qm(this.s),qm(this.l),$m(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const e=$m(this.opacity);return`${1===e?"hsl(":"hsla("}${Vm(this.h)}, ${100*qm(this.s)}%, ${100*qm(this.l)}%${1===e?")":`, ${e})`}`}}));const Xm=e=>()=>e;function Gm(e){return 1===(e=+e)?Zm:function(t,i){return i-t?function(e,t,i){return e=Math.pow(e,i),t=Math.pow(t,i)-e,i=1/i,function(s){return Math.pow(e+s*t,i)}}(t,i,e):Xm(isNaN(t)?i:t)}}function Zm(e,t){var i=t-e;return i?function(e,t){return function(i){return e+i*t}}(e,i):Xm(isNaN(e)?t:e)}const Jm=function e(t){var i=Gm(t);function s(e,t){var s=i((e=Bm(e)).r,(t=Bm(t)).r),r=i(e.g,t.g),n=i(e.b,t.b),o=Zm(e.opacity,t.opacity);return function(t){return e.r=s(t),e.g=r(t),e.b=n(t),e.opacity=o(t),e+""}}return s.gamma=e,s}(1);function Qm(e,t){return e=+e,t=+t,function(i){return e*(1-i)+t*i}}var e_=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,t_=new RegExp(e_.source,"g");function i_(e,t){var i,s,r,n=e_.lastIndex=t_.lastIndex=0,o=-1,a=[],l=[];for(e+="",t+="";(i=e_.exec(e))&&(s=t_.exec(t));)(r=s.index)>n&&(r=t.slice(n,r),a[o]?a[o]+=r:a[++o]=r),(i=i[0])===(s=s[0])?a[o]?a[o]+=s:a[++o]=s:(a[++o]=null,l.push({i:o,x:Qm(i,s)})),n=t_.lastIndex;return n<t.length&&(r=t.slice(n),a[o]?a[o]+=r:a[++o]=r),a.length<2?l[0]?function(e){return function(t){return e(t)+""}}(l[0].x):function(e){return function(){return e}}(t):(t=l.length,function(e){for(var i,s=0;s<t;++s)a[(i=l[s]).i]=i.x(e);return a.join("")})}var s_,r_=180/Math.PI,n_={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function o_(e,t,i,s,r,n){var o,a,l;return(o=Math.sqrt(e*e+t*t))&&(e/=o,t/=o),(l=e*i+t*s)&&(i-=e*l,s-=t*l),(a=Math.sqrt(i*i+s*s))&&(i/=a,s/=a,l/=a),e*s<t*i&&(e=-e,t=-t,l=-l,o=-o),{translateX:r,translateY:n,rotate:Math.atan2(t,e)*r_,skewX:Math.atan(l)*r_,scaleX:o,scaleY:a}}function a_(e,t,i,s){function r(e){return e.length?e.pop()+" ":""}return function(n,o){var a=[],l=[];return n=e(n),o=e(o),function(e,s,r,n,o,a){if(e!==r||s!==n){var l=o.push("translate(",null,t,null,i);a.push({i:l-4,x:Qm(e,r)},{i:l-2,x:Qm(s,n)})}else(r||n)&&o.push("translate("+r+t+n+i)}(n.translateX,n.translateY,o.translateX,o.translateY,a,l),function(e,t,i,n){e!==t?(e-t>180?t+=360:t-e>180&&(e+=360),n.push({i:i.push(r(i)+"rotate(",null,s)-2,x:Qm(e,t)})):t&&i.push(r(i)+"rotate("+t+s)}(n.rotate,o.rotate,a,l),function(e,t,i,n){e!==t?n.push({i:i.push(r(i)+"skewX(",null,s)-2,x:Qm(e,t)}):t&&i.push(r(i)+"skewX("+t+s)}(n.skewX,o.skewX,a,l),function(e,t,i,s,n,o){if(e!==i||t!==s){var a=n.push(r(n)+"scale(",null,",",null,")");o.push({i:a-4,x:Qm(e,i)},{i:a-2,x:Qm(t,s)})}else 1===i&&1===s||n.push(r(n)+"scale("+i+","+s+")")}(n.scaleX,n.scaleY,o.scaleX,o.scaleY,a,l),n=o=null,function(e){for(var t,i=-1,s=l.length;++i<s;)a[(t=l[i]).i]=t.x(e);return a.join("")}}}var l_=a_(function(e){const t=new("function"==typeof DOMMatrix?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?n_:o_(t.a,t.b,t.c,t.d,t.e,t.f)},"px, ","px)","deg)"),c_=a_(function(e){return null==e?n_:(s_||(s_=document.createElementNS("http://www.w3.org/2000/svg","g")),s_.setAttribute("transform",e),(e=s_.transform.baseVal.consolidate())?o_((e=e.matrix).a,e.b,e.c,e.d,e.e,e.f):n_)},", ",")",")");function h_(e){return((e=Math.exp(e))+1/e)/2}const d_=function e(t,i,s){function r(e,r){var n,o,a=e[0],l=e[1],c=e[2],h=r[0],d=r[1],u=r[2],f=h-a,p=d-l,m=f*f+p*p;if(m<1e-12)o=Math.log(u/c)/t,n=function(e){return[a+e*f,l+e*p,c*Math.exp(t*e*o)]};else{var _=Math.sqrt(m),g=(u*u-c*c+s*m)/(2*c*i*_),v=(u*u-c*c-s*m)/(2*u*i*_),y=Math.log(Math.sqrt(g*g+1)-g),x=Math.log(Math.sqrt(v*v+1)-v);o=(x-y)/t,n=function(e){var s,r=e*o,n=h_(y),h=c/(i*_)*(n*(s=t*r+y,((s=Math.exp(2*s))-1)/(s+1))-function(e){return((e=Math.exp(e))-1/e)/2}(y));return[a+h*f,l+h*p,c*n/h_(t*r+y)]}}return n.duration=1e3*o*t/Math.SQRT2,n}return r.rho=function(t){var i=Math.max(.001,+t),s=i*i;return e(i,s,s*s)},r}(Math.SQRT2,2,4);var u_,f_,p_=0,m_=0,__=0,g_=0,v_=0,y_=0,x_="object"==typeof performance&&performance.now?performance:Date,b_="object"==typeof window&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function w_(){return v_||(b_(S_),v_=x_.now()+y_)}function S_(){v_=0}function C_(){this._call=this._time=this._next=null}function k_(e,t,i){var s=new C_;return s.restart(e,t,i),s}function E_(){v_=(g_=x_.now())+y_,p_=m_=0;try{!function(){w_(),++p_;for(var e,t=u_;t;)(e=v_-t._time)>=0&&t._call.call(void 0,e),t=t._next;--p_}()}finally{p_=0,function(){var e,t,i=u_,s=1/0;for(;i;)i._call?(s>i._time&&(s=i._time),e=i,i=i._next):(t=i._next,i._next=null,i=e?e._next=t:u_=t);f_=e,M_(s)}(),v_=0}}function N_(){var e=x_.now(),t=e-g_;t>1e3&&(y_-=t,g_=e)}function M_(e){p_||(m_&&(m_=clearTimeout(m_)),e-v_>24?(e<1/0&&(m_=setTimeout(E_,e-x_.now()-y_)),__&&(__=clearInterval(__))):(__||(g_=x_.now(),__=setInterval(N_,1e3)),p_=1,b_(E_)))}function j_(e,t,i){var s=new C_;return t=null==t?0:+t,s.restart(i=>{s.stop(),e(i+t)},t,i),s}C_.prototype=k_.prototype={constructor:C_,restart:function(e,t,i){if("function"!=typeof e)throw new TypeError("callback is not a function");i=(null==i?w_():+i)+(null==t?0:+t),this._next||f_===this||(f_?f_._next=this:u_=this,f_=this),this._call=e,this._time=i,M_()},stop:function(){this._call&&(this._call=null,this._time=1/0,M_())}};var D_=zf("start","end","cancel","interrupt"),R_=[];function P_(e,t,i,s,r,n){var o=e.__transition;if(o){if(i in o)return}else e.__transition={};!function(e,t,i){var s,r=e.__transition;function n(e){i.state=1,i.timer.restart(o,i.delay,i.time),i.delay<=e&&o(e-i.delay)}function o(n){var c,h,d,u;if(1!==i.state)return l();for(c in r)if((u=r[c]).name===i.name){if(3===u.state)return j_(o);4===u.state?(u.state=6,u.timer.stop(),u.on.call("interrupt",e,e.__data__,u.index,u.group),delete r[c]):+c<t&&(u.state=6,u.timer.stop(),u.on.call("cancel",e,e.__data__,u.index,u.group),delete r[c])}if(j_(function(){3===i.state&&(i.state=4,i.timer.restart(a,i.delay,i.time),a(n))}),i.state=2,i.on.call("start",e,e.__data__,i.index,i.group),2===i.state){for(i.state=3,s=new Array(d=i.tween.length),c=0,h=-1;c<d;++c)(u=i.tween[c].value.call(e,e.__data__,i.index,i.group))&&(s[++h]=u);s.length=h+1}}function a(t){for(var r=t<i.duration?i.ease.call(null,t/i.duration):(i.timer.restart(l),i.state=5,1),n=-1,o=s.length;++n<o;)s[n].call(e,r);5===i.state&&(i.on.call("end",e,e.__data__,i.index,i.group),l())}function l(){for(var s in i.state=6,i.timer.stop(),delete r[t],r)return;delete e.__transition}r[t]=i,i.timer=k_(n,0,i.time)}(e,i,{name:t,index:s,group:r,on:D_,tween:R_,time:n.time,delay:n.delay,duration:n.duration,ease:n.ease,timer:null,state:0})}function L_(e,t){var i=T_(e,t);if(i.state>0)throw new Error("too late; already scheduled");return i}function I_(e,t){var i=T_(e,t);if(i.state>3)throw new Error("too late; already running");return i}function T_(e,t){var i=e.__transition;if(!i||!(i=i[t]))throw new Error("transition not found");return i}function B_(e,t){var i,s,r,n=e.__transition,o=!0;if(n){for(r in t=null==t?null:t+"",n)(i=n[r]).name===t?(s=i.state>2&&i.state<5,i.state=6,i.timer.stop(),i.on.call(s?"interrupt":"cancel",e,e.__data__,i.index,i.group),delete n[r]):o=!1;o&&delete e.__transition}}function O_(e,t){var i,s;return function(){var r=I_(this,e),n=r.tween;if(n!==i)for(var o=0,a=(s=i=n).length;o<a;++o)if(s[o].name===t){(s=s.slice()).splice(o,1);break}r.tween=s}}function A_(e,t,i){var s,r;if("function"!=typeof i)throw new Error;return function(){var n=I_(this,e),o=n.tween;if(o!==s){r=(s=o).slice();for(var a={name:t,value:i},l=0,c=r.length;l<c;++l)if(r[l].name===t){r[l]=a;break}l===c&&r.push(a)}n.tween=r}}function z_(e,t,i){var s=e._id;return e.each(function(){var e=I_(this,s);(e.value||(e.value={}))[t]=i.apply(this,arguments)}),function(e){return T_(e,s).value[t]}}function $_(e,t){var i;return("number"==typeof t?Qm:t instanceof Lm?Jm:(i=Lm(t))?(t=i,Jm):i_)(e,t)}function H_(e){return function(){this.removeAttribute(e)}}function W_(e){return function(){this.removeAttributeNS(e.space,e.local)}}function F_(e,t,i){var s,r,n=i+"";return function(){var o=this.getAttribute(e);return o===n?null:o===s?r:r=t(s=o,i)}}function K_(e,t,i){var s,r,n=i+"";return function(){var o=this.getAttributeNS(e.space,e.local);return o===n?null:o===s?r:r=t(s=o,i)}}function U_(e,t,i){var s,r,n;return function(){var o,a,l=i(this);if(null!=l)return(o=this.getAttribute(e))===(a=l+"")?null:o===s&&a===r?n:(r=a,n=t(s=o,l));this.removeAttribute(e)}}function V_(e,t,i){var s,r,n;return function(){var o,a,l=i(this);if(null!=l)return(o=this.getAttributeNS(e.space,e.local))===(a=l+"")?null:o===s&&a===r?n:(r=a,n=t(s=o,l));this.removeAttributeNS(e.space,e.local)}}function q_(e,t){var i,s;function r(){var r=t.apply(this,arguments);return r!==s&&(i=(s=r)&&function(e,t){return function(i){this.setAttributeNS(e.space,e.local,t.call(this,i))}}(e,r)),i}return r._value=t,r}function Y_(e,t){var i,s;function r(){var r=t.apply(this,arguments);return r!==s&&(i=(s=r)&&function(e,t){return function(i){this.setAttribute(e,t.call(this,i))}}(e,r)),i}return r._value=t,r}function X_(e,t){return function(){L_(this,e).delay=+t.apply(this,arguments)}}function G_(e,t){return t=+t,function(){L_(this,e).delay=t}}function Z_(e,t){return function(){I_(this,e).duration=+t.apply(this,arguments)}}function J_(e,t){return t=+t,function(){I_(this,e).duration=t}}var Q_=em.prototype.constructor;function eg(e){return function(){this.style.removeProperty(e)}}var tg=0;function ig(e,t,i,s){this._groups=e,this._parents=t,this._name=i,this._id=s}function sg(){return++tg}var rg=em.prototype;ig.prototype={constructor:ig,select:function(e){var t=this._name,i=this._id;"function"!=typeof e&&(e=Gf(e));for(var s=this._groups,r=s.length,n=new Array(r),o=0;o<r;++o)for(var a,l,c=s[o],h=c.length,d=n[o]=new Array(h),u=0;u<h;++u)(a=c[u])&&(l=e.call(a,a.__data__,u,c))&&("__data__"in a&&(l.__data__=a.__data__),d[u]=l,P_(d[u],t,i,u,d,T_(a,i)));return new ig(n,this._parents,t,i)},selectAll:function(e){var t=this._name,i=this._id;"function"!=typeof e&&(e=Jf(e));for(var s=this._groups,r=s.length,n=[],o=[],a=0;a<r;++a)for(var l,c=s[a],h=c.length,d=0;d<h;++d)if(l=c[d]){for(var u,f=e.call(l,l.__data__,d,c),p=T_(l,i),m=0,_=f.length;m<_;++m)(u=f[m])&&P_(u,t,i,m,f,p);n.push(f),o.push(l)}return new ig(n,o,t,i)},selectChild:rg.selectChild,selectChildren:rg.selectChildren,filter:function(e){"function"!=typeof e&&(e=ep(e));for(var t=this._groups,i=t.length,s=new Array(i),r=0;r<i;++r)for(var n,o=t[r],a=o.length,l=s[r]=[],c=0;c<a;++c)(n=o[c])&&e.call(n,n.__data__,c,o)&&l.push(n);return new ig(s,this._parents,this._name,this._id)},merge:function(e){if(e._id!==this._id)throw new Error;for(var t=this._groups,i=e._groups,s=t.length,r=i.length,n=Math.min(s,r),o=new Array(s),a=0;a<n;++a)for(var l,c=t[a],h=i[a],d=c.length,u=o[a]=new Array(d),f=0;f<d;++f)(l=c[f]||h[f])&&(u[f]=l);for(;a<s;++a)o[a]=t[a];return new ig(o,this._parents,this._name,this._id)},selection:function(){return new Q_(this._groups,this._parents)},transition:function(){for(var e=this._name,t=this._id,i=sg(),s=this._groups,r=s.length,n=0;n<r;++n)for(var o,a=s[n],l=a.length,c=0;c<l;++c)if(o=a[c]){var h=T_(o,t);P_(o,e,i,c,a,{time:h.time+h.delay+h.duration,delay:0,duration:h.duration,ease:h.ease})}return new ig(s,this._parents,e,i)},call:rg.call,nodes:rg.nodes,node:rg.node,size:rg.size,empty:rg.empty,each:rg.each,on:function(e,t){var i=this._id;return arguments.length<2?T_(this.node(),i).on.on(e):this.each(function(e,t,i){var s,r,n=function(e){return(e+"").trim().split(/^|\s+/).every(function(e){var t=e.indexOf(".");return t>=0&&(e=e.slice(0,t)),!e||"start"===e})}(t)?L_:I_;return function(){var o=n(this,e),a=o.on;a!==s&&(r=(s=a).copy()).on(t,i),o.on=r}}(i,e,t))},attr:function(e,t){var i=Uf(e),s="transform"===i?c_:$_;return this.attrTween(e,"function"==typeof t?(i.local?V_:U_)(i,s,z_(this,"attr."+e,t)):null==t?(i.local?W_:H_)(i):(i.local?K_:F_)(i,s,t))},attrTween:function(e,t){var i="attr."+e;if(arguments.length<2)return(i=this.tween(i))&&i._value;if(null==t)return this.tween(i,null);if("function"!=typeof t)throw new Error;var s=Uf(e);return this.tween(i,(s.local?q_:Y_)(s,t))},style:function(e,t,i){var s="transform"==(e+="")?l_:$_;return null==t?this.styleTween(e,function(e,t){var i,s,r;return function(){var n=Sp(this,e),o=(this.style.removeProperty(e),Sp(this,e));return n===o?null:n===i&&o===s?r:r=t(i=n,s=o)}}(e,s)).on("end.style."+e,eg(e)):"function"==typeof t?this.styleTween(e,function(e,t,i){var s,r,n;return function(){var o=Sp(this,e),a=i(this),l=a+"";return null==a&&(this.style.removeProperty(e),l=a=Sp(this,e)),o===l?null:o===s&&l===r?n:(r=l,n=t(s=o,a))}}(e,s,z_(this,"style."+e,t))).each(function(e,t){var i,s,r,n,o="style."+t,a="end."+o;return function(){var l=I_(this,e),c=l.on,h=null==l.value[o]?n||(n=eg(t)):void 0;c===i&&r===h||(s=(i=c).copy()).on(a,r=h),l.on=s}}(this._id,e)):this.styleTween(e,function(e,t,i){var s,r,n=i+"";return function(){var o=Sp(this,e);return o===n?null:o===s?r:r=t(s=o,i)}}(e,s,t),i).on("end.style."+e,null)},styleTween:function(e,t,i){var s="style."+(e+="");if(arguments.length<2)return(s=this.tween(s))&&s._value;if(null==t)return this.tween(s,null);if("function"!=typeof t)throw new Error;return this.tween(s,function(e,t,i){var s,r;function n(){var n=t.apply(this,arguments);return n!==r&&(s=(r=n)&&function(e,t,i){return function(s){this.style.setProperty(e,t.call(this,s),i)}}(e,n,i)),s}return n._value=t,n}(e,t,null==i?"":i))},text:function(e){return this.tween("text","function"==typeof e?function(e){return function(){var t=e(this);this.textContent=null==t?"":t}}(z_(this,"text",e)):function(e){return function(){this.textContent=e}}(null==e?"":e+""))},textTween:function(e){var t="text";if(arguments.length<1)return(t=this.tween(t))&&t._value;if(null==e)return this.tween(t,null);if("function"!=typeof e)throw new Error;return this.tween(t,function(e){var t,i;function s(){var s=e.apply(this,arguments);return s!==i&&(t=(i=s)&&function(e){return function(t){this.textContent=e.call(this,t)}}(s)),t}return s._value=e,s}(e))},remove:function(){return this.on("end.remove",(e=this._id,function(){var t=this.parentNode;for(var i in this.__transition)if(+i!==e)return;t&&t.removeChild(this)}));var e},tween:function(e,t){var i=this._id;if(e+="",arguments.length<2){for(var s,r=T_(this.node(),i).tween,n=0,o=r.length;n<o;++n)if((s=r[n]).name===e)return s.value;return null}return this.each((null==t?O_:A_)(i,e,t))},delay:function(e){var t=this._id;return arguments.length?this.each(("function"==typeof e?X_:G_)(t,e)):T_(this.node(),t).delay},duration:function(e){var t=this._id;return arguments.length?this.each(("function"==typeof e?Z_:J_)(t,e)):T_(this.node(),t).duration},ease:function(e){var t=this._id;return arguments.length?this.each(function(e,t){if("function"!=typeof t)throw new Error;return function(){I_(this,e).ease=t}}(t,e)):T_(this.node(),t).ease},easeVarying:function(e){if("function"!=typeof e)throw new Error;return this.each(function(e,t){return function(){var i=t.apply(this,arguments);if("function"!=typeof i)throw new Error;I_(this,e).ease=i}}(this._id,e))},end:function(){var e,t,i=this,s=i._id,r=i.size();return new Promise(function(n,o){var a={value:o},l={value:function(){0===--r&&n()}};i.each(function(){var i=I_(this,s),r=i.on;r!==e&&((t=(e=r).copy())._.cancel.push(a),t._.interrupt.push(a),t._.end.push(l)),i.on=t}),0===r&&n()})},[Symbol.iterator]:rg[Symbol.iterator]};var ng={time:null,delay:0,duration:250,ease:function(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}};function og(e,t){for(var i;!(i=e.__transition)||!(i=i[t]);)if(!(e=e.parentNode))throw new Error(`transition ${t} not found`);return i}em.prototype.interrupt=function(e){return this.each(function(){B_(this,e)})},em.prototype.transition=function(e){var t,i;e instanceof ig?(t=e._id,e=e._name):(t=sg(),(i=ng).time=w_(),e=null==e?null:e+"");for(var s=this._groups,r=s.length,n=0;n<r;++n)for(var o,a=s[n],l=a.length,c=0;c<l;++c)(o=a[c])&&P_(o,e,t,c,a,i||og(o,t));return new ig(s,this._parents,e,t)};const ag=e=>()=>e;function lg(e,{sourceEvent:t,target:i,transform:s,dispatch:r}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},target:{value:i,enumerable:!0,configurable:!0},transform:{value:s,enumerable:!0,configurable:!0},_:{value:r}})}function cg(e,t,i){this.k=e,this.x=t,this.y=i}cg.prototype={constructor:cg,scale:function(e){return 1===e?this:new cg(this.k*e,this.x,this.y)},translate:function(e,t){return 0===e&0===t?this:new cg(this.k,this.x+this.k*e,this.y+this.k*t)},apply:function(e){return[e[0]*this.k+this.x,e[1]*this.k+this.y]},applyX:function(e){return e*this.k+this.x},applyY:function(e){return e*this.k+this.y},invert:function(e){return[(e[0]-this.x)/this.k,(e[1]-this.y)/this.k]},invertX:function(e){return(e-this.x)/this.k},invertY:function(e){return(e-this.y)/this.k},rescaleX:function(e){return e.copy().domain(e.range().map(this.invertX,this).map(e.invert,e))},rescaleY:function(e){return e.copy().domain(e.range().map(this.invertY,this).map(e.invert,e))},toString:function(){return"translate("+this.x+","+this.y+") scale("+this.k+")"}};var hg=new cg(1,0,0);function dg(e){e.stopImmediatePropagation()}function ug(e){e.preventDefault(),e.stopImmediatePropagation()}function fg(e){return!(e.ctrlKey&&"wheel"!==e.type||e.button)}function pg(){var e=this;return e instanceof SVGElement?(e=e.ownerSVGElement||e).hasAttribute("viewBox")?[[(e=e.viewBox.baseVal).x,e.y],[e.x+e.width,e.y+e.height]]:[[0,0],[e.width.baseVal.value,e.height.baseVal.value]]:[[0,0],[e.clientWidth,e.clientHeight]]}function mg(){return this.__zoom||hg}function _g(e){return-e.deltaY*(1===e.deltaMode?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function gg(){return navigator.maxTouchPoints||"ontouchstart"in this}function vg(e,t,i){var s=e.invertX(t[0][0])-i[0][0],r=e.invertX(t[1][0])-i[1][0],n=e.invertY(t[0][1])-i[0][1],o=e.invertY(t[1][1])-i[1][1];return e.translate(r>s?(s+r)/2:Math.min(0,s)||Math.max(0,r),o>n?(n+o)/2:Math.min(0,n)||Math.max(0,o))}function yg(){var e,t,i,s=fg,r=pg,n=vg,o=_g,a=gg,l=[0,1/0],c=[[-1/0,-1/0],[1/0,1/0]],h=250,d=d_,u=zf("start","zoom","end"),f=0,p=10;function m(e){e.property("__zoom",mg).on("wheel.zoom",w,{passive:!1}).on("mousedown.zoom",S).on("dblclick.zoom",C).filter(a).on("touchstart.zoom",k).on("touchmove.zoom",E).on("touchend.zoom touchcancel.zoom",N).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function _(e,t){return(t=Math.max(l[0],Math.min(l[1],t)))===e.k?e:new cg(t,e.x,e.y)}function g(e,t,i){var s=t[0]-i[0]*e.k,r=t[1]-i[1]*e.k;return s===e.x&&r===e.y?e:new cg(e.k,s,r)}function v(e){return[(+e[0][0]+ +e[1][0])/2,(+e[0][1]+ +e[1][1])/2]}function y(e,t,i,s){e.on("start.zoom",function(){x(this,arguments).event(s).start()}).on("interrupt.zoom end.zoom",function(){x(this,arguments).event(s).end()}).tween("zoom",function(){var e=this,n=arguments,o=x(e,n).event(s),a=r.apply(e,n),l=null==i?v(a):"function"==typeof i?i.apply(e,n):i,c=Math.max(a[1][0]-a[0][0],a[1][1]-a[0][1]),h=e.__zoom,u="function"==typeof t?t.apply(e,n):t,f=d(h.invert(l).concat(c/h.k),u.invert(l).concat(c/u.k));return function(e){if(1===e)e=u;else{var t=f(e),i=c/t[2];e=new cg(i,l[0]-t[0]*i,l[1]-t[1]*i)}o.zoom(null,e)}})}function x(e,t,i){return!i&&e.__zooming||new b(e,t)}function b(e,t){this.that=e,this.args=t,this.active=0,this.sourceEvent=null,this.extent=r.apply(e,t),this.taps=0}function w(e,...t){if(s.apply(this,arguments)){var i=x(this,t).event(e),r=this.__zoom,a=Math.max(l[0],Math.min(l[1],r.k*Math.pow(2,o.apply(this,arguments)))),h=im(e);if(i.wheel)i.mouse[0][0]===h[0]&&i.mouse[0][1]===h[1]||(i.mouse[1]=r.invert(i.mouse[0]=h)),clearTimeout(i.wheel);else{if(r.k===a)return;i.mouse=[h,r.invert(h)],B_(this),i.start()}ug(e),i.wheel=setTimeout(function(){i.wheel=null,i.end()},150),i.zoom("mouse",n(g(_(r,a),i.mouse[0],i.mouse[1]),i.extent,c))}}function S(e,...t){if(!i&&s.apply(this,arguments)){var r=e.currentTarget,o=x(this,t,!0).event(e),a=tm(e.view).on("mousemove.zoom",function(e){if(ug(e),!o.moved){var t=e.clientX-h,i=e.clientY-d;o.moved=t*t+i*i>f}o.event(e).zoom("mouse",n(g(o.that.__zoom,o.mouse[0]=im(e,r),o.mouse[1]),o.extent,c))},!0).on("mouseup.zoom",function(e){a.on("mousemove.zoom mouseup.zoom",null),lm(e.view,o.moved),ug(e),o.event(e).end()},!0),l=im(e,r),h=e.clientX,d=e.clientY;am(e.view),dg(e),o.mouse=[l,this.__zoom.invert(l)],B_(this),o.start()}}function C(e,...t){if(s.apply(this,arguments)){var i=this.__zoom,o=im(e.changedTouches?e.changedTouches[0]:e,this),a=i.invert(o),l=i.k*(e.shiftKey?.5:2),d=n(g(_(i,l),o,a),r.apply(this,t),c);ug(e),h>0?tm(this).transition().duration(h).call(y,d,o,e):tm(this).call(m.transform,d,o,e)}}function k(i,...r){if(s.apply(this,arguments)){var n,o,a,l,c=i.touches,h=c.length,d=x(this,r,i.changedTouches.length===h).event(i);for(dg(i),o=0;o<h;++o)l=[l=im(a=c[o],this),this.__zoom.invert(l),a.identifier],d.touch0?d.touch1||d.touch0[2]===l[2]||(d.touch1=l,d.taps=0):(d.touch0=l,n=!0,d.taps=1+!!e);e&&(e=clearTimeout(e)),n&&(d.taps<2&&(t=l[0],e=setTimeout(function(){e=null},500)),B_(this),d.start())}}function E(e,...t){if(this.__zooming){var i,s,r,o,a=x(this,t).event(e),l=e.changedTouches,h=l.length;for(ug(e),i=0;i<h;++i)r=im(s=l[i],this),a.touch0&&a.touch0[2]===s.identifier?a.touch0[0]=r:a.touch1&&a.touch1[2]===s.identifier&&(a.touch1[0]=r);if(s=a.that.__zoom,a.touch1){var d=a.touch0[0],u=a.touch0[1],f=a.touch1[0],p=a.touch1[1],m=(m=f[0]-d[0])*m+(m=f[1]-d[1])*m,v=(v=p[0]-u[0])*v+(v=p[1]-u[1])*v;s=_(s,Math.sqrt(m/v)),r=[(d[0]+f[0])/2,(d[1]+f[1])/2],o=[(u[0]+p[0])/2,(u[1]+p[1])/2]}else{if(!a.touch0)return;r=a.touch0[0],o=a.touch0[1]}a.zoom("touch",n(g(s,r,o),a.extent,c))}}function N(e,...s){if(this.__zooming){var r,n,o=x(this,s).event(e),a=e.changedTouches,l=a.length;for(dg(e),i&&clearTimeout(i),i=setTimeout(function(){i=null},500),r=0;r<l;++r)n=a[r],o.touch0&&o.touch0[2]===n.identifier?delete o.touch0:o.touch1&&o.touch1[2]===n.identifier&&delete o.touch1;if(o.touch1&&!o.touch0&&(o.touch0=o.touch1,delete o.touch1),o.touch0)o.touch0[1]=this.__zoom.invert(o.touch0[0]);else if(o.end(),2===o.taps&&(n=im(n,this),Math.hypot(t[0]-n[0],t[1]-n[1])<p)){var c=tm(this).on("dblclick.zoom");c&&c.apply(this,arguments)}}}return m.transform=function(e,t,i,s){var r=e.selection?e.selection():e;r.property("__zoom",mg),e!==r?y(e,t,i,s):r.interrupt().each(function(){x(this,arguments).event(s).start().zoom(null,"function"==typeof t?t.apply(this,arguments):t).end()})},m.scaleBy=function(e,t,i,s){m.scaleTo(e,function(){return this.__zoom.k*("function"==typeof t?t.apply(this,arguments):t)},i,s)},m.scaleTo=function(e,t,i,s){m.transform(e,function(){var e=r.apply(this,arguments),s=this.__zoom,o=null==i?v(e):"function"==typeof i?i.apply(this,arguments):i,a=s.invert(o),l="function"==typeof t?t.apply(this,arguments):t;return n(g(_(s,l),o,a),e,c)},i,s)},m.translateBy=function(e,t,i,s){m.transform(e,function(){return n(this.__zoom.translate("function"==typeof t?t.apply(this,arguments):t,"function"==typeof i?i.apply(this,arguments):i),r.apply(this,arguments),c)},null,s)},m.translateTo=function(e,t,i,s,o){m.transform(e,function(){var e=r.apply(this,arguments),o=this.__zoom,a=null==s?v(e):"function"==typeof s?s.apply(this,arguments):s;return n(hg.translate(a[0],a[1]).scale(o.k).translate("function"==typeof t?-t.apply(this,arguments):-t,"function"==typeof i?-i.apply(this,arguments):-i),e,c)},s,o)},b.prototype={event:function(e){return e&&(this.sourceEvent=e),this},start:function(){return 1===++this.active&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(e,t){return this.mouse&&"mouse"!==e&&(this.mouse[1]=t.invert(this.mouse[0])),this.touch0&&"touch"!==e&&(this.touch0[1]=t.invert(this.touch0[0])),this.touch1&&"touch"!==e&&(this.touch1[1]=t.invert(this.touch1[0])),this.that.__zoom=t,this.emit("zoom"),this},end:function(){return 0===--this.active&&(delete this.that.__zooming,this.emit("end")),this},emit:function(e){var t=tm(this.that).datum();u.call(e,this.that,new lg(e,{sourceEvent:this.sourceEvent,target:m,transform:this.that.__zoom,dispatch:u}),t)}},m.wheelDelta=function(e){return arguments.length?(o="function"==typeof e?e:ag(+e),m):o},m.filter=function(e){return arguments.length?(s="function"==typeof e?e:ag(!!e),m):s},m.touchable=function(e){return arguments.length?(a="function"==typeof e?e:ag(!!e),m):a},m.extent=function(e){return arguments.length?(r="function"==typeof e?e:ag([[+e[0][0],+e[0][1]],[+e[1][0],+e[1][1]]]),m):r},m.scaleExtent=function(e){return arguments.length?(l[0]=+e[0],l[1]=+e[1],m):[l[0],l[1]]},m.translateExtent=function(e){return arguments.length?(c[0][0]=+e[0][0],c[1][0]=+e[1][0],c[0][1]=+e[0][1],c[1][1]=+e[1][1],m):[[c[0][0],c[0][1]],[c[1][0],c[1][1]]]},m.constrain=function(e){return arguments.length?(n=e,m):n},m.duration=function(e){return arguments.length?(h=+e,m):h},m.interpolate=function(e){return arguments.length?(d=e,m):d},m.on=function(){var e=u.on.apply(u,arguments);return e===u?m:e},m.clickDistance=function(e){return arguments.length?(f=(e=+e)*e,m):Math.sqrt(f)},m.tapDistance=function(e){return arguments.length?(p=+e,m):p},m}cg.prototype;const xg=h.createContext(null),bg=xg.Provider,wg=e=>`Node type "${e}" not found. Using fallback type "default".`,Sg=()=>"The React Flow parent container needs a width and a height to render the graph.",Cg=()=>"Only child nodes can use a parent extent.",kg=e=>`Marker type "${e}" doesn't exist.`,Eg=(e,t)=>`Couldn't create edge for ${e?"target":"source"} handle id: "${e?t.targetHandle:t.sourceHandle}", edge id: ${t.id}.`,Ng=()=>"Handle: No node id found. Make sure to only use a Handle inside a custom Node.",Mg=e=>`Edge type "${e}" not found. Using fallback type "default".`,jg=e=>`Node with id "${e}" does not exist, it may have been removed. This can happen when a node is deleted before the "onNodeClick" handler is called.`,Dg=(()=>"[React Flow]: Seems like you have not used zustand provider as an ancestor. Help: https://reactflow.dev/error#001")();function Rg(e,t){const i=h.useContext(xg);if(null===i)throw new Error(Dg);return Tf(i,e,t)}const Pg=()=>{const e=h.useContext(xg);if(null===e)throw new Error(Dg);return h.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe,destroy:e.destroy}),[e])},Lg=e=>e.userSelectionActive?"none":"all";function Ig({position:e,children:t,className:i,style:s,...r}){const n=Rg(Lg),o=`${e}`.split("-");return N.createElement("div",{className:vf(["react-flow__panel",i,...o]),style:{...s,pointerEvents:n},...r},t)}function Tg({proOptions:e,position:t="bottom-right"}){return(null==e?void 0:e.hideAttribution)?null:N.createElement(Ig,{position:t,className:"react-flow__attribution","data-message":"Please only hide this attribution when you are subscribed to React Flow Pro: https://reactflow.dev/pro"},N.createElement("a",{href:"https://reactflow.dev",target:"_blank",rel:"noopener noreferrer","aria-label":"React Flow attribution"},"React Flow"))}var Bg=h.memo(({x:e,y:t,label:i,labelStyle:s={},labelShowBg:r=!0,labelBgStyle:n={},labelBgPadding:o=[2,4],labelBgBorderRadius:a=2,children:l,className:c,...d})=>{const u=h.useRef(null),[f,p]=h.useState({x:0,y:0,width:0,height:0}),m=vf(["react-flow__edge-textwrapper",c]);return h.useEffect(()=>{if(u.current){const e=u.current.getBBox();p({x:e.x,y:e.y,width:e.width,height:e.height})}},[i]),void 0!==i&&i?N.createElement("g",{transform:`translate(${e-f.width/2} ${t-f.height/2})`,className:m,visibility:f.width?"visible":"hidden",...d},r&&N.createElement("rect",{width:f.width+2*o[0],x:-o[0],y:-o[1],height:f.height+2*o[1],className:"react-flow__edge-textbg",style:n,rx:a,ry:a}),N.createElement("text",{className:"react-flow__edge-text",y:f.height/2,dy:"0.3em",ref:u,style:s},i),l):null});const Og=e=>({width:e.offsetWidth,height:e.offsetHeight}),Ag=(e,t=0,i=1)=>Math.min(Math.max(e,t),i),zg=(e={x:0,y:0},t)=>({x:Ag(e.x,t[0][0],t[1][0]),y:Ag(e.y,t[0][1],t[1][1])}),$g=(e,t,i)=>e<t?Ag(Math.abs(e-t),1,50)/50:e>i?-Ag(Math.abs(e-i),1,50)/50:0,Hg=(e,t)=>[20*$g(e.x,35,t.width-35),20*$g(e.y,35,t.height-35)],Wg=e=>{var t;return(null==(t=e.getRootNode)?void 0:t.call(e))||(null==window?void 0:window.document)},Fg=(e,t)=>({x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),x2:Math.max(e.x2,t.x2),y2:Math.max(e.y2,t.y2)}),Kg=({x:e,y:t,width:i,height:s})=>({x:e,y:t,x2:e+i,y2:t+s}),Ug=({x:e,y:t,x2:i,y2:s})=>({x:e,y:t,width:i-e,height:s-t}),Vg=e=>({...e.positionAbsolute||{x:0,y:0},width:e.width||0,height:e.height||0}),qg=(e,t)=>{const i=Math.max(0,Math.min(e.x+e.width,t.x+t.width)-Math.max(e.x,t.x)),s=Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y));return Math.ceil(i*s)},Yg=e=>!isNaN(e)&&isFinite(e),Xg=Symbol.for("internals"),Gg=["Enter"," ","Escape"];function Zg(e){var t,i;const s=(e=>"nativeEvent"in e)(e)?e.nativeEvent:e,r=(null==(i=null==(t=s.composedPath)?void 0:t.call(s))?void 0:i[0])||e.target;return["INPUT","SELECT","TEXTAREA"].includes(null==r?void 0:r.nodeName)||(null==r?void 0:r.hasAttribute("contenteditable"))||!!(null==r?void 0:r.closest(".nokey"))}const Jg=e=>"clientX"in e,Qg=(e,t)=>{var i,s;const r=Jg(e),n=r?e.clientX:null==(i=e.touches)?void 0:i[0].clientX,o=r?e.clientY:null==(s=e.touches)?void 0:s[0].clientY;return{x:n-((null==t?void 0:t.left)??0),y:o-((null==t?void 0:t.top)??0)}},ev=()=>{var e;return"undefined"!=typeof navigator&&(null==(e=null==navigator?void 0:navigator.userAgent)?void 0:e.indexOf("Mac"))>=0},tv=({id:e,path:t,labelX:i,labelY:s,label:r,labelStyle:n,labelShowBg:o,labelBgStyle:a,labelBgPadding:l,labelBgBorderRadius:c,style:h,markerEnd:d,markerStart:u,interactionWidth:f=20})=>N.createElement(N.Fragment,null,N.createElement("path",{id:e,style:h,d:t,fill:"none",className:"react-flow__edge-path",markerEnd:d,markerStart:u}),f&&N.createElement("path",{d:t,fill:"none",strokeOpacity:0,strokeWidth:f,className:"react-flow__edge-interaction"}),r&&Yg(i)&&Yg(s)?N.createElement(Bg,{x:i,y:s,label:r,labelStyle:n,labelShowBg:o,labelBgStyle:a,labelBgPadding:l,labelBgBorderRadius:c}):null);function iv(e,t,i){return void 0===i?i:s=>{const r=t().edges.find(t=>t.id===e);r&&i(s,{...r})}}function sv({sourceX:e,sourceY:t,targetX:i,targetY:s}){const r=Math.abs(i-e)/2,n=i<e?i+r:i-r,o=Math.abs(s-t)/2;return[n,s<t?s+o:s-o,r,o]}function rv({sourceX:e,sourceY:t,targetX:i,targetY:s,sourceControlX:r,sourceControlY:n,targetControlX:o,targetControlY:a}){const l=.125*e+.375*r+.375*o+.125*i,c=.125*t+.375*n+.375*a+.125*s;return[l,c,Math.abs(l-e),Math.abs(c-t)]}var nv,ov,av,lv,cv,hv,dv,uv,fv,pv,mv,_v;function gv({pos:e,x1:t,y1:i,x2:s,y2:r}){return e===mv.Left||e===mv.Right?[.5*(t+s),i]:[t,.5*(i+r)]}function vv({sourceX:e,sourceY:t,sourcePosition:i=mv.Bottom,targetX:s,targetY:r,targetPosition:n=mv.Top}){const[o,a]=gv({pos:i,x1:e,y1:t,x2:s,y2:r}),[l,c]=gv({pos:n,x1:s,y1:r,x2:e,y2:t}),[h,d,u,f]=rv({sourceX:e,sourceY:t,targetX:s,targetY:r,sourceControlX:o,sourceControlY:a,targetControlX:l,targetControlY:c});return[`M${e},${t} C${o},${a} ${l},${c} ${s},${r}`,h,d,u,f]}tv.displayName="BaseEdge",(ov=nv||(nv={})).Strict="strict",ov.Loose="loose",(lv=av||(av={})).Free="free",lv.Vertical="vertical",lv.Horizontal="horizontal",(hv=cv||(cv={})).Partial="partial",hv.Full="full",(uv=dv||(dv={})).Bezier="default",uv.Straight="straight",uv.Step="step",uv.SmoothStep="smoothstep",uv.SimpleBezier="simplebezier",(pv=fv||(fv={})).Arrow="arrow",pv.ArrowClosed="arrowclosed",(_v=mv||(mv={})).Left="left",_v.Top="top",_v.Right="right",_v.Bottom="bottom";const yv=h.memo(({sourceX:e,sourceY:t,targetX:i,targetY:s,sourcePosition:r=mv.Bottom,targetPosition:n=mv.Top,label:o,labelStyle:a,labelShowBg:l,labelBgStyle:c,labelBgPadding:h,labelBgBorderRadius:d,style:u,markerEnd:f,markerStart:p,interactionWidth:m})=>{const[_,g,v]=vv({sourceX:e,sourceY:t,sourcePosition:r,targetX:i,targetY:s,targetPosition:n});return N.createElement(tv,{path:_,labelX:g,labelY:v,label:o,labelStyle:a,labelShowBg:l,labelBgStyle:c,labelBgPadding:h,labelBgBorderRadius:d,style:u,markerEnd:f,markerStart:p,interactionWidth:m})});yv.displayName="SimpleBezierEdge";const xv={[mv.Left]:{x:-1,y:0},[mv.Right]:{x:1,y:0},[mv.Top]:{x:0,y:-1},[mv.Bottom]:{x:0,y:1}},bv=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function wv({source:e,sourcePosition:t=mv.Bottom,target:i,targetPosition:s=mv.Top,center:r,offset:n}){const o=xv[t],a=xv[s],l={x:e.x+o.x*n,y:e.y+o.y*n},c={x:i.x+a.x*n,y:i.y+a.y*n},h=(({source:e,sourcePosition:t=mv.Bottom,target:i})=>t===mv.Left||t===mv.Right?e.x<i.x?{x:1,y:0}:{x:-1,y:0}:e.y<i.y?{x:0,y:1}:{x:0,y:-1})({source:l,sourcePosition:t,target:c}),d=0!==h.x?"x":"y",u=h[d];let f,p,m=[];const _={x:0,y:0},g={x:0,y:0},[v,y,x,b]=sv({sourceX:e.x,sourceY:e.y,targetX:i.x,targetY:i.y});if(o[d]*a[d]===-1){f=r.x??v,p=r.y??y;const e=[{x:f,y:l.y},{x:f,y:c.y}],t=[{x:l.x,y:p},{x:c.x,y:p}];m=o[d]===u?"x"===d?e:t:"x"===d?t:e}else{const r=[{x:l.x,y:c.y}],h=[{x:c.x,y:l.y}];if(m="x"===d?o.x===u?h:r:o.y===u?r:h,t===s){const t=Math.abs(e[d]-i[d]);if(t<=n){const s=Math.min(n-1,n-t);o[d]===u?_[d]=(l[d]>e[d]?-1:1)*s:g[d]=(c[d]>i[d]?-1:1)*s}}if(t!==s){const e="x"===d?"y":"x",t=o[d]===a[e],i=l[e]>c[e],s=l[e]<c[e];(1===o[d]&&(!t&&i||t&&s)||1!==o[d]&&(!t&&s||t&&i))&&(m="x"===d?r:h)}const v={x:l.x+_.x,y:l.y+_.y},y={x:c.x+g.x,y:c.y+g.y};Math.max(Math.abs(v.x-m[0].x),Math.abs(y.x-m[0].x))>=Math.max(Math.abs(v.y-m[0].y),Math.abs(y.y-m[0].y))?(f=(v.x+y.x)/2,p=m[0].y):(f=m[0].x,p=(v.y+y.y)/2)}return[[e,{x:l.x+_.x,y:l.y+_.y},...m,{x:c.x+g.x,y:c.y+g.y},i],f,p,x,b]}function Sv({sourceX:e,sourceY:t,sourcePosition:i=mv.Bottom,targetX:s,targetY:r,targetPosition:n=mv.Top,borderRadius:o=5,centerX:a,centerY:l,offset:c=20}){const[h,d,u,f,p]=wv({source:{x:e,y:t},sourcePosition:i,target:{x:s,y:r},targetPosition:n,center:{x:a,y:l},offset:c}),m=h.reduce((e,t,i)=>{let s="";return s=i>0&&i<h.length-1?function(e,t,i,s){const r=Math.min(bv(e,t)/2,bv(t,i)/2,s),{x:n,y:o}=t;if(e.x===n&&n===i.x||e.y===o&&o===i.y)return`L${n} ${o}`;if(e.y===o)return`L ${n+r*(e.x<i.x?-1:1)},${o}Q ${n},${o} ${n},${o+r*(e.y<i.y?1:-1)}`;const a=e.x<i.x?1:-1;return`L ${n},${o+r*(e.y<i.y?-1:1)}Q ${n},${o} ${n+r*a},${o}`}(h[i-1],t,h[i+1],o):`${0===i?"M":"L"}${t.x} ${t.y}`,e+=s},"");return[m,d,u,f,p]}const Cv=h.memo(({sourceX:e,sourceY:t,targetX:i,targetY:s,label:r,labelStyle:n,labelShowBg:o,labelBgStyle:a,labelBgPadding:l,labelBgBorderRadius:c,style:h,sourcePosition:d=mv.Bottom,targetPosition:u=mv.Top,markerEnd:f,markerStart:p,pathOptions:m,interactionWidth:_})=>{const[g,v,y]=Sv({sourceX:e,sourceY:t,sourcePosition:d,targetX:i,targetY:s,targetPosition:u,borderRadius:null==m?void 0:m.borderRadius,offset:null==m?void 0:m.offset});return N.createElement(tv,{path:g,labelX:v,labelY:y,label:r,labelStyle:n,labelShowBg:o,labelBgStyle:a,labelBgPadding:l,labelBgBorderRadius:c,style:h,markerEnd:f,markerStart:p,interactionWidth:_})});Cv.displayName="SmoothStepEdge";const kv=h.memo(e=>{var t;return N.createElement(Cv,{...e,pathOptions:h.useMemo(()=>{var t;return{borderRadius:0,offset:null==(t=e.pathOptions)?void 0:t.offset}},[null==(t=e.pathOptions)?void 0:t.offset])})});kv.displayName="StepEdge";const Ev=h.memo(({sourceX:e,sourceY:t,targetX:i,targetY:s,label:r,labelStyle:n,labelShowBg:o,labelBgStyle:a,labelBgPadding:l,labelBgBorderRadius:c,style:h,markerEnd:d,markerStart:u,interactionWidth:f})=>{const[p,m,_]=function({sourceX:e,sourceY:t,targetX:i,targetY:s}){const[r,n,o,a]=sv({sourceX:e,sourceY:t,targetX:i,targetY:s});return[`M ${e},${t}L ${i},${s}`,r,n,o,a]}({sourceX:e,sourceY:t,targetX:i,targetY:s});return N.createElement(tv,{path:p,labelX:m,labelY:_,label:r,labelStyle:n,labelShowBg:o,labelBgStyle:a,labelBgPadding:l,labelBgBorderRadius:c,style:h,markerEnd:d,markerStart:u,interactionWidth:f})});function Nv(e,t){return e>=0?.5*e:25*t*Math.sqrt(-e)}function Mv({pos:e,x1:t,y1:i,x2:s,y2:r,c:n}){switch(e){case mv.Left:return[t-Nv(t-s,n),i];case mv.Right:return[t+Nv(s-t,n),i];case mv.Top:return[t,i-Nv(i-r,n)];case mv.Bottom:return[t,i+Nv(r-i,n)]}}function jv({sourceX:e,sourceY:t,sourcePosition:i=mv.Bottom,targetX:s,targetY:r,targetPosition:n=mv.Top,curvature:o=.25}){const[a,l]=Mv({pos:i,x1:e,y1:t,x2:s,y2:r,c:o}),[c,h]=Mv({pos:n,x1:s,y1:r,x2:e,y2:t,c:o}),[d,u,f,p]=rv({sourceX:e,sourceY:t,targetX:s,targetY:r,sourceControlX:a,sourceControlY:l,targetControlX:c,targetControlY:h});return[`M${e},${t} C${a},${l} ${c},${h} ${s},${r}`,d,u,f,p]}Ev.displayName="StraightEdge";const Dv=h.memo(({sourceX:e,sourceY:t,targetX:i,targetY:s,sourcePosition:r=mv.Bottom,targetPosition:n=mv.Top,label:o,labelStyle:a,labelShowBg:l,labelBgStyle:c,labelBgPadding:h,labelBgBorderRadius:d,style:u,markerEnd:f,markerStart:p,pathOptions:m,interactionWidth:_})=>{const[g,v,y]=jv({sourceX:e,sourceY:t,sourcePosition:r,targetX:i,targetY:s,targetPosition:n,curvature:null==m?void 0:m.curvature});return N.createElement(tv,{path:g,labelX:v,labelY:y,label:o,labelStyle:a,labelShowBg:l,labelBgStyle:c,labelBgPadding:h,labelBgBorderRadius:d,style:u,markerEnd:f,markerStart:p,interactionWidth:_})});Dv.displayName="BezierEdge";const Rv=h.createContext(null),Pv=Rv.Provider;Rv.Consumer;const Lv=({source:e,sourceHandle:t,target:i,targetHandle:s})=>`reactflow__edge-${e}${t||""}-${i}${s||""}`,Iv=(e,t)=>{if(void 0===e)return"";if("string"==typeof e)return e;return`${t?`${t}__`:""}${Object.keys(e).sort().map(t=>`${t}=${e[t]}`).join("&")}`},Tv=({x:e,y:t},[i,s,r],n,[o,a])=>{const l={x:(e-i)/r,y:(t-s)/r};return n?{x:o*Math.round(l.x/o),y:a*Math.round(l.y/a)}:l},Bv=({x:e,y:t},[i,s,r])=>({x:e*r+i,y:t*r+s}),Ov=(e,t=[0,0])=>{if(!e)return{x:0,y:0,positionAbsolute:{x:0,y:0}};const i=(e.width??0)*t[0],s=(e.height??0)*t[1],r={x:e.position.x-i,y:e.position.y-s};return{...r,positionAbsolute:e.positionAbsolute?{x:e.positionAbsolute.x-i,y:e.positionAbsolute.y-s}:r}},Av=(e,t=[0,0])=>{if(0===e.length)return{x:0,y:0,width:0,height:0};const i=e.reduce((e,i)=>{const{x:s,y:r}=Ov(i,t).positionAbsolute;return Fg(e,Kg({x:s,y:r,width:i.width||0,height:i.height||0}))},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return Ug(i)},zv=(e,t,[i,s,r]=[0,0,1],n=!1,o=!1,a=[0,0])=>{const l={x:(t.x-i)/r,y:(t.y-s)/r,width:t.width/r,height:t.height/r},c=[];return e.forEach(e=>{const{width:t,height:i,selectable:s=!0,hidden:r=!1}=e;if(o&&!s||r)return!1;const{positionAbsolute:h}=Ov(e,a),d={x:h.x,y:h.y,width:t||0,height:i||0},u=qg(l,d);(void 0===t||void 0===i||null===t||null===i||n&&u>0||u>=(t||0)*(i||0)||e.dragging)&&c.push(e)}),c},$v=(e,t)=>{const i=e.map(e=>e.id);return t.filter(e=>i.includes(e.source)||i.includes(e.target))},Hv=(e,t,i,s,r,n=.1)=>{const o=t/(e.width*(1+n)),a=i/(e.height*(1+n)),l=Math.min(o,a),c=Ag(l,s,r);return{x:t/2-(e.x+e.width/2)*c,y:i/2-(e.y+e.height/2)*c,zoom:c}},Wv=(e,t=0)=>e.transition().duration(t);function Fv(e,t,i,s){return(t[i]||[]).reduce((t,r)=>{var n,o;return`${e.id}-${r.id}-${i}`!==s&&t.push({id:r.id||null,type:i,nodeId:e.id,x:((null==(n=e.positionAbsolute)?void 0:n.x)??0)+r.x+r.width/2,y:((null==(o=e.positionAbsolute)?void 0:o.y)??0)+r.y+r.height/2}),t},[])}const Kv={source:null,target:null,sourceHandle:null,targetHandle:null},Uv=()=>({handleDomNode:null,isValid:!1,connection:Kv,endHandle:null});function Vv(e,t,i,s,r,n,o){const a="target"===r,l=o.querySelector(`.react-flow__handle[data-id="${null==e?void 0:e.nodeId}-${null==e?void 0:e.id}-${null==e?void 0:e.type}"]`),c={...Uv(),handleDomNode:l};if(l){const e=qv(void 0,l),r=l.getAttribute("data-nodeid"),o=l.getAttribute("data-handleid"),h=l.classList.contains("connectable"),d=l.classList.contains("connectableend"),u={source:a?r:i,sourceHandle:a?o:s,target:a?i:r,targetHandle:a?s:o};c.connection=u;h&&d&&(t===nv.Strict?a&&"source"===e||!a&&"target"===e:r!==i||o!==s)&&(c.endHandle={nodeId:r,handleId:o,type:e},c.isValid=n(u))}return c}function qv(e,t){return e||((null==t?void 0:t.classList.contains("target"))?"target":(null==t?void 0:t.classList.contains("source"))?"source":null)}function Yv(e){null==e||e.classList.remove("valid","connecting","react-flow__handle-valid","react-flow__handle-connecting")}function Xv(e,t){let i=null;return t?i="valid":e&&!t&&(i="invalid"),i}function Gv({event:e,handleId:t,nodeId:i,onConnect:s,isTarget:r,getState:n,setState:o,isValidConnection:a,edgeUpdaterType:l,onReconnectEnd:c}){const h=Wg(e.target),{connectionMode:d,domNode:u,autoPanOnConnect:f,connectionRadius:p,onConnectStart:m,panBy:_,getNodes:g,cancelConnection:v}=n();let y,x=0;const{x:b,y:w}=Qg(e),S=null==h?void 0:h.elementFromPoint(b,w),C=qv(l,S),k=null==u?void 0:u.getBoundingClientRect();if(!k||!C)return;let E,N=Qg(e,k),M=!1,j=null,D=!1,R=null;const P=function({nodes:e,nodeId:t,handleId:i,handleType:s}){return e.reduce((e,r)=>{if(r[Xg]){const{handleBounds:n}=r[Xg];let o=[],a=[];n&&(o=Fv(r,n,"source",`${t}-${i}-${s}`),a=Fv(r,n,"target",`${t}-${i}-${s}`)),e.push(...o,...a)}return e},[])}({nodes:g(),nodeId:i,handleId:t,handleType:C}),L=()=>{if(!f)return;const[e,t]=Hg(N,k);_({x:e,y:t}),x=requestAnimationFrame(L)};function I(e){const{transform:s}=n();N=Qg(e,k);const{handle:l,validHandleResult:c}=function(e,t,i,s,r,n){const{x:o,y:a}=Qg(e),l=t.elementsFromPoint(o,a).find(e=>e.classList.contains("react-flow__handle"));if(l){const e=l.getAttribute("data-nodeid");if(e){const t=qv(void 0,l),s=l.getAttribute("data-handleid"),o=n({nodeId:e,id:s,type:t});if(o){const n=r.find(i=>i.nodeId===e&&i.type===t&&i.id===s);return{handle:{id:s,type:t,nodeId:e,x:(null==n?void 0:n.x)||i.x,y:(null==n?void 0:n.y)||i.y},validHandleResult:o}}}}let c=[],h=1/0;if(r.forEach(e=>{const t=Math.sqrt((e.x-i.x)**2+(e.y-i.y)**2);if(t<=s){const i=n(e);t<=h&&(t<h?c=[{handle:e,validHandleResult:i}]:t===h&&c.push({handle:e,validHandleResult:i}),h=t)}}),!c.length)return{handle:null,validHandleResult:Uv()};if(1===c.length)return c[0];const d=c.some(({validHandleResult:e})=>e.isValid),u=c.some(({handle:e})=>"target"===e.type);return c.find(({handle:e,validHandleResult:t})=>u?"target"===e.type:!d||t.isValid)||c[0]}(e,h,Tv(N,s,!1,[1,1]),p,P,e=>Vv(e,d,i,t,r?"target":"source",a,h));if(y=l,M||(L(),M=!0),R=c.handleDomNode,j=c.connection,D=c.isValid,o({connectionPosition:y&&D?Bv({x:y.x,y:y.y},s):N,connectionStatus:Xv(!!y,D),connectionEndHandle:c.endHandle}),!y&&!D&&!R)return Yv(E);j.source!==j.target&&R&&(Yv(E),E=R,R.classList.add("connecting","react-flow__handle-connecting"),R.classList.toggle("valid",D),R.classList.toggle("react-flow__handle-valid",D))}function T(e){var t,i;(y||R)&&j&&D&&(null==s||s(j)),null==(i=(t=n()).onConnectEnd)||i.call(t,e),l&&(null==c||c(e)),Yv(E),v(),cancelAnimationFrame(x),M=!1,D=!1,j=null,R=null,h.removeEventListener("mousemove",I),h.removeEventListener("mouseup",T),h.removeEventListener("touchmove",I),h.removeEventListener("touchend",T)}o({connectionPosition:N,connectionStatus:null,connectionNodeId:i,connectionHandleId:t,connectionHandleType:C,connectionStartHandle:{nodeId:i,handleId:t,type:C},connectionEndHandle:null}),null==m||m(e,{nodeId:i,handleId:t,handleType:C}),h.addEventListener("mousemove",I),h.addEventListener("mouseup",T),h.addEventListener("touchmove",I),h.addEventListener("touchend",T)}const Zv=()=>!0,Jv=e=>({connectionStartHandle:e.connectionStartHandle,connectOnClick:e.connectOnClick,noPanClassName:e.noPanClassName}),Qv=h.forwardRef(({type:e="source",position:t=mv.Top,isValidConnection:i,isConnectable:s=!0,isConnectableStart:r=!0,isConnectableEnd:n=!0,id:o,onConnect:a,children:l,className:c,onMouseDown:d,onTouchStart:u,...f},p)=>{var m,_;const g=o||null,v="target"===e,y=Pg(),x=h.useContext(Rv),{connectOnClick:b,noPanClassName:w}=Rg(Jv,Of),{connecting:S,clickConnecting:C}=Rg(((e,t,i)=>s=>{const{connectionStartHandle:r,connectionEndHandle:n,connectionClickStartHandle:o}=s;return{connecting:(null==r?void 0:r.nodeId)===e&&(null==r?void 0:r.handleId)===t&&(null==r?void 0:r.type)===i||(null==n?void 0:n.nodeId)===e&&(null==n?void 0:n.handleId)===t&&(null==n?void 0:n.type)===i,clickConnecting:(null==o?void 0:o.nodeId)===e&&(null==o?void 0:o.handleId)===t&&(null==o?void 0:o.type)===i}})(x,g,e),Of);x||null==(_=(m=y.getState()).onError)||_.call(m,"010",Ng());const k=e=>{const{defaultEdgeOptions:t,onConnect:i,hasDefaultEdges:s}=y.getState(),r={...t,...e};if(s){const{edges:e,setEdges:t}=y.getState();t(((e,t)=>{if(!e.source||!e.target)return t;let i;var s;return i="id"in(s=e)&&"source"in s&&"target"in s?{...e}:{...e,id:Lv(e)},((e,t)=>t.some(t=>!(t.source!==e.source||t.target!==e.target||t.sourceHandle!==e.sourceHandle&&(t.sourceHandle||e.sourceHandle)||t.targetHandle!==e.targetHandle&&(t.targetHandle||e.targetHandle))))(i,t)?t:t.concat(i)})(r,e))}null==i||i(r),null==a||a(r)},E=e=>{if(!x)return;const t=Jg(e);r&&(t&&0===e.button||!t)&&Gv({event:e,handleId:g,nodeId:x,onConnect:k,isTarget:v,getState:y.getState,setState:y.setState,isValidConnection:i||y.getState().isValidConnection||Zv}),t?null==d||d(e):null==u||u(e)};return N.createElement("div",{"data-handleid":g,"data-nodeid":x,"data-handlepos":t,"data-id":`${x}-${g}-${e}`,className:vf(["react-flow__handle",`react-flow__handle-${t}`,"nodrag",w,c,{source:!v,target:v,connectable:s,connectablestart:r,connectableend:n,connecting:C,connectionindicator:s&&(r&&!S||n&&S)}]),onMouseDown:E,onTouchStart:E,onClick:b?t=>{const{onClickConnectStart:s,onClickConnectEnd:n,connectionClickStartHandle:o,connectionMode:a,isValidConnection:l}=y.getState();if(!x||!o&&!r)return;if(!o)return null==s||s(t,{nodeId:x,handleId:g,handleType:e}),void y.setState({connectionClickStartHandle:{nodeId:x,type:e,handleId:g}});const c=Wg(t.target),h=i||l||Zv,{connection:d,isValid:u}=Vv({nodeId:x,id:g,type:e},a,o.nodeId,o.handleId||null,o.type,h,c);u&&k(d),null==n||n(t),y.setState({connectionClickStartHandle:null})}:void 0,ref:p,...f},l)});Qv.displayName="Handle";var ey=h.memo(Qv);const ty=({data:e,isConnectable:t,targetPosition:i=mv.Top,sourcePosition:s=mv.Bottom})=>N.createElement(N.Fragment,null,N.createElement(ey,{type:"target",position:i,isConnectable:t}),null==e?void 0:e.label,N.createElement(ey,{type:"source",position:s,isConnectable:t}));ty.displayName="DefaultNode";var iy=h.memo(ty);const sy=({data:e,isConnectable:t,sourcePosition:i=mv.Bottom})=>N.createElement(N.Fragment,null,null==e?void 0:e.label,N.createElement(ey,{type:"source",position:i,isConnectable:t}));sy.displayName="InputNode";var ry=h.memo(sy);const ny=({data:e,isConnectable:t,targetPosition:i=mv.Top})=>N.createElement(N.Fragment,null,N.createElement(ey,{type:"target",position:i,isConnectable:t}),null==e?void 0:e.label);ny.displayName="OutputNode";var oy=h.memo(ny);const ay=()=>null;ay.displayName="GroupNode";const ly=e=>({selectedNodes:e.getNodes().filter(e=>e.selected),selectedEdges:e.edges.filter(e=>e.selected).map(e=>({...e}))}),cy=e=>e.id;function hy(e,t){return Of(e.selectedNodes.map(cy),t.selectedNodes.map(cy))&&Of(e.selectedEdges.map(cy),t.selectedEdges.map(cy))}const dy=h.memo(({onSelectionChange:e})=>{const t=Pg(),{selectedNodes:i,selectedEdges:s}=Rg(ly,hy);return h.useEffect(()=>{const r={nodes:i,edges:s};null==e||e(r),t.getState().onSelectionChange.forEach(e=>e(r))},[i,s,e]),null});dy.displayName="SelectionListener";const uy=e=>!!e.onSelectionChange;function fy({onSelectionChange:e}){const t=Rg(uy);return e||t?N.createElement(dy,{onSelectionChange:e}):null}const py=e=>({setNodes:e.setNodes,setEdges:e.setEdges,setDefaultNodesAndEdges:e.setDefaultNodesAndEdges,setMinZoom:e.setMinZoom,setMaxZoom:e.setMaxZoom,setTranslateExtent:e.setTranslateExtent,setNodeExtent:e.setNodeExtent,reset:e.reset});function my(e,t){h.useEffect(()=>{void 0!==e&&t(e)},[e])}function _y(e,t,i){h.useEffect(()=>{void 0!==t&&i({[e]:t})},[t])}const gy=({nodes:e,edges:t,defaultNodes:i,defaultEdges:s,onConnect:r,onConnectStart:n,onConnectEnd:o,onClickConnectStart:a,onClickConnectEnd:l,nodesDraggable:c,nodesConnectable:d,nodesFocusable:u,edgesFocusable:f,edgesUpdatable:p,elevateNodesOnSelect:m,minZoom:_,maxZoom:g,nodeExtent:v,onNodesChange:y,onEdgesChange:x,elementsSelectable:b,connectionMode:w,snapGrid:S,snapToGrid:C,translateExtent:k,connectOnClick:E,defaultEdgeOptions:N,fitView:M,fitViewOptions:j,onNodesDelete:D,onEdgesDelete:R,onNodeDrag:P,onNodeDragStart:L,onNodeDragStop:I,onSelectionDrag:T,onSelectionDragStart:B,onSelectionDragStop:O,noPanClassName:A,nodeOrigin:z,rfId:$,autoPanOnConnect:H,autoPanOnNodeDrag:W,onError:F,connectionRadius:K,isValidConnection:U,nodeDragThreshold:V})=>{const{setNodes:q,setEdges:Y,setDefaultNodesAndEdges:X,setMinZoom:G,setMaxZoom:Z,setTranslateExtent:J,setNodeExtent:Q,reset:ee}=Rg(py,Of),te=Pg();return h.useEffect(()=>{const e=null==s?void 0:s.map(e=>({...e,...N}));return X(i,e),()=>{ee()}},[]),_y("defaultEdgeOptions",N,te.setState),_y("connectionMode",w,te.setState),_y("onConnect",r,te.setState),_y("onConnectStart",n,te.setState),_y("onConnectEnd",o,te.setState),_y("onClickConnectStart",a,te.setState),_y("onClickConnectEnd",l,te.setState),_y("nodesDraggable",c,te.setState),_y("nodesConnectable",d,te.setState),_y("nodesFocusable",u,te.setState),_y("edgesFocusable",f,te.setState),_y("edgesUpdatable",p,te.setState),_y("elementsSelectable",b,te.setState),_y("elevateNodesOnSelect",m,te.setState),_y("snapToGrid",C,te.setState),_y("snapGrid",S,te.setState),_y("onNodesChange",y,te.setState),_y("onEdgesChange",x,te.setState),_y("connectOnClick",E,te.setState),_y("fitViewOnInit",M,te.setState),_y("fitViewOnInitOptions",j,te.setState),_y("onNodesDelete",D,te.setState),_y("onEdgesDelete",R,te.setState),_y("onNodeDrag",P,te.setState),_y("onNodeDragStart",L,te.setState),_y("onNodeDragStop",I,te.setState),_y("onSelectionDrag",T,te.setState),_y("onSelectionDragStart",B,te.setState),_y("onSelectionDragStop",O,te.setState),_y("noPanClassName",A,te.setState),_y("nodeOrigin",z,te.setState),_y("rfId",$,te.setState),_y("autoPanOnConnect",H,te.setState),_y("autoPanOnNodeDrag",W,te.setState),_y("onError",F,te.setState),_y("connectionRadius",K,te.setState),_y("isValidConnection",U,te.setState),_y("nodeDragThreshold",V,te.setState),my(e,q),my(t,Y),my(_,G),my(g,Z),my(k,J),my(v,Q),null},vy={display:"none"},yy={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},xy="react-flow__node-desc",by="react-flow__edge-desc",wy=e=>e.ariaLiveMessage;function Sy({rfId:e}){const t=Rg(wy);return N.createElement("div",{id:`react-flow__aria-live-${e}`,"aria-live":"assertive","aria-atomic":"true",style:yy},t)}function Cy({rfId:e,disableKeyboardA11y:t}){return N.createElement(N.Fragment,null,N.createElement("div",{id:`${xy}-${e}`,style:vy},"Press enter or space to select a node.",!t&&"You can then use the arrow keys to move the node around."," Press delete to remove it and escape to cancel."," "),N.createElement("div",{id:`${by}-${e}`,style:vy},"Press enter or space to select an edge. You can then press delete to remove it or escape to cancel."),!t&&N.createElement(Sy,{rfId:e}))}var ky=(e=null,t={actInsideInputWithModifier:!0})=>{const[i,s]=h.useState(!1),r=h.useRef(!1),n=h.useRef(new Set([])),[o,a]=h.useMemo(()=>{if(null!==e){const t=(Array.isArray(e)?e:[e]).filter(e=>"string"==typeof e).map(e=>e.split("+")),i=t.reduce((e,t)=>e.concat(...t),[]);return[t,i]}return[[],[]]},[e]);return h.useEffect(()=>{const i="undefined"!=typeof document?document:null,l=(null==t?void 0:t.target)||i;if(null!==e){const e=e=>{r.current=e.ctrlKey||e.metaKey||e.shiftKey;if((!r.current||r.current&&!t.actInsideInputWithModifier)&&Zg(e))return!1;const i=Ny(e.code,a);n.current.add(e[i]),Ey(o,n.current,!1)&&(e.preventDefault(),s(!0))},i=e=>{if((!r.current||r.current&&!t.actInsideInputWithModifier)&&Zg(e))return!1;const i=Ny(e.code,a);Ey(o,n.current,!0)?(s(!1),n.current.clear()):n.current.delete(e[i]),"Meta"===e.key&&n.current.clear(),r.current=!1},c=()=>{n.current.clear(),s(!1)};return null==l||l.addEventListener("keydown",e),null==l||l.addEventListener("keyup",i),window.addEventListener("blur",c),()=>{null==l||l.removeEventListener("keydown",e),null==l||l.removeEventListener("keyup",i),window.removeEventListener("blur",c)}}},[e,s]),i};function Ey(e,t,i){return e.filter(e=>i||e.length===t.size).some(e=>e.every(e=>t.has(e)))}function Ny(e,t){return t.includes(e)?"code":"key"}function My(e,t,i,s){var r,n;const o=e.parentNode||e.parentId;if(!o)return i;const a=t.get(o),l=Ov(a,s);return My(a,t,{x:(i.x??0)+l.x,y:(i.y??0)+l.y,z:((null==(r=a[Xg])?void 0:r.z)??0)>(i.z??0)?(null==(n=a[Xg])?void 0:n.z)??0:i.z??0},s)}function jy(e,t,i){e.forEach(s=>{var r;const n=s.parentNode||s.parentId;if(n&&!e.has(n))throw new Error(`Parent node ${n} not found`);if(n||(null==i?void 0:i[s.id])){const{x:n,y:o,z:a}=My(s,e,{...s.position,z:(null==(r=s[Xg])?void 0:r.z)??0},t);s.positionAbsolute={x:n,y:o},s[Xg].z=a,(null==i?void 0:i[s.id])&&(s[Xg].isParent=!0)}})}function Dy(e,t,i,s){const r=new Map,n={},o=s?1e3:0;return e.forEach(e=>{var i;const s=(Yg(e.zIndex)?e.zIndex:0)+(e.selected?o:0),a=t.get(e.id),l={...e,positionAbsolute:{x:e.position.x,y:e.position.y}},c=e.parentNode||e.parentId;c&&(n[c]=!0);const h=(null==a?void 0:a.type)&&(null==a?void 0:a.type)!==e.type;Object.defineProperty(l,Xg,{enumerable:!1,value:{handleBounds:h||null==(i=null==a?void 0:a[Xg])?void 0:i.handleBounds,z:s}}),r.set(e.id,l)}),jy(r,i,n),r}function Ry(e,t={}){const{getNodes:i,width:s,height:r,minZoom:n,maxZoom:o,d3Zoom:a,d3Selection:l,fitViewOnInitDone:c,fitViewOnInit:h,nodeOrigin:d}=e(),u=t.initial&&!c&&h;if(a&&l&&(u||!t.initial)){const e=i().filter(e=>{var i;const s=t.includeHiddenNodes?e.width&&e.height:!e.hidden;return(null==(i=t.nodes)?void 0:i.length)?s&&t.nodes.some(t=>t.id===e.id):s}),c=e.every(e=>e.width&&e.height);if(e.length>0&&c){const i=Av(e,d),{x:c,y:h,zoom:u}=Hv(i,s,r,t.minZoom??n,t.maxZoom??o,t.padding??.1),f=hg.translate(c,h).scale(u);return"number"==typeof t.duration&&t.duration>0?a.transform(Wv(l,t.duration),f):a.transform(l,f),!0}}return!1}function Py(e,t){return e.forEach(e=>{const i=t.get(e.id);i&&t.set(i.id,{...i,[Xg]:i[Xg],selected:e.selected})}),new Map(t)}function Ly(e,t){return t.map(t=>{const i=e.find(e=>e.id===t.id);return i&&(t.selected=i.selected),t})}function Iy({changedNodes:e,changedEdges:t,get:i,set:s}){const{nodeInternals:r,edges:n,onNodesChange:o,onEdgesChange:a,hasDefaultNodes:l,hasDefaultEdges:c}=i();(null==e?void 0:e.length)&&(l&&s({nodeInternals:Py(e,r)}),null==o||o(e)),(null==t?void 0:t.length)&&(c&&s({edges:Ly(t,n)}),null==a||a(t))}const Ty=()=>{},By={zoomIn:Ty,zoomOut:Ty,zoomTo:Ty,getZoom:()=>1,setViewport:Ty,getViewport:()=>({x:0,y:0,zoom:1}),fitView:()=>!1,setCenter:Ty,fitBounds:Ty,project:e=>e,screenToFlowPosition:e=>e,flowToScreenPosition:e=>e,viewportInitialized:!1},Oy=e=>({d3Zoom:e.d3Zoom,d3Selection:e.d3Selection});function Ay(){const e=(()=>{const e=Pg(),{d3Zoom:t,d3Selection:i}=Rg(Oy,Of);return h.useMemo(()=>i&&t?{zoomIn:e=>t.scaleBy(Wv(i,null==e?void 0:e.duration),1.2),zoomOut:e=>t.scaleBy(Wv(i,null==e?void 0:e.duration),1/1.2),zoomTo:(e,s)=>t.scaleTo(Wv(i,null==s?void 0:s.duration),e),getZoom:()=>e.getState().transform[2],setViewport:(s,r)=>{const[n,o,a]=e.getState().transform,l=hg.translate(s.x??n,s.y??o).scale(s.zoom??a);t.transform(Wv(i,null==r?void 0:r.duration),l)},getViewport:()=>{const[t,i,s]=e.getState().transform;return{x:t,y:i,zoom:s}},fitView:t=>Ry(e.getState,t),setCenter:(s,r,n)=>{const{width:o,height:a,maxZoom:l}=e.getState(),c=void 0!==(null==n?void 0:n.zoom)?n.zoom:l,h=o/2-s*c,d=a/2-r*c,u=hg.translate(h,d).scale(c);t.transform(Wv(i,null==n?void 0:n.duration),u)},fitBounds:(s,r)=>{const{width:n,height:o,minZoom:a,maxZoom:l}=e.getState(),{x:c,y:h,zoom:d}=Hv(s,n,o,a,l,(null==r?void 0:r.padding)??.1),u=hg.translate(c,h).scale(d);t.transform(Wv(i,null==r?void 0:r.duration),u)},project:t=>{const{transform:i,snapToGrid:s,snapGrid:r}=e.getState();return console.warn("[DEPRECATED] `project` is deprecated. Instead use `screenToFlowPosition`. There is no need to subtract the react flow bounds anymore! https://reactflow.dev/api-reference/types/react-flow-instance#screen-to-flow-position"),Tv(t,i,s,r)},screenToFlowPosition:t=>{const{transform:i,snapToGrid:s,snapGrid:r,domNode:n}=e.getState();if(!n)return t;const{x:o,y:a}=n.getBoundingClientRect(),l={x:t.x-o,y:t.y-a};return Tv(l,i,s,r)},flowToScreenPosition:t=>{const{transform:i,domNode:s}=e.getState();if(!s)return t;const{x:r,y:n}=s.getBoundingClientRect(),o=Bv(t,i);return{x:o.x+r,y:o.y+n}},viewportInitialized:!0}:By,[t,i])})(),t=Pg(),i=h.useCallback(()=>t.getState().getNodes().map(e=>({...e})),[]),s=h.useCallback(e=>t.getState().nodeInternals.get(e),[]),r=h.useCallback(()=>{const{edges:e=[]}=t.getState();return e.map(e=>({...e}))},[]),n=h.useCallback(e=>{const{edges:i=[]}=t.getState();return i.find(t=>t.id===e)},[]),o=h.useCallback(e=>{const{getNodes:i,setNodes:s,hasDefaultNodes:r,onNodesChange:n}=t.getState(),o=i(),a="function"==typeof e?e(o):e;if(r)s(a);else if(n){n(0===a.length?o.map(e=>({type:"remove",id:e.id})):a.map(e=>({item:e,type:"reset"})))}},[]),a=h.useCallback(e=>{const{edges:i=[],setEdges:s,hasDefaultEdges:r,onEdgesChange:n}=t.getState(),o="function"==typeof e?e(i):e;if(r)s(o);else if(n){n(0===o.length?i.map(e=>({type:"remove",id:e.id})):o.map(e=>({item:e,type:"reset"})))}},[]),l=h.useCallback(e=>{const i=Array.isArray(e)?e:[e],{getNodes:s,setNodes:r,hasDefaultNodes:n,onNodesChange:o}=t.getState();if(n){r([...s(),...i])}else if(o){o(i.map(e=>({item:e,type:"add"})))}},[]),c=h.useCallback(e=>{const i=Array.isArray(e)?e:[e],{edges:s=[],setEdges:r,hasDefaultEdges:n,onEdgesChange:o}=t.getState();if(n)r([...s,...i]);else if(o){o(i.map(e=>({item:e,type:"add"})))}},[]),d=h.useCallback(()=>{const{getNodes:e,edges:i=[],transform:s}=t.getState(),[r,n,o]=s;return{nodes:e().map(e=>({...e})),edges:i.map(e=>({...e})),viewport:{x:r,y:n,zoom:o}}},[]),u=h.useCallback(({nodes:e,edges:i})=>{const{nodeInternals:s,getNodes:r,edges:n,hasDefaultNodes:o,hasDefaultEdges:a,onNodesDelete:l,onEdgesDelete:c,onNodesChange:h,onEdgesChange:d}=t.getState(),u=(e||[]).map(e=>e.id),f=(i||[]).map(e=>e.id),p=r().reduce((e,t)=>{const i=t.parentNode||t.parentId,s=!u.includes(t.id)&&i&&e.find(e=>e.id===i);return("boolean"!=typeof t.deletable||t.deletable)&&(u.includes(t.id)||s)&&e.push(t),e},[]),m=n.filter(e=>"boolean"!=typeof e.deletable||e.deletable),_=m.filter(e=>f.includes(e.id));if(p||_){const e=$v(p,m),i=[..._,...e],r=i.reduce((e,t)=>(e.includes(t.id)||e.push(t.id),e),[]);if((a||o)&&(a&&t.setState({edges:n.filter(e=>!r.includes(e.id))}),o&&(p.forEach(e=>{s.delete(e.id)}),t.setState({nodeInternals:new Map(s)}))),r.length>0&&(null==c||c(i),d&&d(r.map(e=>({id:e,type:"remove"})))),p.length>0&&(null==l||l(p),h)){const e=p.map(e=>({id:e.id,type:"remove"}));h(e)}}},[]),f=h.useCallback(e=>{const i=Yg((s=e).width)&&Yg(s.height)&&Yg(s.x)&&Yg(s.y);var s;const r=i?null:t.getState().nodeInternals.get(e.id);if(!i&&!r)return[null,null,i];return[i?e:Vg(r),r,i]},[]),p=h.useCallback((e,i=!0,s)=>{const[r,n,o]=f(e);return r?(s||t.getState().getNodes()).filter(e=>{if(!(o||e.id!==n.id&&e.positionAbsolute))return!1;const t=Vg(e),s=qg(t,r);return i&&s>0||s>=r.width*r.height}):[]},[]),m=h.useCallback((e,t,i=!0)=>{const[s]=f(e);if(!s)return!1;const r=qg(s,t);return i&&r>0||r>=s.width*s.height},[]);return h.useMemo(()=>({...e,getNodes:i,getNode:s,getEdges:r,getEdge:n,setNodes:o,setEdges:a,addNodes:l,addEdges:c,toObject:d,deleteElements:u,getIntersectingNodes:p,isNodeIntersecting:m}),[e,i,s,r,n,o,a,l,c,d,u,p,m])}const zy={actInsideInputWithModifier:!1};const $y={position:"absolute",width:"100%",height:"100%",top:0,left:0},Hy=e=>({x:e.x,y:e.y,zoom:e.k}),Wy=(e,t)=>e.target.closest(`.${t}`),Fy=(e,t)=>2===t&&Array.isArray(e)&&e.includes(2),Ky=e=>{const t=e.ctrlKey&&ev()?10:1;return-e.deltaY*(1===e.deltaMode?.05:e.deltaMode?1:.002)*t},Uy=e=>({d3Zoom:e.d3Zoom,d3Selection:e.d3Selection,d3ZoomHandler:e.d3ZoomHandler,userSelectionActive:e.userSelectionActive}),Vy=({onMove:e,onMoveStart:t,onMoveEnd:i,onPaneContextMenu:s,zoomOnScroll:r=!0,zoomOnPinch:n=!0,panOnScroll:o=!1,panOnScrollSpeed:a=.5,panOnScrollMode:l=av.Free,zoomOnDoubleClick:c=!0,elementsSelectable:d,panOnDrag:u=!0,defaultViewport:f,translateExtent:p,minZoom:m,maxZoom:_,zoomActivationKeyCode:g,preventScrolling:v=!0,children:y,noWheelClassName:x,noPanClassName:b})=>{const w=h.useRef(),S=Pg(),C=h.useRef(!1),k=h.useRef(!1),E=h.useRef(null),M=h.useRef({x:0,y:0,zoom:0}),{d3Zoom:j,d3Selection:D,d3ZoomHandler:R,userSelectionActive:P}=Rg(Uy,Of),L=ky(g),I=h.useRef(0),T=h.useRef(!1),B=h.useRef();return function(e){const t=Pg();h.useEffect(()=>{let i;const s=()=>{var i,s;if(!e.current)return;const r=Og(e.current);0!==r.height&&0!==r.width||null==(s=(i=t.getState()).onError)||s.call(i,"004",Sg()),t.setState({width:r.width||500,height:r.height||500})};return s(),window.addEventListener("resize",s),e.current&&(i=new ResizeObserver(()=>s()),i.observe(e.current)),()=>{window.removeEventListener("resize",s),i&&e.current&&i.unobserve(e.current)}},[])}(E),h.useEffect(()=>{if(E.current){const e=E.current.getBoundingClientRect(),t=yg().scaleExtent([m,_]).translateExtent(p),i=tm(E.current).call(t),s=hg.translate(f.x,f.y).scale(Ag(f.zoom,m,_)),r=[[0,0],[e.width,e.height]],n=t.constrain()(s,r,p);t.transform(i,n),t.wheelDelta(Ky),S.setState({d3Zoom:t,d3Selection:i,d3ZoomHandler:i.on("wheel.zoom"),transform:[n.x,n.y,n.k],domNode:E.current.closest(".react-flow")})}},[]),h.useEffect(()=>{D&&j&&(!o||L||P?void 0!==R&&D.on("wheel.zoom",function(e,t){if(!v&&"wheel"===e.type&&!e.ctrlKey||Wy(e,x))return null;e.preventDefault(),R.call(this,e,t)},{passive:!1}):D.on("wheel.zoom",s=>{if(Wy(s,x))return!1;s.preventDefault(),s.stopImmediatePropagation();const r=D.property("__zoom").k||1;if(s.ctrlKey&&n){const e=im(s),t=Ky(s),i=r*Math.pow(2,t);return void j.scaleTo(D,i,e,s)}const o=1===s.deltaMode?20:1;let c=l===av.Vertical?0:s.deltaX*o,h=l===av.Horizontal?0:s.deltaY*o;!ev()&&s.shiftKey&&l!==av.Vertical&&(c=s.deltaY*o,h=0),j.translateBy(D,-c/r*a,-h/r*a,{internal:!0});const d=Hy(D.property("__zoom")),{onViewportChangeStart:u,onViewportChange:f,onViewportChangeEnd:p}=S.getState();clearTimeout(B.current),T.current||(T.current=!0,null==t||t(s,d),null==u||u(d)),T.current&&(null==e||e(s,d),null==f||f(d),B.current=setTimeout(()=>{null==i||i(s,d),null==p||p(d),T.current=!1},150))},{passive:!1}))},[P,o,l,D,j,R,L,n,v,x,t,e,i]),h.useEffect(()=>{j&&j.on("start",e=>{var i,s;if(!e.sourceEvent||e.sourceEvent.internal)return null;I.current=null==(i=e.sourceEvent)?void 0:i.button;const{onViewportChangeStart:r}=S.getState(),n=Hy(e.transform);C.current=!0,M.current=n,"mousedown"===(null==(s=e.sourceEvent)?void 0:s.type)&&S.setState({paneDragging:!0}),null==r||r(n),null==t||t(e.sourceEvent,n)})},[j,t]),h.useEffect(()=>{j&&(P&&!C.current?j.on("zoom",null):P||j.on("zoom",t=>{var i;const{onViewportChange:r}=S.getState();if(S.setState({transform:[t.transform.x,t.transform.y,t.transform.k]}),k.current=!(!s||!Fy(u,I.current??0)),(e||r)&&!(null==(i=t.sourceEvent)?void 0:i.internal)){const i=Hy(t.transform);null==r||r(i),null==e||e(t.sourceEvent,i)}}))},[P,j,e,u,s]),h.useEffect(()=>{j&&j.on("end",e=>{if(!e.sourceEvent||e.sourceEvent.internal)return null;const{onViewportChangeEnd:t}=S.getState();if(C.current=!1,S.setState({paneDragging:!1}),s&&Fy(u,I.current??0)&&!k.current&&s(e.sourceEvent),k.current=!1,(i||t)&&(r=M.current,n=e.transform,r.x!==n.x||r.y!==n.y||r.zoom!==n.k)){const s=Hy(e.transform);M.current=s,clearTimeout(w.current),w.current=setTimeout(()=>{null==t||t(s),null==i||i(e.sourceEvent,s)},o?150:0)}var r,n})},[j,o,u,i,s]),h.useEffect(()=>{j&&j.filter(e=>{const t=L||r,i=n&&e.ctrlKey;if((!0===u||Array.isArray(u)&&u.includes(1))&&1===e.button&&"mousedown"===e.type&&(Wy(e,"react-flow__node")||Wy(e,"react-flow__edge")))return!0;if(!(u||t||o||c||n))return!1;if(P)return!1;if(!c&&"dblclick"===e.type)return!1;if(Wy(e,x)&&"wheel"===e.type)return!1;if(Wy(e,b)&&("wheel"!==e.type||o&&"wheel"===e.type&&!L))return!1;if(!n&&e.ctrlKey&&"wheel"===e.type)return!1;if(!t&&!o&&!i&&"wheel"===e.type)return!1;if(!u&&("mousedown"===e.type||"touchstart"===e.type))return!1;if(Array.isArray(u)&&!u.includes(e.button)&&"mousedown"===e.type)return!1;const s=Array.isArray(u)&&u.includes(e.button)||!e.button||e.button<=1;return(!e.ctrlKey||"wheel"===e.type)&&s})},[P,j,r,n,o,c,u,d,L]),N.createElement("div",{className:"react-flow__renderer",ref:E,style:$y},y)},qy=e=>({userSelectionActive:e.userSelectionActive,userSelectionRect:e.userSelectionRect});function Yy(){const{userSelectionActive:e,userSelectionRect:t}=Rg(qy,Of);return e&&t?N.createElement("div",{className:"react-flow__selection react-flow__container",style:{width:t.width,height:t.height,transform:`translate(${t.x}px, ${t.y}px)`}}):null}function Xy(e,t){const i=t.parentNode||t.parentId,s=e.find(e=>e.id===i);if(s){const e=t.position.x+t.width-s.width,i=t.position.y+t.height-s.height;if(e>0||i>0||t.position.x<0||t.position.y<0){if(s.style={...s.style},s.style.width=s.style.width??s.width,s.style.height=s.style.height??s.height,e>0&&(s.style.width+=e),i>0&&(s.style.height+=i),t.position.x<0){const e=Math.abs(t.position.x);s.position.x=s.position.x-e,s.style.width+=e,t.position.x=0}if(t.position.y<0){const e=Math.abs(t.position.y);s.position.y=s.position.y-e,s.style.height+=e,t.position.y=0}s.width=s.style.width,s.height=s.style.height}}}function Gy(e,t){return function(e,t){if(e.some(e=>"reset"===e.type))return e.filter(e=>"reset"===e.type).map(e=>e.item);const i=e.filter(e=>"add"===e.type).map(e=>e.item);return t.reduce((t,i)=>{const s=e.filter(e=>e.id===i.id);if(0===s.length)return t.push(i),t;const r={...i};for(const e of s)if(e)switch(e.type){case"select":r.selected=e.selected;break;case"position":void 0!==e.position&&(r.position=e.position),void 0!==e.positionAbsolute&&(r.positionAbsolute=e.positionAbsolute),void 0!==e.dragging&&(r.dragging=e.dragging),r.expandParent&&Xy(t,r);break;case"dimensions":void 0!==e.dimensions&&(r.width=e.dimensions.width,r.height=e.dimensions.height),void 0!==e.updateStyle&&(r.style={...r.style||{},...e.dimensions}),"boolean"==typeof e.resizing&&(r.resizing=e.resizing),r.expandParent&&Xy(t,r);break;case"remove":return t}return t.push(r),t},i)}(e,t)}const Zy=(e,t)=>({id:e,type:"select",selected:t});function Jy(e,t){return e.reduce((e,i)=>{const s=t.includes(i.id);return!i.selected&&s?(i.selected=!0,e.push(Zy(i.id,!0))):i.selected&&!s&&(i.selected=!1,e.push(Zy(i.id,!1))),e},[])}const Qy=(e,t)=>i=>{i.target===t.current&&(null==e||e(i))},ex=e=>({userSelectionActive:e.userSelectionActive,elementsSelectable:e.elementsSelectable,dragging:e.paneDragging}),tx=h.memo(({isSelecting:e,selectionMode:t=cv.Full,panOnDrag:i,onSelectionStart:s,onSelectionEnd:r,onPaneClick:n,onPaneContextMenu:o,onPaneScroll:a,onPaneMouseEnter:l,onPaneMouseMove:c,onPaneMouseLeave:d,children:u})=>{const f=h.useRef(null),p=Pg(),m=h.useRef(0),_=h.useRef(0),g=h.useRef(),{userSelectionActive:v,elementsSelectable:y,dragging:x}=Rg(ex,Of),b=()=>{p.setState({userSelectionActive:!1,userSelectionRect:null}),m.current=0,_.current=0},w=e=>{null==n||n(e),p.getState().resetSelectedElements(),p.setState({nodesSelectionActive:!1})},S=a?e=>a(e):void 0,C=y&&(e||v);return N.createElement("div",{className:vf(["react-flow__pane",{dragging:x,selection:e}]),onClick:C?void 0:Qy(w,f),onContextMenu:Qy(e=>{Array.isArray(i)&&(null==i?void 0:i.includes(2))?e.preventDefault():null==o||o(e)},f),onWheel:Qy(S,f),onMouseEnter:C?void 0:l,onMouseDown:C?t=>{const{resetSelectedElements:i,domNode:r}=p.getState();if(g.current=null==r?void 0:r.getBoundingClientRect(),!y||!e||0!==t.button||t.target!==f.current||!g.current)return;const{x:n,y:o}=Qg(t,g.current);i(),p.setState({userSelectionRect:{width:0,height:0,startX:n,startY:o,x:n,y:o}}),null==s||s(t)}:void 0,onMouseMove:C?i=>{const{userSelectionRect:s,nodeInternals:r,edges:n,transform:o,onNodesChange:a,onEdgesChange:l,nodeOrigin:c,getNodes:h}=p.getState();if(!e||!g.current||!s)return;p.setState({userSelectionActive:!0,nodesSelectionActive:!1});const d=Qg(i,g.current),u=s.startX??0,f=s.startY??0,v={...s,x:d.x<u?d.x:u,y:d.y<f?d.y:f,width:Math.abs(d.x-u),height:Math.abs(d.y-f)},y=h(),x=zv(r,v,o,t===cv.Partial,!0,c),b=$v(x,n).map(e=>e.id),w=x.map(e=>e.id);if(m.current!==w.length){m.current=w.length;const e=Jy(y,w);e.length&&(null==a||a(e))}if(_.current!==b.length){_.current=b.length;const e=Jy(n,b);e.length&&(null==l||l(e))}p.setState({userSelectionRect:v})}:c,onMouseUp:C?e=>{if(0!==e.button)return;const{userSelectionRect:t}=p.getState();!v&&t&&e.target===f.current&&(null==w||w(e)),p.setState({nodesSelectionActive:m.current>0}),b(),null==r||r(e)}:void 0,onMouseLeave:C?e=>{v&&(p.setState({nodesSelectionActive:m.current>0}),null==r||r(e)),b()}:d,ref:f,style:$y},u,N.createElement(Yy,null))});function ix(e,t){const i=e.parentNode||e.parentId;if(!i)return!1;const s=t.get(i);return!!s&&(!!s.selected||ix(s,t))}function sx(e,t,i){let s=e;do{if(null==s?void 0:s.matches(t))return!0;if(s===i.current)return!1;s=s.parentElement}while(s);return!1}function rx(e,t,i,s){return Array.from(e.values()).filter(i=>(i.selected||i.id===s)&&(!i.parentNode||i.parentId||!ix(i,e))&&(i.draggable||t&&void 0===i.draggable)).map(e=>{var t,s;return{id:e.id,position:e.position||{x:0,y:0},positionAbsolute:e.positionAbsolute||{x:0,y:0},distance:{x:i.x-((null==(t=e.positionAbsolute)?void 0:t.x)??0),y:i.y-((null==(s=e.positionAbsolute)?void 0:s.y)??0)},delta:{x:0,y:0},extent:e.extent,parentNode:e.parentNode||e.parentId,parentId:e.parentNode||e.parentId,width:e.width,height:e.height,expandParent:e.expandParent}})}function nx(e,t,i,s,r=[0,0],n){const o=function(e,t){return t&&"parent"!==t?[t[0],[t[1][0]-(e.width||0),t[1][1]-(e.height||0)]]:t}(e,e.extent||s);let a=o;const l=e.parentNode||e.parentId;if("parent"!==e.extent||e.expandParent){if(e.extent&&l&&"parent"!==e.extent){const t=i.get(l),{x:s,y:n}=Ov(t,r).positionAbsolute;a=[[e.extent[0][0]+s,e.extent[0][1]+n],[e.extent[1][0]+s,e.extent[1][1]+n]]}}else if(l&&e.width&&e.height){const t=i.get(l),{x:s,y:n}=Ov(t,r).positionAbsolute;a=t&&Yg(s)&&Yg(n)&&Yg(t.width)&&Yg(t.height)?[[s+e.width*r[0],n+e.height*r[1]],[s+t.width-e.width+e.width*r[0],n+t.height-e.height+e.height*r[1]]]:a}else null==n||n("005",Cg()),a=o;let c={x:0,y:0};if(l){const e=i.get(l);c=Ov(e,r).positionAbsolute}const h=a&&"parent"!==a?zg(t,a):t;return{position:{x:h.x-c.x,y:h.y-c.y},positionAbsolute:h}}function ox({nodeId:e,dragItems:t,nodeInternals:i}){const s=t.map(e=>({...i.get(e.id),position:e.position,positionAbsolute:e.positionAbsolute}));return[e?s.find(t=>t.id===e):s[0],s]}tx.displayName="Pane";const ax=(e,t,i,s)=>{const r=t.querySelectorAll(e);if(!r||!r.length)return null;const n=Array.from(r),o=t.getBoundingClientRect(),a=o.width*s[0],l=o.height*s[1];return n.map(e=>{const t=e.getBoundingClientRect();return{id:e.getAttribute("data-handleid"),position:e.getAttribute("data-handlepos"),x:(t.left-o.left-a)/i,y:(t.top-o.top-l)/i,...Og(e)}})};function lx(e,t,i){return void 0===i?i:s=>{const r=t().nodeInternals.get(e);r&&i(s,{...r})}}function cx({id:e,store:t,unselect:i=!1,nodeRef:s}){const{addSelectedNodes:r,unselectNodesAndEdges:n,multiSelectionActive:o,nodeInternals:a,onError:l}=t.getState(),c=a.get(e);c?(t.setState({nodesSelectionActive:!1}),c.selected?(i||c.selected&&o)&&(n({nodes:[c],edges:[]}),requestAnimationFrame(()=>{var e;return null==(e=null==s?void 0:s.current)?void 0:e.blur()})):r([e])):null==l||l("012",jg(e))}function hx(e){return(t,i,s)=>null==e?void 0:e(t,s)}function dx({nodeRef:e,disabled:t=!1,noDragClassName:i,handleSelector:s,nodeId:r,isSelectable:n,selectNodesOnDrag:o}){const a=Pg(),[l,c]=h.useState(!1),d=h.useRef([]),u=h.useRef({x:null,y:null}),f=h.useRef(0),p=h.useRef(null),m=h.useRef({x:0,y:0}),_=h.useRef(null),g=h.useRef(!1),v=h.useRef(!1),y=h.useRef(!1),x=function(){const e=Pg();return h.useCallback(({sourceEvent:t})=>{const{transform:i,snapGrid:s,snapToGrid:r}=e.getState(),n=t.touches?t.touches[0].clientX:t.clientX,o=t.touches?t.touches[0].clientY:t.clientY,a={x:(n-i[0])/i[2],y:(o-i[1])/i[2]};return{xSnapped:r?s[0]*Math.round(a.x/s[0]):a.x,ySnapped:r?s[1]*Math.round(a.y/s[1]):a.y,...a}},[])}();return h.useEffect(()=>{if(null==e?void 0:e.current){const l=tm(e.current),h=({x:e,y:t})=>{const{nodeInternals:i,onNodeDrag:s,onSelectionDrag:n,updateNodePositions:o,nodeExtent:l,snapGrid:h,snapToGrid:f,nodeOrigin:p,onError:m}=a.getState();u.current={x:e,y:t};let g=!1,v={x:0,y:0,x2:0,y2:0};if(d.current.length>1&&l){const e=Av(d.current,p);v=Kg(e)}if(d.current=d.current.map(s=>{const r={x:e-s.distance.x,y:t-s.distance.y};f&&(r.x=h[0]*Math.round(r.x/h[0]),r.y=h[1]*Math.round(r.y/h[1]));const n=[[l[0][0],l[0][1]],[l[1][0],l[1][1]]];d.current.length>1&&l&&!s.extent&&(n[0][0]=s.positionAbsolute.x-v.x+l[0][0],n[1][0]=s.positionAbsolute.x+(s.width??0)-v.x2+l[1][0],n[0][1]=s.positionAbsolute.y-v.y+l[0][1],n[1][1]=s.positionAbsolute.y+(s.height??0)-v.y2+l[1][1]);const o=nx(s,r,i,n,p,m);return g=g||s.position.x!==o.position.x||s.position.y!==o.position.y,s.position=o.position,s.positionAbsolute=o.positionAbsolute,s}),!g)return;o(d.current,!0,!0),c(!0);const y=r?s:hx(n);if(y&&_.current){const[e,t]=ox({nodeId:r,dragItems:d.current,nodeInternals:i});y(_.current,e,t)}},b=()=>{if(!p.current)return;const[e,t]=Hg(m.current,p.current);if(0!==e||0!==t){const{transform:i,panBy:s}=a.getState();u.current.x=(u.current.x??0)-e/i[2],u.current.y=(u.current.y??0)-t/i[2],s({x:e,y:t})&&h(u.current)}f.current=requestAnimationFrame(b)},w=t=>{var i;const{nodeInternals:s,multiSelectionActive:l,nodesDraggable:c,unselectNodesAndEdges:h,onNodeDragStart:f,onSelectionDragStart:p}=a.getState();v.current=!0;const m=r?f:hx(p);o&&n||l||!r||(null==(i=s.get(r))?void 0:i.selected)||h(),r&&n&&o&&cx({id:r,store:a,nodeRef:e});const _=x(t);if(u.current=_,d.current=rx(s,c,_,r),m&&d.current){const[e,i]=ox({nodeId:r,dragItems:d.current,nodeInternals:s});m(t.sourceEvent,e,i)}};if(!t){const t=function(){var e,t,i,s,r=dm,n=um,o=fm,a=pm,l={},c=zf("start","drag","end"),h=0,d=0;function u(e){e.on("mousedown.drag",f).filter(a).on("touchstart.drag",_).on("touchmove.drag",g,sm).on("touchend.drag touchcancel.drag",v).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function f(o,a){if(!s&&r.call(this,o,a)){var l=y(this,n.call(this,o,a),o,a,"mouse");l&&(tm(o.view).on("mousemove.drag",p,rm).on("mouseup.drag",m,rm),am(o.view),nm(o),i=!1,e=o.clientX,t=o.clientY,l("start",o))}}function p(s){if(om(s),!i){var r=s.clientX-e,n=s.clientY-t;i=r*r+n*n>d}l.mouse("drag",s)}function m(e){tm(e.view).on("mousemove.drag mouseup.drag",null),lm(e.view,i),om(e),l.mouse("end",e)}function _(e,t){if(r.call(this,e,t)){var i,s,o=e.changedTouches,a=n.call(this,e,t),l=o.length;for(i=0;i<l;++i)(s=y(this,a,e,t,o[i].identifier,o[i]))&&(nm(e),s("start",e,o[i]))}}function g(e){var t,i,s=e.changedTouches,r=s.length;for(t=0;t<r;++t)(i=l[s[t].identifier])&&(om(e),i("drag",e,s[t]))}function v(e){var t,i,r=e.changedTouches,n=r.length;for(s&&clearTimeout(s),s=setTimeout(function(){s=null},500),t=0;t<n;++t)(i=l[r[t].identifier])&&(nm(e),i("end",e,r[t]))}function y(e,t,i,s,r,n){var a,d,f,p=c.copy(),m=im(n||i,t);if(null!=(f=o.call(e,new hm("beforestart",{sourceEvent:i,target:u,identifier:r,active:h,x:m[0],y:m[1],dx:0,dy:0,dispatch:p}),s)))return a=f.x-m[0]||0,d=f.y-m[1]||0,function i(n,o,c){var _,g=m;switch(n){case"start":l[r]=i,_=h++;break;case"end":delete l[r],--h;case"drag":m=im(c||o,t),_=h}p.call(n,e,new hm(n,{sourceEvent:o,subject:f,target:u,identifier:r,active:_,x:m[0]+a,y:m[1]+d,dx:m[0]-g[0],dy:m[1]-g[1],dispatch:p}),s)}}return u.filter=function(e){return arguments.length?(r="function"==typeof e?e:cm(!!e),u):r},u.container=function(e){return arguments.length?(n="function"==typeof e?e:cm(e),u):n},u.subject=function(e){return arguments.length?(o="function"==typeof e?e:cm(e),u):o},u.touchable=function(e){return arguments.length?(a="function"==typeof e?e:cm(!!e),u):a},u.on=function(){var e=c.on.apply(c,arguments);return e===c?u:e},u.clickDistance=function(e){return arguments.length?(d=(e=+e)*e,u):Math.sqrt(d)},u}().on("start",e=>{const{domNode:t,nodeDragThreshold:i}=a.getState();0===i&&w(e),y.current=!1;const s=x(e);u.current=s,p.current=(null==t?void 0:t.getBoundingClientRect())||null,m.current=Qg(e.sourceEvent,p.current)}).on("drag",e=>{var t,i;const s=x(e),{autoPanOnNodeDrag:r,nodeDragThreshold:n}=a.getState();if("touchmove"===e.sourceEvent.type&&e.sourceEvent.touches.length>1&&(y.current=!0),!y.current){if(!g.current&&v.current&&r&&(g.current=!0,b()),!v.current){const r=s.xSnapped-((null==(t=null==u?void 0:u.current)?void 0:t.x)??0),o=s.ySnapped-((null==(i=null==u?void 0:u.current)?void 0:i.y)??0);Math.sqrt(r*r+o*o)>n&&w(e)}(u.current.x!==s.xSnapped||u.current.y!==s.ySnapped)&&d.current&&v.current&&(_.current=e.sourceEvent,m.current=Qg(e.sourceEvent,p.current),h(s))}}).on("end",e=>{if(v.current&&!y.current&&(c(!1),g.current=!1,v.current=!1,cancelAnimationFrame(f.current),d.current)){const{updateNodePositions:t,nodeInternals:i,onNodeDragStop:s,onSelectionDragStop:n}=a.getState(),o=r?s:hx(n);if(t(d.current,!1,!1),o){const[t,s]=ox({nodeId:r,dragItems:d.current,nodeInternals:i});o(e.sourceEvent,t,s)}}}).filter(t=>{const r=t.target;return!t.button&&(!i||!sx(r,`.${i}`,e))&&(!s||sx(r,s,e))});return l.call(t),()=>{l.on(".drag",null)}}l.on(".drag",null)}},[e,t,i,s,n,a,r,o,x]),l}function ux(){const e=Pg(),t=h.useCallback(t=>{const{nodeInternals:i,nodeExtent:s,updateNodePositions:r,getNodes:n,snapToGrid:o,snapGrid:a,onError:l,nodesDraggable:c}=e.getState(),h=n().filter(e=>e.selected&&(e.draggable||c&&void 0===e.draggable)),d=o?a[0]:5,u=o?a[1]:5,f=t.isShiftPressed?4:1,p=t.x*d*f,m=t.y*u*f,_=h.map(e=>{if(e.positionAbsolute){const t={x:e.positionAbsolute.x+p,y:e.positionAbsolute.y+m};o&&(t.x=a[0]*Math.round(t.x/a[0]),t.y=a[1]*Math.round(t.y/a[1]));const{positionAbsolute:r,position:n}=nx(e,t,i,s,void 0,l);e.position=n,e.positionAbsolute=r}return e});r(_,!0,!1)},[]);return t}const fx={ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1},ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0}};var px=e=>{const t=({id:t,type:i,data:s,xPos:r,yPos:n,xPosOrigin:o,yPosOrigin:a,selected:l,onClick:c,onMouseEnter:d,onMouseMove:u,onMouseLeave:f,onContextMenu:p,onDoubleClick:m,style:_,className:g,isDraggable:v,isSelectable:y,isConnectable:x,isFocusable:b,selectNodesOnDrag:w,sourcePosition:S,targetPosition:C,hidden:k,resizeObserver:E,dragHandle:M,zIndex:j,isParent:D,noDragClassName:R,noPanClassName:P,initialized:L,disableKeyboardA11y:I,ariaLabel:T,rfId:B,hasHandleBounds:O})=>{const A=Pg(),z=h.useRef(null),$=h.useRef(null),H=h.useRef(S),W=h.useRef(C),F=h.useRef(i),K=y||v||c||d||u||f,U=ux(),V=lx(t,A.getState,d),q=lx(t,A.getState,u),Y=lx(t,A.getState,f),X=lx(t,A.getState,p),G=lx(t,A.getState,m);h.useEffect(()=>()=>{$.current&&(null==E||E.unobserve($.current),$.current=null)},[]),h.useEffect(()=>{if(z.current&&!k){const e=z.current;L&&O&&$.current===e||($.current&&(null==E||E.unobserve($.current)),null==E||E.observe(e),$.current=e)}},[k,L,O]),h.useEffect(()=>{const e=F.current!==i,s=H.current!==S,r=W.current!==C;z.current&&(e||s||r)&&(e&&(F.current=i),s&&(H.current=S),r&&(W.current=C),A.getState().updateNodeDimensions([{id:t,nodeElement:z.current,forceUpdate:!0}]))},[t,i,S,C]);const Z=dx({nodeRef:z,disabled:k||!v,noDragClassName:R,handleSelector:M,nodeId:t,isSelectable:y,selectNodesOnDrag:w});return k?null:N.createElement("div",{className:vf(["react-flow__node",`react-flow__node-${i}`,{[P]:v},g,{selected:l,selectable:y,parent:D,dragging:Z}]),ref:z,style:{zIndex:j,transform:`translate(${o}px,${a}px)`,pointerEvents:K?"all":"none",visibility:L?"visible":"hidden",..._},"data-id":t,"data-testid":`rf__node-${t}`,onMouseEnter:V,onMouseMove:q,onMouseLeave:Y,onContextMenu:X,onClick:e=>{const{nodeDragThreshold:i}=A.getState();if(y&&(!w||!v||i>0)&&cx({id:t,store:A,nodeRef:z}),c){const i=A.getState().nodeInternals.get(t);i&&c(e,{...i})}},onDoubleClick:G,onKeyDown:b?e=>{if(!Zg(e)&&!I)if(Gg.includes(e.key)&&y){const i="Escape"===e.key;cx({id:t,store:A,unselect:i,nodeRef:z})}else v&&l&&Object.prototype.hasOwnProperty.call(fx,e.key)&&(A.setState({ariaLiveMessage:`Moved selected node ${e.key.replace("Arrow","").toLowerCase()}. New position, x: ${~~r}, y: ${~~n}`}),U({x:fx[e.key].x,y:fx[e.key].y,isShiftPressed:e.shiftKey}))}:void 0,tabIndex:b?0:void 0,role:b?"button":void 0,"aria-describedby":I?void 0:`${xy}-${B}`,"aria-label":T},N.createElement(Pv,{value:t},N.createElement(e,{id:t,data:s,type:i,xPos:r,yPos:n,selected:l,isConnectable:x,sourcePosition:S,targetPosition:C,dragging:Z,dragHandle:M,zIndex:j})))};return t.displayName="NodeWrapper",h.memo(t)};const mx=e=>{const t=e.getNodes().filter(e=>e.selected);return{...Av(t,e.nodeOrigin),transformString:`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]})`,userSelectionActive:e.userSelectionActive}};var _x=h.memo(function({onSelectionContextMenu:e,noPanClassName:t,disableKeyboardA11y:i}){const s=Pg(),{width:r,height:n,x:o,y:a,transformString:l,userSelectionActive:c}=Rg(mx,Of),d=ux(),u=h.useRef(null);if(h.useEffect(()=>{var e;i||null==(e=u.current)||e.focus({preventScroll:!0})},[i]),dx({nodeRef:u}),c||!r||!n)return null;const f=e?t=>{const i=s.getState().getNodes().filter(e=>e.selected);e(t,i)}:void 0;return N.createElement("div",{className:vf(["react-flow__nodesselection","react-flow__container",t]),style:{transform:l}},N.createElement("div",{ref:u,className:"react-flow__nodesselection-rect",onContextMenu:f,tabIndex:i?void 0:-1,onKeyDown:i?void 0:e=>{Object.prototype.hasOwnProperty.call(fx,e.key)&&d({x:fx[e.key].x,y:fx[e.key].y,isShiftPressed:e.shiftKey})},style:{width:r,height:n,top:a,left:o}}))});const gx=e=>e.nodesSelectionActive,vx=({children:e,onPaneClick:t,onPaneMouseEnter:i,onPaneMouseMove:s,onPaneMouseLeave:r,onPaneContextMenu:n,onPaneScroll:o,deleteKeyCode:a,onMove:l,onMoveStart:c,onMoveEnd:d,selectionKeyCode:u,selectionOnDrag:f,selectionMode:p,onSelectionStart:m,onSelectionEnd:_,multiSelectionKeyCode:g,panActivationKeyCode:v,zoomActivationKeyCode:y,elementsSelectable:x,zoomOnScroll:b,zoomOnPinch:w,panOnScroll:S,panOnScrollSpeed:C,panOnScrollMode:k,zoomOnDoubleClick:E,panOnDrag:M,defaultViewport:j,translateExtent:D,minZoom:R,maxZoom:P,preventScrolling:L,onSelectionContextMenu:I,noWheelClassName:T,noPanClassName:B,disableKeyboardA11y:O})=>{const A=Rg(gx),z=ky(u),$=ky(v),H=$||M,W=$||S,F=z||f&&!0!==H;return(({deleteKeyCode:e,multiSelectionKeyCode:t})=>{const i=Pg(),{deleteElements:s}=Ay(),r=ky(e,zy),n=ky(t);h.useEffect(()=>{if(r){const{edges:e,getNodes:t}=i.getState(),r=t().filter(e=>e.selected),n=e.filter(e=>e.selected);s({nodes:r,edges:n}),i.setState({nodesSelectionActive:!1})}},[r]),h.useEffect(()=>{i.setState({multiSelectionActive:n})},[n])})({deleteKeyCode:a,multiSelectionKeyCode:g}),N.createElement(Vy,{onMove:l,onMoveStart:c,onMoveEnd:d,onPaneContextMenu:n,elementsSelectable:x,zoomOnScroll:b,zoomOnPinch:w,panOnScroll:W,panOnScrollSpeed:C,panOnScrollMode:k,zoomOnDoubleClick:E,panOnDrag:!z&&H,defaultViewport:j,translateExtent:D,minZoom:R,maxZoom:P,zoomActivationKeyCode:y,preventScrolling:L,noWheelClassName:T,noPanClassName:B},N.createElement(tx,{onSelectionStart:m,onSelectionEnd:_,onPaneClick:t,onPaneMouseEnter:i,onPaneMouseMove:s,onPaneMouseLeave:r,onPaneContextMenu:n,onPaneScroll:o,panOnDrag:H,isSelecting:!!F,selectionMode:p},e,A&&N.createElement(_x,{onSelectionContextMenu:I,noPanClassName:B,disableKeyboardA11y:O})))};vx.displayName="FlowRenderer";var yx=h.memo(vx);function xx(e){return{...{input:px(e.input||ry),default:px(e.default||iy),output:px(e.output||oy),group:px(e.group||ay)},...Object.keys(e).filter(e=>!["input","default","output","group"].includes(e)).reduce((t,i)=>(t[i]=px(e[i]||iy),t),{})}}const bx=e=>({nodesDraggable:e.nodesDraggable,nodesConnectable:e.nodesConnectable,nodesFocusable:e.nodesFocusable,elementsSelectable:e.elementsSelectable,updateNodeDimensions:e.updateNodeDimensions,onError:e.onError}),wx=e=>{const{nodesDraggable:t,nodesConnectable:i,nodesFocusable:s,elementsSelectable:r,updateNodeDimensions:n,onError:o}=Rg(bx,Of),a=(l=e.onlyRenderVisibleElements,Rg(h.useCallback(e=>l?zv(e.nodeInternals,{x:0,y:0,width:e.width,height:e.height},e.transform,!0):e.getNodes(),[l])));var l;const c=h.useRef(),d=h.useMemo(()=>{if("undefined"==typeof ResizeObserver)return null;const e=new ResizeObserver(e=>{const t=e.map(e=>({id:e.target.getAttribute("data-id"),nodeElement:e.target,forceUpdate:!0}));n(t)});return c.current=e,e},[]);return h.useEffect(()=>()=>{var e;null==(e=null==c?void 0:c.current)||e.disconnect()},[]),N.createElement("div",{className:"react-flow__nodes",style:$y},a.map(n=>{var a,l,c;let h=n.type||"default";e.nodeTypes[h]||(null==o||o("003",wg(h)),h="default");const u=e.nodeTypes[h]||e.nodeTypes.default,f=!!(n.draggable||t&&void 0===n.draggable),p=!!(n.selectable||r&&void 0===n.selectable),m=!!(n.connectable||i&&void 0===n.connectable),_=!!(n.focusable||s&&void 0===n.focusable),g=e.nodeExtent?zg(n.positionAbsolute,e.nodeExtent):n.positionAbsolute,v=(null==g?void 0:g.x)??0,y=(null==g?void 0:g.y)??0,x=(({x:e,y:t,width:i,height:s,origin:r})=>i&&s?r[0]<0||r[1]<0||r[0]>1||r[1]>1?{x:e,y:t}:{x:e-i*r[0],y:t-s*r[1]}:{x:e,y:t})({x:v,y:y,width:n.width??0,height:n.height??0,origin:e.nodeOrigin});return N.createElement(u,{key:n.id,id:n.id,className:n.className,style:n.style,type:h,data:n.data,sourcePosition:n.sourcePosition||mv.Bottom,targetPosition:n.targetPosition||mv.Top,hidden:n.hidden,xPos:v,yPos:y,xPosOrigin:x.x,yPosOrigin:x.y,selectNodesOnDrag:e.selectNodesOnDrag,onClick:e.onNodeClick,onMouseEnter:e.onNodeMouseEnter,onMouseMove:e.onNodeMouseMove,onMouseLeave:e.onNodeMouseLeave,onContextMenu:e.onNodeContextMenu,onDoubleClick:e.onNodeDoubleClick,selected:!!n.selected,isDraggable:f,isSelectable:p,isConnectable:m,isFocusable:_,resizeObserver:d,dragHandle:n.dragHandle,zIndex:(null==(a=n[Xg])?void 0:a.z)??0,isParent:!!(null==(l=n[Xg])?void 0:l.isParent),noDragClassName:e.noDragClassName,noPanClassName:e.noPanClassName,initialized:!!n.width&&!!n.height,rfId:e.rfId,disableKeyboardA11y:e.disableKeyboardA11y,ariaLabel:n.ariaLabel,hasHandleBounds:!!(null==(c=n[Xg])?void 0:c.handleBounds)})}))};wx.displayName="NodeRenderer";var Sx=h.memo(wx);const Cx=(e,t,i)=>i===mv.Left?e-t:i===mv.Right?e+t:e,kx=(e,t,i)=>i===mv.Top?e-t:i===mv.Bottom?e+t:e,Ex="react-flow__edgeupdater",Nx=({position:e,centerX:t,centerY:i,radius:s=10,onMouseDown:r,onMouseEnter:n,onMouseOut:o,type:a})=>N.createElement("circle",{onMouseDown:r,onMouseEnter:n,onMouseOut:o,className:vf([Ex,`${Ex}-${a}`]),cx:Cx(t,s,e),cy:kx(i,s,e),r:s,stroke:"transparent",fill:"transparent"}),Mx=()=>!0;var jx=e=>{const t=({id:t,className:i,type:s,data:r,onClick:n,onEdgeDoubleClick:o,selected:a,animated:l,label:c,labelStyle:d,labelShowBg:u,labelBgStyle:f,labelBgPadding:p,labelBgBorderRadius:m,style:_,source:g,target:v,sourceX:y,sourceY:x,targetX:b,targetY:w,sourcePosition:S,targetPosition:C,elementsSelectable:k,hidden:E,sourceHandleId:M,targetHandleId:j,onContextMenu:D,onMouseEnter:R,onMouseMove:P,onMouseLeave:L,reconnectRadius:I,onReconnect:T,onReconnectStart:B,onReconnectEnd:O,markerEnd:A,markerStart:z,rfId:$,ariaLabel:H,isFocusable:W,isReconnectable:F,pathOptions:K,interactionWidth:U,disableKeyboardA11y:V})=>{const q=h.useRef(null),[Y,X]=h.useState(!1),[G,Z]=h.useState(!1),J=Pg(),Q=h.useMemo(()=>`url('#${Iv(z,$)}')`,[z,$]),ee=h.useMemo(()=>`url('#${Iv(A,$)}')`,[A,$]);if(E)return null;const te=iv(t,J.getState,o),ie=iv(t,J.getState,D),se=iv(t,J.getState,R),re=iv(t,J.getState,P),ne=iv(t,J.getState,L),oe=(e,i)=>{if(0!==e.button)return;const{edges:s,isValidConnection:r}=J.getState(),n=i?v:g,o=(i?j:M)||null,a=i?"target":"source",l=r||Mx,c=i,h=s.find(e=>e.id===t);Z(!0),null==B||B(e,h,a);Gv({event:e,handleId:o,nodeId:n,onConnect:e=>null==T?void 0:T(h,e),isTarget:c,getState:J.getState,setState:J.setState,isValidConnection:l,edgeUpdaterType:a,onReconnectEnd:e=>{Z(!1),null==O||O(e,h,a)}})},ae=()=>X(!0),le=()=>X(!1),ce=!k&&!n;return N.createElement("g",{className:vf(["react-flow__edge",`react-flow__edge-${s}`,i,{selected:a,animated:l,inactive:ce,updating:Y}]),onClick:e=>{var i;const{edges:s,addSelectedEdges:r,unselectNodesAndEdges:o,multiSelectionActive:a}=J.getState(),l=s.find(e=>e.id===t);l&&(k&&(J.setState({nodesSelectionActive:!1}),l.selected&&a?(o({nodes:[],edges:[l]}),null==(i=q.current)||i.blur()):r([t])),n&&n(e,l))},onDoubleClick:te,onContextMenu:ie,onMouseEnter:se,onMouseMove:re,onMouseLeave:ne,onKeyDown:W?e=>{var i;if(!V&&Gg.includes(e.key)&&k){const{unselectNodesAndEdges:s,addSelectedEdges:r,edges:n}=J.getState();"Escape"===e.key?(null==(i=q.current)||i.blur(),s({edges:[n.find(e=>e.id===t)]})):r([t])}}:void 0,tabIndex:W?0:void 0,role:W?"button":"img","data-testid":`rf__edge-${t}`,"aria-label":null===H?void 0:H||`Edge from ${g} to ${v}`,"aria-describedby":W?`${by}-${$}`:void 0,ref:q},!G&&N.createElement(e,{id:t,source:g,target:v,selected:a,animated:l,label:c,labelStyle:d,labelShowBg:u,labelBgStyle:f,labelBgPadding:p,labelBgBorderRadius:m,data:r,style:_,sourceX:y,sourceY:x,targetX:b,targetY:w,sourcePosition:S,targetPosition:C,sourceHandleId:M,targetHandleId:j,markerStart:Q,markerEnd:ee,pathOptions:K,interactionWidth:U}),F&&N.createElement(N.Fragment,null,("source"===F||!0===F)&&N.createElement(Nx,{position:S,centerX:y,centerY:x,radius:I,onMouseDown:e=>oe(e,!0),onMouseEnter:ae,onMouseOut:le,type:"source"}),("target"===F||!0===F)&&N.createElement(Nx,{position:C,centerX:b,centerY:w,radius:I,onMouseDown:e=>oe(e,!1),onMouseEnter:ae,onMouseOut:le,type:"target"})))};return t.displayName="EdgeWrapper",h.memo(t)};function Dx(e){return{...{default:jx(e.default||Dv),straight:jx(e.bezier||Ev),step:jx(e.step||kv),smoothstep:jx(e.step||Cv),simplebezier:jx(e.simplebezier||yv)},...Object.keys(e).filter(e=>!["default","bezier"].includes(e)).reduce((t,i)=>(t[i]=jx(e[i]||Dv),t),{})}}function Rx(e,t,i=null){const s=((null==i?void 0:i.x)||0)+t.x,r=((null==i?void 0:i.y)||0)+t.y,n=(null==i?void 0:i.width)||t.width,o=(null==i?void 0:i.height)||t.height;switch(e){case mv.Top:return{x:s+n/2,y:r};case mv.Right:return{x:s+n,y:r+o/2};case mv.Bottom:return{x:s+n/2,y:r+o};case mv.Left:return{x:s,y:r+o/2}}}function Px(e,t){return e?1!==e.length&&t?t&&e.find(e=>e.id===t)||null:e[0]:null}function Lx(e){var t,i,s,r,n;const o=(null==(t=null==e?void 0:e[Xg])?void 0:t.handleBounds)||null,a=o&&(null==e?void 0:e.width)&&(null==e?void 0:e.height)&&void 0!==(null==(i=null==e?void 0:e.positionAbsolute)?void 0:i.x)&&void 0!==(null==(s=null==e?void 0:e.positionAbsolute)?void 0:s.y);return[{x:(null==(r=null==e?void 0:e.positionAbsolute)?void 0:r.x)||0,y:(null==(n=null==e?void 0:e.positionAbsolute)?void 0:n.y)||0,width:(null==e?void 0:e.width)||0,height:(null==e?void 0:e.height)||0},o,!!a]}const Ix=[{level:0,isMaxLevel:!0,edges:[]}];function Tx(e,t,i){const s=Rg(h.useCallback(i=>e?i.edges.filter(e=>{const s=t.get(e.source),r=t.get(e.target);return(null==s?void 0:s.width)&&(null==s?void 0:s.height)&&(null==r?void 0:r.width)&&(null==r?void 0:r.height)&&function({sourcePos:e,targetPos:t,sourceWidth:i,sourceHeight:s,targetWidth:r,targetHeight:n,width:o,height:a,transform:l}){const c={x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),x2:Math.max(e.x+i,t.x+r),y2:Math.max(e.y+s,t.y+n)};c.x===c.x2&&(c.x2+=1),c.y===c.y2&&(c.y2+=1);const h=Kg({x:(0-l[0])/l[2],y:(0-l[1])/l[2],width:o/l[2],height:a/l[2]}),d=Math.max(0,Math.min(h.x2,c.x2)-Math.max(h.x,c.x)),u=Math.max(0,Math.min(h.y2,c.y2)-Math.max(h.y,c.y));return Math.ceil(d*u)>0}({sourcePos:s.positionAbsolute||{x:0,y:0},targetPos:r.positionAbsolute||{x:0,y:0},sourceWidth:s.width,sourceHeight:s.height,targetWidth:r.width,targetHeight:r.height,width:i.width,height:i.height,transform:i.transform})}):i.edges,[e,t]));return function(e,t,i=!1){let s=-1;const r=e.reduce((e,r)=>{var n,o;const a=Yg(r.zIndex);let l=a?r.zIndex:0;if(i){const e=t.get(r.target),i=t.get(r.source),s=r.selected||(null==e?void 0:e.selected)||(null==i?void 0:i.selected),c=Math.max((null==(n=null==i?void 0:i[Xg])?void 0:n.z)||0,(null==(o=null==e?void 0:e[Xg])?void 0:o.z)||0,1e3);l=(a?r.zIndex:0)+(s?c:0)}return e[l]?e[l].push(r):e[l]=[r],s=l>s?l:s,e},{}),n=Object.entries(r).map(([e,t])=>{const i=+e;return{edges:t,level:i,isMaxLevel:i===s}});return 0===n.length?Ix:n}(s,t,i)}const Bx={[fv.Arrow]:({color:e="none",strokeWidth:t=1})=>N.createElement("polyline",{style:{stroke:e,strokeWidth:t},strokeLinecap:"round",strokeLinejoin:"round",fill:"none",points:"-5,-4 0,0 -5,4"}),[fv.ArrowClosed]:({color:e="none",strokeWidth:t=1})=>N.createElement("polyline",{style:{stroke:e,fill:e,strokeWidth:t},strokeLinecap:"round",strokeLinejoin:"round",points:"-5,-4 0,0 -5,4 -5,-4"})};const Ox=({id:e,type:t,color:i,width:s=12.5,height:r=12.5,markerUnits:n="strokeWidth",strokeWidth:o,orient:a="auto-start-reverse"})=>{const l=function(e){const t=Pg();return h.useMemo(()=>{var i,s;return Object.prototype.hasOwnProperty.call(Bx,e)?Bx[e]:(null==(s=(i=t.getState()).onError)||s.call(i,"009",kg(e)),null)},[e])}(t);return l?N.createElement("marker",{className:"react-flow__arrowhead",id:e,markerWidth:`${s}`,markerHeight:`${r}`,viewBox:"-10 -10 20 20",markerUnits:n,orient:a,refX:"0",refY:"0"},N.createElement(l,{color:i,strokeWidth:o})):null},Ax=({defaultColor:e,rfId:t})=>{const i=Rg(h.useCallback((({defaultColor:e,rfId:t})=>i=>{const s=[];return i.edges.reduce((i,r)=>([r.markerStart,r.markerEnd].forEach(r=>{if(r&&"object"==typeof r){const n=Iv(r,t);s.includes(n)||(i.push({id:n,color:r.color||e,...r}),s.push(n))}}),i),[]).sort((e,t)=>e.id.localeCompare(t.id))})({defaultColor:e,rfId:t}),[e,t]),(e,t)=>!(e.length!==t.length||e.some((e,i)=>e.id!==t[i].id)));return N.createElement("defs",null,i.map(e=>N.createElement(Ox,{id:e.id,key:e.id,type:e.type,color:e.color,width:e.width,height:e.height,markerUnits:e.markerUnits,strokeWidth:e.strokeWidth,orient:e.orient})))};Ax.displayName="MarkerDefinitions";var zx=h.memo(Ax);const $x=e=>({nodesConnectable:e.nodesConnectable,edgesFocusable:e.edgesFocusable,edgesUpdatable:e.edgesUpdatable,elementsSelectable:e.elementsSelectable,width:e.width,height:e.height,connectionMode:e.connectionMode,nodeInternals:e.nodeInternals,onError:e.onError}),Hx=({defaultMarkerColor:e,onlyRenderVisibleElements:t,elevateEdgesOnSelect:i,rfId:s,edgeTypes:r,noPanClassName:n,onEdgeContextMenu:o,onEdgeMouseEnter:a,onEdgeMouseMove:l,onEdgeMouseLeave:c,onEdgeClick:h,onEdgeDoubleClick:d,onReconnect:u,onReconnectStart:f,onReconnectEnd:p,reconnectRadius:m,children:_,disableKeyboardA11y:g})=>{const{edgesFocusable:v,edgesUpdatable:y,elementsSelectable:x,width:b,height:w,connectionMode:S,nodeInternals:C,onError:k}=Rg($x,Of),E=Tx(t,C,i);return b?N.createElement(N.Fragment,null,E.map(({level:t,edges:i,isMaxLevel:_})=>N.createElement("svg",{key:t,style:{zIndex:t},width:b,height:w,className:"react-flow__edges react-flow__container"},_&&N.createElement(zx,{defaultColor:e,rfId:s}),N.createElement("g",null,i.map(e=>{const[t,i,_]=Lx(C.get(e.source)),[b,w,E]=Lx(C.get(e.target));if(!_||!E)return null;let M=e.type||"default";r[M]||(null==k||k("011",Mg(M)),M="default");const j=r[M]||r.default,D=S===nv.Strict?w.target:(w.target??[]).concat(w.source??[]),R=Px(i.source,e.sourceHandle),P=Px(D,e.targetHandle),L=(null==R?void 0:R.position)||mv.Bottom,I=(null==P?void 0:P.position)||mv.Top,T=!!(e.focusable||v&&void 0===e.focusable),B=e.reconnectable||e.updatable,O=void 0!==u&&(B||y&&void 0===B);if(!R||!P)return null==k||k("008",Eg(R,e)),null;const{sourceX:A,sourceY:z,targetX:$,targetY:H}=((e,t,i,s,r,n)=>{const o=Rx(i,e,t),a=Rx(n,s,r);return{sourceX:o.x,sourceY:o.y,targetX:a.x,targetY:a.y}})(t,R,L,b,P,I);return N.createElement(j,{key:e.id,id:e.id,className:vf([e.className,n]),type:M,data:e.data,selected:!!e.selected,animated:!!e.animated,hidden:!!e.hidden,label:e.label,labelStyle:e.labelStyle,labelShowBg:e.labelShowBg,labelBgStyle:e.labelBgStyle,labelBgPadding:e.labelBgPadding,labelBgBorderRadius:e.labelBgBorderRadius,style:e.style,source:e.source,target:e.target,sourceHandleId:e.sourceHandle,targetHandleId:e.targetHandle,markerEnd:e.markerEnd,markerStart:e.markerStart,sourceX:A,sourceY:z,targetX:$,targetY:H,sourcePosition:L,targetPosition:I,elementsSelectable:x,onContextMenu:o,onMouseEnter:a,onMouseMove:l,onMouseLeave:c,onClick:h,onEdgeDoubleClick:d,onReconnect:u,onReconnectStart:f,onReconnectEnd:p,reconnectRadius:m,rfId:s,ariaLabel:e.ariaLabel,isFocusable:T,isReconnectable:O,pathOptions:"pathOptions"in e?e.pathOptions:void 0,interactionWidth:e.interactionWidth,disableKeyboardA11y:g})})))),_):null};Hx.displayName="EdgeRenderer";var Wx=h.memo(Hx);const Fx=e=>`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]})`;function Kx({children:e}){const t=Rg(Fx);return N.createElement("div",{className:"react-flow__viewport react-flow__container",style:{transform:t}},e)}const Ux={[mv.Left]:mv.Right,[mv.Right]:mv.Left,[mv.Top]:mv.Bottom,[mv.Bottom]:mv.Top},Vx=({nodeId:e,handleType:t,style:i,type:s=dv.Bezier,CustomComponent:r,connectionStatus:n})=>{var o,a,l;const{fromNode:c,handleId:d,toX:u,toY:f,connectionMode:p}=Rg(h.useCallback(t=>({fromNode:t.nodeInternals.get(e),handleId:t.connectionHandleId,toX:(t.connectionPosition.x-t.transform[0])/t.transform[2],toY:(t.connectionPosition.y-t.transform[1])/t.transform[2],connectionMode:t.connectionMode}),[e]),Of),m=null==(o=null==c?void 0:c[Xg])?void 0:o.handleBounds;let _=null==m?void 0:m[t];if(p===nv.Loose&&(_=_||(null==m?void 0:m["source"===t?"target":"source"])),!c||!_)return null;const g=d?_.find(e=>e.id===d):_[0],v=g?g.x+g.width/2:(c.width??0)/2,y=g?g.y+g.height/2:c.height??0,x=((null==(a=c.positionAbsolute)?void 0:a.x)??0)+v,b=((null==(l=c.positionAbsolute)?void 0:l.y)??0)+y,w=null==g?void 0:g.position,S=w?Ux[w]:null;if(!w||!S)return null;if(r)return N.createElement(r,{connectionLineType:s,connectionLineStyle:i,fromNode:c,fromHandle:g,fromX:x,fromY:b,toX:u,toY:f,fromPosition:w,toPosition:S,connectionStatus:n});let C="";const k={sourceX:x,sourceY:b,sourcePosition:w,targetX:u,targetY:f,targetPosition:S};return s===dv.Bezier?[C]=jv(k):s===dv.Step?[C]=Sv({...k,borderRadius:0}):s===dv.SmoothStep?[C]=Sv(k):s===dv.SimpleBezier?[C]=vv(k):C=`M${x},${b} ${u},${f}`,N.createElement("path",{d:C,fill:"none",className:"react-flow__connection-path",style:i})};Vx.displayName="ConnectionLine";const qx=e=>({nodeId:e.connectionNodeId,handleType:e.connectionHandleType,nodesConnectable:e.nodesConnectable,connectionStatus:e.connectionStatus,width:e.width,height:e.height});function Yx({containerStyle:e,style:t,type:i,component:s}){const{nodeId:r,handleType:n,nodesConnectable:o,width:a,height:l,connectionStatus:c}=Rg(qx,Of);return!!(r&&n&&a&&o)?N.createElement("svg",{style:e,width:a,height:l,className:"react-flow__edges react-flow__connectionline react-flow__container"},N.createElement("g",{className:vf(["react-flow__connection",c])},N.createElement(Vx,{nodeId:r,handleType:n,style:t,type:i,CustomComponent:s,connectionStatus:c}))):null}function Xx(e,t){h.useRef(null),Pg();return h.useMemo(()=>t(e),[e])}const Gx=({nodeTypes:e,edgeTypes:t,onMove:i,onMoveStart:s,onMoveEnd:r,onInit:n,onNodeClick:o,onEdgeClick:a,onNodeDoubleClick:l,onEdgeDoubleClick:c,onNodeMouseEnter:d,onNodeMouseMove:u,onNodeMouseLeave:f,onNodeContextMenu:p,onSelectionContextMenu:m,onSelectionStart:_,onSelectionEnd:g,connectionLineType:v,connectionLineStyle:y,connectionLineComponent:x,connectionLineContainerStyle:b,selectionKeyCode:w,selectionOnDrag:S,selectionMode:C,multiSelectionKeyCode:k,panActivationKeyCode:E,zoomActivationKeyCode:M,deleteKeyCode:j,onlyRenderVisibleElements:D,elementsSelectable:R,selectNodesOnDrag:P,defaultViewport:L,translateExtent:I,minZoom:T,maxZoom:B,preventScrolling:O,defaultMarkerColor:A,zoomOnScroll:z,zoomOnPinch:$,panOnScroll:H,panOnScrollSpeed:W,panOnScrollMode:F,zoomOnDoubleClick:K,panOnDrag:U,onPaneClick:V,onPaneMouseEnter:q,onPaneMouseMove:Y,onPaneMouseLeave:X,onPaneScroll:G,onPaneContextMenu:Z,onEdgeContextMenu:J,onEdgeMouseEnter:Q,onEdgeMouseMove:ee,onEdgeMouseLeave:te,onReconnect:ie,onReconnectStart:se,onReconnectEnd:re,reconnectRadius:ne,noDragClassName:oe,noWheelClassName:ae,noPanClassName:le,elevateEdgesOnSelect:ce,disableKeyboardA11y:he,nodeOrigin:de,nodeExtent:ue,rfId:fe})=>{const pe=Xx(e,xx),me=Xx(t,Dx);return function(e){const t=Ay(),i=h.useRef(!1);h.useEffect(()=>{!i.current&&t.viewportInitialized&&e&&(setTimeout(()=>e(t),1),i.current=!0)},[e,t.viewportInitialized])}(n),N.createElement(yx,{onPaneClick:V,onPaneMouseEnter:q,onPaneMouseMove:Y,onPaneMouseLeave:X,onPaneContextMenu:Z,onPaneScroll:G,deleteKeyCode:j,selectionKeyCode:w,selectionOnDrag:S,selectionMode:C,onSelectionStart:_,onSelectionEnd:g,multiSelectionKeyCode:k,panActivationKeyCode:E,zoomActivationKeyCode:M,elementsSelectable:R,onMove:i,onMoveStart:s,onMoveEnd:r,zoomOnScroll:z,zoomOnPinch:$,zoomOnDoubleClick:K,panOnScroll:H,panOnScrollSpeed:W,panOnScrollMode:F,panOnDrag:U,defaultViewport:L,translateExtent:I,minZoom:T,maxZoom:B,onSelectionContextMenu:m,preventScrolling:O,noDragClassName:oe,noWheelClassName:ae,noPanClassName:le,disableKeyboardA11y:he},N.createElement(Kx,null,N.createElement(Wx,{edgeTypes:me,onEdgeClick:a,onEdgeDoubleClick:c,onlyRenderVisibleElements:D,onEdgeContextMenu:J,onEdgeMouseEnter:Q,onEdgeMouseMove:ee,onEdgeMouseLeave:te,onReconnect:ie,onReconnectStart:se,onReconnectEnd:re,reconnectRadius:ne,defaultMarkerColor:A,noPanClassName:le,elevateEdgesOnSelect:!!ce,disableKeyboardA11y:he,rfId:fe},N.createElement(Yx,{style:y,type:v,component:x,containerStyle:b})),N.createElement("div",{className:"react-flow__edgelabel-renderer"}),N.createElement(Sx,{nodeTypes:pe,onNodeClick:o,onNodeDoubleClick:l,onNodeMouseEnter:d,onNodeMouseMove:u,onNodeMouseLeave:f,onNodeContextMenu:p,selectNodesOnDrag:P,onlyRenderVisibleElements:D,noPanClassName:le,noDragClassName:oe,disableKeyboardA11y:he,nodeOrigin:de,nodeExtent:ue,rfId:fe})))};Gx.displayName="GraphView";var Zx=h.memo(Gx);const Jx=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],Qx={rfId:"1",width:0,height:0,transform:[0,0,1],nodeInternals:new Map,edges:[],onNodesChange:null,onEdgesChange:null,hasDefaultNodes:!1,hasDefaultEdges:!1,d3Zoom:null,d3Selection:null,d3ZoomHandler:void 0,minZoom:.5,maxZoom:2,translateExtent:Jx,nodeExtent:Jx,nodesSelectionActive:!1,userSelectionActive:!1,userSelectionRect:null,connectionNodeId:null,connectionHandleId:null,connectionHandleType:"source",connectionPosition:{x:0,y:0},connectionStatus:null,connectionMode:nv.Strict,domNode:null,paneDragging:!1,noPanClassName:"nopan",nodeOrigin:[0,0],nodeDragThreshold:0,snapGrid:[15,15],snapToGrid:!1,nodesDraggable:!0,nodesConnectable:!0,nodesFocusable:!0,edgesFocusable:!0,edgesUpdatable:!0,elementsSelectable:!0,elevateNodesOnSelect:!0,fitViewOnInit:!1,fitViewOnInitDone:!1,fitViewOnInitOptions:void 0,onSelectionChange:[],multiSelectionActive:!1,connectionStartHandle:null,connectionEndHandle:null,connectionClickStartHandle:null,connectOnClick:!0,ariaLiveMessage:"",autoPanOnConnect:!0,autoPanOnNodeDrag:!0,connectionRadius:20,onError:(e,t)=>{},isValidConnection:void 0},eb=()=>{return e=(e,t)=>({...Qx,setNodes:i=>{const{nodeInternals:s,nodeOrigin:r,elevateNodesOnSelect:n}=t();e({nodeInternals:Dy(i,s,r,n)})},getNodes:()=>Array.from(t().nodeInternals.values()),setEdges:i=>{const{defaultEdgeOptions:s={}}=t();e({edges:i.map(e=>({...s,...e}))})},setDefaultNodesAndEdges:(i,s)=>{const r=void 0!==i,n=void 0!==s,o=r?Dy(i,new Map,t().nodeOrigin,t().elevateNodesOnSelect):new Map;e({nodeInternals:o,edges:n?s:[],hasDefaultNodes:r,hasDefaultEdges:n})},updateNodeDimensions:i=>{const{onNodesChange:s,nodeInternals:r,fitViewOnInit:n,fitViewOnInitDone:o,fitViewOnInitOptions:a,domNode:l,nodeOrigin:c}=t(),h=null==l?void 0:l.querySelector(".react-flow__viewport");if(!h)return;const d=window.getComputedStyle(h),{m22:u}=new window.DOMMatrixReadOnly(d.transform),f=i.reduce((e,t)=>{const i=r.get(t.id);if(null==i?void 0:i.hidden)r.set(i.id,{...i,[Xg]:{...i[Xg],handleBounds:void 0}});else if(i){const s=Og(t.nodeElement);s.width&&s.height&&(i.width!==s.width||i.height!==s.height||t.forceUpdate)&&(r.set(i.id,{...i,[Xg]:{...i[Xg],handleBounds:{source:ax(".source",t.nodeElement,u,c),target:ax(".target",t.nodeElement,u,c)}},...s}),e.push({id:i.id,type:"dimensions",dimensions:s}))}return e},[]);jy(r,c);const p=o||n&&!o&&Ry(t,{initial:!0,...a});e({nodeInternals:new Map(r),fitViewOnInitDone:p}),(null==f?void 0:f.length)>0&&(null==s||s(f))},updateNodePositions:(e,i=!0,s=!1)=>{const{triggerNodeChanges:r}=t();r(e.map(e=>{const t={id:e.id,type:"position",dragging:s};return i&&(t.positionAbsolute=e.positionAbsolute,t.position=e.position),t}))},triggerNodeChanges:i=>{const{onNodesChange:s,nodeInternals:r,hasDefaultNodes:n,nodeOrigin:o,getNodes:a,elevateNodesOnSelect:l}=t();if(null==i?void 0:i.length){if(n){const t=Dy(Gy(i,a()),r,o,l);e({nodeInternals:t})}null==s||s(i)}},addSelectedNodes:i=>{const{multiSelectionActive:s,edges:r,getNodes:n}=t();let o,a=null;s?o=i.map(e=>Zy(e,!0)):(o=Jy(n(),i),a=Jy(r,[])),Iy({changedNodes:o,changedEdges:a,get:t,set:e})},addSelectedEdges:i=>{const{multiSelectionActive:s,edges:r,getNodes:n}=t();let o,a=null;s?o=i.map(e=>Zy(e,!0)):(o=Jy(r,i),a=Jy(n(),[])),Iy({changedNodes:a,changedEdges:o,get:t,set:e})},unselectNodesAndEdges:({nodes:i,edges:s}={})=>{const{edges:r,getNodes:n}=t(),o=s||r,a=(i||n()).map(e=>(e.selected=!1,Zy(e.id,!1)));Iy({changedNodes:a,changedEdges:o.map(e=>Zy(e.id,!1)),get:t,set:e})},setMinZoom:i=>{const{d3Zoom:s,maxZoom:r}=t();null==s||s.scaleExtent([i,r]),e({minZoom:i})},setMaxZoom:i=>{const{d3Zoom:s,minZoom:r}=t();null==s||s.scaleExtent([r,i]),e({maxZoom:i})},setTranslateExtent:i=>{var s;null==(s=t().d3Zoom)||s.translateExtent(i),e({translateExtent:i})},resetSelectedElements:()=>{const{edges:i,getNodes:s}=t(),r=s().filter(e=>e.selected).map(e=>Zy(e.id,!1)),n=i.filter(e=>e.selected).map(e=>Zy(e.id,!1));Iy({changedNodes:r,changedEdges:n,get:t,set:e})},setNodeExtent:i=>{const{nodeInternals:s}=t();s.forEach(e=>{e.positionAbsolute=zg(e.position,i)}),e({nodeExtent:i,nodeInternals:new Map(s)})},panBy:e=>{const{transform:i,width:s,height:r,d3Zoom:n,d3Selection:o,translateExtent:a}=t();if(!n||!o||!e.x&&!e.y)return!1;const l=hg.translate(i[0]+e.x,i[1]+e.y).scale(i[2]),c=[[0,0],[s,r]],h=null==n?void 0:n.constrain()(l,c,a);return n.transform(o,h),i[0]!==h.x||i[1]!==h.y||i[2]!==h.k},cancelConnection:()=>e({connectionNodeId:Qx.connectionNodeId,connectionHandleId:Qx.connectionHandleId,connectionHandleType:Qx.connectionHandleType,connectionStatus:Qx.connectionStatus,connectionStartHandle:Qx.connectionStartHandle,connectionEndHandle:Qx.connectionEndHandle}),reset:()=>e({...Qx})}),t=Object.is,e?Bf(e,t):Bf;var e,t},tb=({children:e})=>{const t=h.useRef(null);return t.current||(t.current=eb()),N.createElement(bg,{value:t.current},e)};tb.displayName="ReactFlowProvider";const ib=({children:e})=>h.useContext(xg)?N.createElement(N.Fragment,null,e):N.createElement(tb,null,e);ib.displayName="ReactFlowWrapper";const sb={input:ry,default:iy,output:oy,group:ay},rb={default:Dv,straight:Ev,step:kv,smoothstep:Cv,simplebezier:yv},nb=[0,0],ob=[15,15],ab={x:0,y:0,zoom:1},lb={width:"100%",height:"100%",overflow:"hidden",position:"relative",zIndex:0},cb=h.forwardRef(({nodes:e,edges:t,defaultNodes:i,defaultEdges:s,className:r,nodeTypes:n=sb,edgeTypes:o=rb,onNodeClick:a,onEdgeClick:l,onInit:c,onMove:h,onMoveStart:d,onMoveEnd:u,onConnect:f,onConnectStart:p,onConnectEnd:m,onClickConnectStart:_,onClickConnectEnd:g,onNodeMouseEnter:v,onNodeMouseMove:y,onNodeMouseLeave:x,onNodeContextMenu:b,onNodeDoubleClick:w,onNodeDragStart:S,onNodeDrag:C,onNodeDragStop:k,onNodesDelete:E,onEdgesDelete:M,onSelectionChange:j,onSelectionDragStart:D,onSelectionDrag:R,onSelectionDragStop:P,onSelectionContextMenu:L,onSelectionStart:I,onSelectionEnd:T,connectionMode:B=nv.Strict,connectionLineType:O=dv.Bezier,connectionLineStyle:A,connectionLineComponent:z,connectionLineContainerStyle:$,deleteKeyCode:H="Backspace",selectionKeyCode:W="Shift",selectionOnDrag:F=!1,selectionMode:K=cv.Full,panActivationKeyCode:U="Space",multiSelectionKeyCode:V=(ev()?"Meta":"Control"),zoomActivationKeyCode:q=(ev()?"Meta":"Control"),snapToGrid:Y=!1,snapGrid:X=ob,onlyRenderVisibleElements:G=!1,selectNodesOnDrag:Z=!0,nodesDraggable:J,nodesConnectable:Q,nodesFocusable:ee,nodeOrigin:te=nb,edgesFocusable:ie,edgesUpdatable:se,elementsSelectable:re,defaultViewport:ne=ab,minZoom:oe=.5,maxZoom:ae=2,translateExtent:le=Jx,preventScrolling:ce=!0,nodeExtent:he,defaultMarkerColor:de="#b1b1b7",zoomOnScroll:ue=!0,zoomOnPinch:fe=!0,panOnScroll:pe=!1,panOnScrollSpeed:me=.5,panOnScrollMode:_e=av.Free,zoomOnDoubleClick:ge=!0,panOnDrag:ve=!0,onPaneClick:ye,onPaneMouseEnter:xe,onPaneMouseMove:be,onPaneMouseLeave:we,onPaneScroll:Se,onPaneContextMenu:Ce,children:ke,onEdgeContextMenu:Ee,onEdgeDoubleClick:Ne,onEdgeMouseEnter:Me,onEdgeMouseMove:je,onEdgeMouseLeave:De,onEdgeUpdate:Re,onEdgeUpdateStart:Pe,onEdgeUpdateEnd:Le,onReconnect:Ie,onReconnectStart:Te,onReconnectEnd:Be,reconnectRadius:Oe=10,edgeUpdaterRadius:Ae=10,onNodesChange:ze,onEdgesChange:$e,noDragClassName:He="nodrag",noWheelClassName:We="nowheel",noPanClassName:Fe="nopan",fitView:Ke=!1,fitViewOptions:Ue,connectOnClick:Ve=!0,attributionPosition:qe,proOptions:Ye,defaultEdgeOptions:Xe,elevateNodesOnSelect:Ge=!0,elevateEdgesOnSelect:Ze=!1,disableKeyboardA11y:Je=!1,autoPanOnConnect:Qe=!0,autoPanOnNodeDrag:et=!0,connectionRadius:tt=20,isValidConnection:it,onError:st,style:rt,id:nt,nodeDragThreshold:ot,...at},lt)=>{const ct=nt||"1";return N.createElement("div",{...at,style:{...rt,...lb},ref:lt,className:vf(["react-flow",r]),"data-testid":"rf__wrapper",id:nt},N.createElement(ib,null,N.createElement(Zx,{onInit:c,onMove:h,onMoveStart:d,onMoveEnd:u,onNodeClick:a,onEdgeClick:l,onNodeMouseEnter:v,onNodeMouseMove:y,onNodeMouseLeave:x,onNodeContextMenu:b,onNodeDoubleClick:w,nodeTypes:n,edgeTypes:o,connectionLineType:O,connectionLineStyle:A,connectionLineComponent:z,connectionLineContainerStyle:$,selectionKeyCode:W,selectionOnDrag:F,selectionMode:K,deleteKeyCode:H,multiSelectionKeyCode:V,panActivationKeyCode:U,zoomActivationKeyCode:q,onlyRenderVisibleElements:G,selectNodesOnDrag:Z,defaultViewport:ne,translateExtent:le,minZoom:oe,maxZoom:ae,preventScrolling:ce,zoomOnScroll:ue,zoomOnPinch:fe,zoomOnDoubleClick:ge,panOnScroll:pe,panOnScrollSpeed:me,panOnScrollMode:_e,panOnDrag:ve,onPaneClick:ye,onPaneMouseEnter:xe,onPaneMouseMove:be,onPaneMouseLeave:we,onPaneScroll:Se,onPaneContextMenu:Ce,onSelectionContextMenu:L,onSelectionStart:I,onSelectionEnd:T,onEdgeContextMenu:Ee,onEdgeDoubleClick:Ne,onEdgeMouseEnter:Me,onEdgeMouseMove:je,onEdgeMouseLeave:De,onReconnect:Ie??Re,onReconnectStart:Te??Pe,onReconnectEnd:Be??Le,reconnectRadius:Oe??Ae,defaultMarkerColor:de,noDragClassName:He,noWheelClassName:We,noPanClassName:Fe,elevateEdgesOnSelect:Ze,rfId:ct,disableKeyboardA11y:Je,nodeOrigin:te,nodeExtent:he}),N.createElement(gy,{nodes:e,edges:t,defaultNodes:i,defaultEdges:s,onConnect:f,onConnectStart:p,onConnectEnd:m,onClickConnectStart:_,onClickConnectEnd:g,nodesDraggable:J,nodesConnectable:Q,nodesFocusable:ee,edgesFocusable:ie,edgesUpdatable:se,elementsSelectable:re,elevateNodesOnSelect:Ge,minZoom:oe,maxZoom:ae,nodeExtent:he,onNodesChange:ze,onEdgesChange:$e,snapToGrid:Y,snapGrid:X,connectionMode:B,translateExtent:le,connectOnClick:Ve,defaultEdgeOptions:Xe,fitView:Ke,fitViewOptions:Ue,onNodesDelete:E,onEdgesDelete:M,onNodeDragStart:S,onNodeDrag:C,onNodeDragStop:k,onSelectionDrag:R,onSelectionDragStart:D,onSelectionDragStop:P,noPanClassName:Fe,nodeOrigin:te,rfId:ct,autoPanOnConnect:Qe,autoPanOnNodeDrag:et,onError:st,connectionRadius:tt,isValidConnection:it,nodeDragThreshold:ot}),N.createElement(fy,{onSelectionChange:j}),ke,N.createElement(Tg,{proOptions:Ye,position:qe}),N.createElement(Cy,{rfId:ct,disableKeyboardA11y:Je})))});cb.displayName="ReactFlow";const hb=e=>{var t;return null==(t=e.domNode)?void 0:t.querySelector(".react-flow__edgelabel-renderer")};function db({children:e}){const t=Rg(hb);return t?pt.createPortal(e,t):null}function ub(e,t){if(Object.is(e,t))return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(const[i,s]of e)if(!Object.is(s,t.get(i)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(const i of e)if(!t.has(i))return!1;return!0}const i=Object.keys(e);if(i.length!==Object.keys(t).length)return!1;for(const s of i)if(!Object.prototype.hasOwnProperty.call(t,s)||!Object.is(e[s],t[s]))return!1;return!0}const fb=({id:e,x:t,y:i,width:s,height:r,style:n,color:o,strokeColor:a,strokeWidth:l,className:c,borderRadius:h,shapeRendering:d,onClick:u,selected:f})=>{const{background:p,backgroundColor:m}=n||{},_=o||p||m;return N.createElement("rect",{className:vf(["react-flow__minimap-node",{selected:f},c]),x:t,y:i,rx:h,ry:h,width:s,height:r,fill:_,stroke:a,strokeWidth:l,shapeRendering:d,onClick:u?t=>u(t,e):void 0})};fb.displayName="MiniMapNode";var pb=h.memo(fb);const mb=e=>e.nodeOrigin,_b=e=>e.getNodes().filter(e=>!e.hidden&&e.width&&e.height),gb=e=>e instanceof Function?e:()=>e;var vb=h.memo(function({nodeStrokeColor:e="transparent",nodeColor:t="#e2e2e2",nodeClassName:i="",nodeBorderRadius:s=5,nodeStrokeWidth:r=2,nodeComponent:n=pb,onClick:o}){const a=Rg(_b,ub),l=Rg(mb),c=gb(t),h=gb(e),d=gb(i),u="undefined"==typeof window||window.chrome?"crispEdges":"geometricPrecision";return N.createElement(N.Fragment,null,a.map(e=>{const{x:t,y:i}=Ov(e,l).positionAbsolute;return N.createElement(n,{key:e.id,x:t,y:i,width:e.width,height:e.height,style:e.style,selected:e.selected,className:d(e),color:c(e),borderRadius:s,strokeColor:h(e),strokeWidth:r,shapeRendering:u,onClick:o,id:e.id})}))});const yb=e=>{const t=e.getNodes(),i={x:-e.transform[0]/e.transform[2],y:-e.transform[1]/e.transform[2],width:e.width/e.transform[2],height:e.height/e.transform[2]};return{viewBB:i,boundingRect:t.length>0?(s=Av(t,e.nodeOrigin),r=i,Ug(Fg(Kg(s),Kg(r)))):i,rfId:e.rfId};var s,r};function xb({style:e,className:t,nodeStrokeColor:i="transparent",nodeColor:s="#e2e2e2",nodeClassName:r="",nodeBorderRadius:n=5,nodeStrokeWidth:o=2,nodeComponent:a,maskColor:l="rgb(240, 240, 240, 0.6)",maskStrokeColor:c="none",maskStrokeWidth:d=1,position:u="bottom-right",onClick:f,onNodeClick:p,pannable:m=!1,zoomable:_=!1,ariaLabel:g="React Flow mini map",inversePan:v=!1,zoomStep:y=10,offsetScale:x=5}){const b=Pg(),w=h.useRef(null),{boundingRect:S,viewBB:C,rfId:k}=Rg(yb,ub),E=(null==e?void 0:e.width)??200,M=(null==e?void 0:e.height)??150,j=S.width/E,D=S.height/M,R=Math.max(j,D),P=R*E,L=R*M,I=x*R,T=S.x-(P-S.width)/2-I,B=S.y-(L-S.height)/2-I,O=P+2*I,A=L+2*I,z=`react-flow__minimap-desc-${k}`,$=h.useRef(0);$.current=R,h.useEffect(()=>{if(w.current){const e=tm(w.current),t=e=>{const{transform:t,d3Selection:i,d3Zoom:s}=b.getState();if("wheel"!==e.sourceEvent.type||!i||!s)return;const r=-e.sourceEvent.deltaY*(1===e.sourceEvent.deltaMode?.05:e.sourceEvent.deltaMode?1:.002)*y,n=t[2]*Math.pow(2,r);s.scaleTo(i,n)},i=e=>{const{transform:t,d3Selection:i,d3Zoom:s,translateExtent:r,width:n,height:o}=b.getState();if("mousemove"!==e.sourceEvent.type||!i||!s)return;const a=$.current*Math.max(1,t[2])*(v?-1:1),l={x:t[0]-e.sourceEvent.movementX*a,y:t[1]-e.sourceEvent.movementY*a},c=[[0,0],[n,o]],h=hg.translate(l.x,l.y).scale(t[2]),d=s.constrain()(h,c,r);s.transform(i,d)},s=yg().on("zoom",m?i:null).on("zoom.wheel",_?t:null);return e.call(s),()=>{e.on("zoom",null)}}},[m,_,v,y]);const H=f?e=>{const t=im(e);f(e,{x:t[0],y:t[1]})}:void 0,W=p?(e,t)=>{const i=b.getState().nodeInternals.get(t);p(e,i)}:void 0;return N.createElement(Ig,{position:u,style:e,className:vf(["react-flow__minimap",t]),"data-testid":"rf__minimap"},N.createElement("svg",{width:E,height:M,viewBox:`${T} ${B} ${O} ${A}`,role:"img","aria-labelledby":z,ref:w,onClick:H},g&&N.createElement("title",{id:z},g),N.createElement(vb,{onClick:W,nodeColor:s,nodeStrokeColor:i,nodeBorderRadius:n,nodeClassName:r,nodeStrokeWidth:o,nodeComponent:a}),N.createElement("path",{className:"react-flow__minimap-mask",d:`M${T-I},${B-I}h${O+2*I}v${A+2*I}h${-O-2*I}z\n M${C.x},${C.y}h${C.width}v${C.height}h${-C.width}z`,fill:l,fillRule:"evenodd",stroke:c,strokeWidth:d,pointerEvents:"none"})))}xb.displayName="MiniMap";var bb=h.memo(xb);function wb(e,t){if(Object.is(e,t))return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(const[i,s]of e)if(!Object.is(s,t.get(i)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(const i of e)if(!t.has(i))return!1;return!0}const i=Object.keys(e);if(i.length!==Object.keys(t).length)return!1;for(const s of i)if(!Object.prototype.hasOwnProperty.call(t,s)||!Object.is(e[s],t[s]))return!1;return!0}function Sb(){return N.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 32"},N.createElement("path",{d:"M32 18.133H18.133V32h-4.266V18.133H0v-4.266h13.867V0h4.266v13.867H32z"}))}function Cb(){return N.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 5"},N.createElement("path",{d:"M0 0h32v4.2H0z"}))}function kb(){return N.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 30"},N.createElement("path",{d:"M3.692 4.63c0-.53.4-.938.939-.938h5.215V0H4.708C2.13 0 0 2.054 0 4.63v5.216h3.692V4.631zM27.354 0h-5.2v3.692h5.17c.53 0 .984.4.984.939v5.215H32V4.631A4.624 4.624 0 0027.354 0zm.954 24.83c0 .532-.4.94-.939.94h-5.215v3.768h5.215c2.577 0 4.631-2.13 4.631-4.707v-5.139h-3.692v5.139zm-23.677.94c-.531 0-.939-.4-.939-.94v-5.138H0v5.139c0 2.577 2.13 4.707 4.708 4.707h5.138V25.77H4.631z"}))}function Eb(){return N.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 25 32"},N.createElement("path",{d:"M21.333 10.667H19.81V7.619C19.81 3.429 16.38 0 12.19 0 8 0 4.571 3.429 4.571 7.619v3.048H3.048A3.056 3.056 0 000 13.714v15.238A3.056 3.056 0 003.048 32h18.285a3.056 3.056 0 003.048-3.048V13.714a3.056 3.056 0 00-3.048-3.047zM12.19 24.533a3.056 3.056 0 01-3.047-3.047 3.056 3.056 0 013.047-3.048 3.056 3.056 0 013.048 3.048 3.056 3.056 0 01-3.048 3.047zm4.724-13.866H7.467V7.619c0-2.59 2.133-4.724 4.723-4.724 2.591 0 4.724 2.133 4.724 4.724v3.048z"}))}function Nb(){return N.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 25 32"},N.createElement("path",{d:"M21.333 10.667H19.81V7.619C19.81 3.429 16.38 0 12.19 0c-4.114 1.828-1.37 2.133.305 2.438 1.676.305 4.42 2.59 4.42 5.181v3.048H3.047A3.056 3.056 0 000 13.714v15.238A3.056 3.056 0 003.048 32h18.285a3.056 3.056 0 003.048-3.048V13.714a3.056 3.056 0 00-3.048-3.047zM12.19 24.533a3.056 3.056 0 01-3.047-3.047 3.056 3.056 0 013.047-3.048 3.056 3.056 0 013.048 3.048 3.056 3.056 0 01-3.048 3.047z"}))}const Mb=({children:e,className:t,...i})=>N.createElement("button",{type:"button",className:vf(["react-flow__controls-button",t]),...i},e);Mb.displayName="ControlButton";const jb=e=>({isInteractive:e.nodesDraggable||e.nodesConnectable||e.elementsSelectable,minZoomReached:e.transform[2]<=e.minZoom,maxZoomReached:e.transform[2]>=e.maxZoom}),Db=({style:e,showZoom:t=!0,showFitView:i=!0,showInteractive:s=!0,fitViewOptions:r,onZoomIn:n,onZoomOut:o,onFitView:a,onInteractiveChange:l,className:c,children:d,position:u="bottom-left"})=>{const f=Pg(),[p,m]=h.useState(!1),{isInteractive:_,minZoomReached:g,maxZoomReached:v}=Rg(jb,wb),{zoomIn:y,zoomOut:x,fitView:b}=Ay();if(h.useEffect(()=>{m(!0)},[]),!p)return null;return N.createElement(Ig,{className:vf(["react-flow__controls",c]),position:u,style:e,"data-testid":"rf__controls"},t&&N.createElement(N.Fragment,null,N.createElement(Mb,{onClick:()=>{y(),null==n||n()},className:"react-flow__controls-zoomin",title:"zoom in","aria-label":"zoom in",disabled:v},N.createElement(Sb,null)),N.createElement(Mb,{onClick:()=>{x(),null==o||o()},className:"react-flow__controls-zoomout",title:"zoom out","aria-label":"zoom out",disabled:g},N.createElement(Cb,null))),i&&N.createElement(Mb,{className:"react-flow__controls-fitview",onClick:()=>{b(r),null==a||a()},title:"fit view","aria-label":"fit view"},N.createElement(kb,null)),s&&N.createElement(Mb,{className:"react-flow__controls-interactive",onClick:()=>{f.setState({nodesDraggable:!_,nodesConnectable:!_,elementsSelectable:!_}),null==l||l(!_)},title:"toggle interactivity","aria-label":"toggle interactivity"},_?N.createElement(Nb,null):N.createElement(Eb,null)),d)};Db.displayName="Controls";var Rb,Pb,Lb=h.memo(Db);function Ib(e,t){if(Object.is(e,t))return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(const[i,s]of e)if(!Object.is(s,t.get(i)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(const i of e)if(!t.has(i))return!1;return!0}const i=Object.keys(e);if(i.length!==Object.keys(t).length)return!1;for(const s of i)if(!Object.prototype.hasOwnProperty.call(t,s)||!Object.is(e[s],t[s]))return!1;return!0}function Tb({color:e,dimensions:t,lineWidth:i}){return N.createElement("path",{stroke:e,strokeWidth:i,d:`M${t[0]/2} 0 V${t[1]} M0 ${t[1]/2} H${t[0]}`})}function Bb({color:e,radius:t}){return N.createElement("circle",{cx:t,cy:t,r:t,fill:e})}(Pb=Rb||(Rb={})).Lines="lines",Pb.Dots="dots",Pb.Cross="cross";const Ob={[Rb.Dots]:"#91919a",[Rb.Lines]:"#eee",[Rb.Cross]:"#e2e2e2"},Ab={[Rb.Dots]:1,[Rb.Lines]:1,[Rb.Cross]:6},zb=e=>({transform:e.transform,patternId:`pattern-${e.rfId}`});function $b({id:e,variant:t=Rb.Dots,gap:i=20,size:s,lineWidth:r=1,offset:n=2,color:o,style:a,className:l}){const c=h.useRef(null),{transform:d,patternId:u}=Rg(zb,Ib),f=o||Ob[t],p=s||Ab[t],m=t===Rb.Dots,_=t===Rb.Cross,g=Array.isArray(i)?i:[i,i],v=[g[0]*d[2]||1,g[1]*d[2]||1],y=p*d[2],x=_?[y,y]:v,b=m?[y/n,y/n]:[x[0]/n,x[1]/n];return N.createElement("svg",{className:vf(["react-flow__background",l]),style:{...a,position:"absolute",width:"100%",height:"100%",top:0,left:0},ref:c,"data-testid":"rf__background"},N.createElement("pattern",{id:u+e,x:d[0]%v[0],y:d[1]%v[1],width:v[0],height:v[1],patternUnits:"userSpaceOnUse",patternTransform:`translate(-${b[0]},-${b[1]})`},m?N.createElement(Bb,{color:f,radius:y/n}):N.createElement(Tb,{dimensions:x,color:f,lineWidth:r})),N.createElement("rect",{x:"0",y:"0",width:"100%",height:"100%",fill:`url(#${u+e})`}))}$b.displayName="Background";var Hb=h.memo($b);function Wb(e,t){switch(t.type){case"add_variable":return e.variables.some(e=>e.key===t.variable.key)?e:{...e,variables:[...e.variables,t.variable]};case"remove_variable":return{...e,variables:e.variables.filter(e=>e.key!==t.key)};case"update_variable":return void 0!==t.patch.key&&t.patch.key!==t.key&&e.variables.some(e=>e.key===t.patch.key)?e:{...e,variables:e.variables.map(e=>e.key===t.key?{...e,...t.patch}:e)};case"add_node":return{...e,nodes:[...e.nodes,t.node]};case"remove_node":return{...e,nodes:e.nodes.filter(e=>e.id!==t.nodeId),edges:e.edges.filter(e=>e.source!==t.nodeId&&e.target!==t.nodeId)};case"update_node":{const{type:i,...s}=t.patch;return{...e,nodes:e.nodes.map(e=>e.id===t.nodeId?{...e,...s}:e)}}case"move_node":return{...e,nodes:e.nodes.map(e=>e.id===t.nodeId?{...e,position:t.position}:e)};case"add_edge":{const i=t.sourceHandle??"default",s=e.edges.some(e=>e.source===t.source&&(e.sourceHandle??"default")===i&&e.target===t.target);if(s)return e;const r={id:cs("e"),source:t.source,sourceHandle:i,target:t.target};return{...e,edges:[...e.edges,r]}}case"remove_edge":return{...e,edges:e.edges.filter(e=>e.id!==t.edgeId)};case"set_track_name":return{...e,trackName:t.name};case"set_adapter":return{...e,adapter:t.adapter};case"replace":return t.flow;default:return e}}const Fb=h.createContext(null);function Kb({value:e,children:t}){return _.jsx(Fb.Provider,{value:e,children:t})}function Ub(){const e=h.useContext(Fb);if(!e)throw new Error("useGraphDispatch outside GraphProvider");return e.dispatch}function Vb(e){const t=h.useContext(Fb);return(null==t?void 0:t.nodeStates)?t.nodeStates.get(e)??null:null}const qb=[{type:"user_input",Icon:xi,label:"用户输入",iconClass:"text-pink-600 dark:text-pink-400"},{type:"llm",Icon:ci,label:"LLM 调用",iconClass:"text-orange-600 dark:text-orange-400"},{type:"if",Icon:_i,label:"逻辑判断",iconClass:"text-sky-600 dark:text-sky-400"}];function Yb(e,t){const i=cs("n");switch(e){case"user_input":return{id:i,type:"user_input",position:t,fields:[]};case"llm":return{id:i,type:"llm",position:t,promptTemplate:"",inputs:[],outputs:[]};case"if":return{id:i,type:"if",position:t,conditionExpr:""};default:throw new Error(`unknown node type: ${e}`)}}function Xb(){const e=Ub();return _.jsxs("aside",{className:"w-32 border-r border-border bg-background p-2 flex flex-col gap-2",children:[_.jsx("div",{className:"text-xs text-muted-foreground px-1",children:"拖入画布"}),qb.map(({type:t,Icon:i,label:s,iconClass:r})=>_.jsxs("div",{draggable:!0,role:"button",tabIndex:0,onDragStart:e=>{e.dataTransfer.setData("application/x-ccweb-flow-node",t),e.dataTransfer.effectAllowed="move"},onClick:()=>{const i=Yb(t,{x:200,y:200});e({type:"add_node",node:i})},onKeyDown:i=>{if("Enter"===i.key||" "===i.key){i.preventDefault();const s=Yb(t,{x:200,y:200});e({type:"add_node",node:s})}},className:"cursor-grab rounded-md border border-border bg-muted/40 hover:bg-accent px-2 py-2 text-sm flex items-center gap-1.5 transition-colors",children:[_.jsx(i,{className:`h-3.5 w-3.5 shrink-0 ${r}`}),_.jsx("span",{className:"text-foreground truncate",children:s})]},t))]})}function Gb({nodeId:e,icon:t,label:i}){const s=Ub();return _.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[_.jsx("span",{className:"text-base shrink-0 [&_svg]:h-4 [&_svg]:w-4",children:t}),_.jsx("span",{className:"font-medium flex-1 text-foreground truncate",children:i}),_.jsx("button",{type:"button",className:"nodrag inline-flex items-center justify-center h-5 w-5 rounded text-muted-foreground hover:text-destructive hover:bg-accent transition-colors",onClick:t=>{t.stopPropagation(),s({type:"remove_node",nodeId:e})},onPointerDown:e=>{e.stopPropagation()},title:"删除节点",children:_.jsx(S,{className:"h-3 w-3"})})]})}const Zb={user_input:function({id:e,data:t,selected:i}){var s;const r=Vb(e);return _.jsxs("div",{className:["rounded-lg border-2 px-3 py-2 min-w-[240px]","bg-pink-50 dark:bg-pink-950/40",i?"border-primary shadow":"border-pink-300 dark:border-pink-800",(n=r,"active"===n?"border-amber-500 ring-2 ring-amber-200 dark:ring-amber-900 animate-pulse":"completed"===n?"border-emerald-600 ring-1 ring-emerald-200 dark:ring-emerald-900":"failed"===n?"border-destructive ring-2 ring-red-200 dark:ring-red-900":"skipped"===n?"opacity-50 line-through":"")].join(" "),children:[_.jsx(ey,{type:"target",position:mv.Top}),_.jsx(Gb,{nodeId:e,icon:_.jsx(xi,{className:"text-pink-600 dark:text-pink-400"}),label:(null==(s=t.label)?void 0:s.trim())||"用户输入"}),_.jsx("div",{className:"font-mono text-sm text-foreground/80",children:0===t.fields.length?_.jsx("div",{className:"text-muted-foreground",children:"(无字段)"}):t.fields.map((e,t)=>_.jsxs("div",{className:"pl-1",children:[e.varKey," ",_.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",e.uiHint??"text",")"]})]},t))}),_.jsx(ey,{type:"source",position:mv.Bottom})]});var n},llm:function({id:e,data:t,selected:i}){var s;const r=Vb(e);return _.jsxs("div",{className:["rounded-lg border-2 px-3 py-2 min-w-[280px] max-w-[360px]","bg-orange-50 dark:bg-orange-950/40",i?"border-primary shadow":"border-orange-300 dark:border-orange-800",(n=r,"active"===n?"border-amber-500 ring-2 ring-amber-200 dark:ring-amber-900 animate-pulse":"completed"===n?"border-emerald-600 ring-1 ring-emerald-200 dark:ring-emerald-900":"failed"===n?"border-destructive ring-2 ring-red-200 dark:ring-red-900":"skipped"===n?"opacity-50 line-through":"")].join(" "),children:[_.jsx(ey,{type:"target",position:mv.Top}),_.jsx(Gb,{nodeId:e,icon:_.jsx(ci,{className:"text-orange-600 dark:text-orange-400"}),label:(null==(s=t.label)?void 0:s.trim())||"LLM 调用"}),_.jsxs("div",{className:"font-mono text-xs text-foreground/80",children:[_.jsxs("div",{className:"truncate",children:["prompt: ",t.promptTemplate.slice(0,60),t.promptTemplate.length>60?"…":""]}),_.jsxs("div",{className:"text-xs text-muted-foreground mt-1",children:[t.inputs.length," 输入 → ",t.outputs.length," 输出"]})]}),_.jsx(ey,{type:"source",position:mv.Bottom})]});var n},if:function({id:e,data:t,selected:i}){var s;const r=Vb(e);return _.jsxs("div",{className:["rounded-lg border-2 px-3 py-2 min-w-[240px]","bg-sky-50 dark:bg-sky-950/40",i?"border-primary shadow":"border-sky-300 dark:border-sky-800",(n=r,"active"===n?"border-amber-500 ring-2 ring-amber-200 dark:ring-amber-900 animate-pulse":"completed"===n?"border-emerald-600 ring-1 ring-emerald-200 dark:ring-emerald-900":"failed"===n?"border-destructive ring-2 ring-red-200 dark:ring-red-900":"skipped"===n?"opacity-50 line-through":"")].join(" "),children:[_.jsx(ey,{type:"target",position:mv.Top}),_.jsx(Gb,{nodeId:e,icon:_.jsx(_i,{className:"text-sky-600 dark:text-sky-400"}),label:(null==(s=t.label)?void 0:s.trim())||"逻辑判断"}),_.jsxs("div",{className:"font-mono text-sm text-foreground/80",children:["if (",t.conditionExpr||"<空条件>",")"]}),_.jsx(ey,{type:"source",position:mv.Bottom,id:"true",style:{left:"30%",background:"#10b981"}}),_.jsx(ey,{type:"source",position:mv.Bottom,id:"false",style:{left:"70%",background:"#ef4444"}}),_.jsxs("div",{className:"flex justify-between text-xs mt-1 px-2",children:[_.jsx("span",{className:"text-emerald-600 dark:text-emerald-400",children:"true"}),_.jsx("span",{className:"text-red-600 dark:text-red-400",children:"false"})]})]});var n}},Jb={deletable:function(e){const{id:t,sourceX:i,sourceY:s,targetX:r,targetY:n,sourcePosition:o,targetPosition:a,selected:l,style:c,markerEnd:d}=e,u=Ub(),[f,p]=h.useState(!1),[m,g,v]=jv({sourceX:i,sourceY:s,sourcePosition:o,targetX:r,targetY:n,targetPosition:a});return _.jsxs(_.Fragment,{children:[_.jsx(tv,{id:t,path:m,markerEnd:d,style:c}),_.jsx("path",{d:m,fill:"none",stroke:"transparent",strokeWidth:20,onMouseEnter:()=>p(!0),onMouseLeave:()=>p(!1),style:{cursor:"pointer"}}),_.jsx(db,{children:(f||l)&&_.jsx("div",{style:{position:"absolute",transform:`translate(-50%, -50%) translate(${g}px, ${v}px)`,pointerEvents:"all"},className:"nodrag nopan",onMouseEnter:()=>p(!0),onMouseLeave:()=>p(!1),children:_.jsx("button",{type:"button",onClick:e=>{e.stopPropagation(),u({type:"remove_edge",edgeId:t})},className:"inline-flex items-center justify-center rounded-full bg-background border border-border text-muted-foreground hover:text-destructive hover:border-destructive/60 w-5 h-5 shadow transition-colors",title:"删除连线",children:_.jsx(S,{className:"h-3 w-3"})})})})]})}},Qb={type:"deletable"};function ew({flow:e,dispatch:t,selectedNodeId:i,onSelect:s}){const r=h.useRef(null),n=Ay(),o=h.useMemo(()=>function(e){const t=new Map;if(0===e.nodes.length)return t;const i=new Map;for(const a of e.nodes)i.set(a.id,0);for(const a of e.edges)null!==a.target&&i.set(a.target,(i.get(a.target)??0)+1);const s=e.nodes.filter(e=>0===(i.get(e.id)??0)),r=new Set,n=s.map(e=>e.id);let o=1;for(;n.length>0;){const i=n.shift();if(r.has(i))continue;r.add(i),t.set(i,o++);const s=e.edges.filter(e=>e.source===i&&null!==e.target);for(const e of s)e.target&&!r.has(e.target)&&n.push(e.target)}for(const a of e.nodes)r.has(a.id)||t.set(a.id,o++);return t}(e),[e]),a=h.useMemo(()=>e.nodes.map(e=>({id:e.id,type:e.type,position:e.position,data:e,selected:e.id===i})),[e.nodes,i]),l=h.useMemo(()=>e.edges.filter(e=>null!==e.target).map(e=>({id:e.id,source:e.source,target:e.target,sourceHandle:"default"===e.sourceHandle?null:e.sourceHandle??null,type:"deletable"})),[e.edges]),c=h.useCallback(e=>{for(const r of e)"position"===r.type&&r.position?t({type:"move_node",nodeId:r.id,position:r.position}):"remove"===r.type?t({type:"remove_node",nodeId:r.id}):"select"===r.type&&(r.selected?s(r.id):i===r.id&&s(null))},[t,s,i]),d=h.useCallback(e=>{for(const i of e)"remove"===i.type&&t({type:"remove_edge",edgeId:i.id})},[t]),u=h.useCallback(e=>{if(!e.source||!e.target)return;const i="true"===e.sourceHandle||"false"===e.sourceHandle?e.sourceHandle:"default";t({type:"add_edge",source:e.source,sourceHandle:i,target:e.target})},[t]);return _.jsxs("div",{ref:r,className:"flex-1 h-full relative",onDragOver:e=>{e.preventDefault(),e.dataTransfer.dropEffect="move"},onDrop:e=>{e.preventDefault();const i=e.dataTransfer.getData("application/x-ccweb-flow-node");if(!i)return;const s=Yb(i,n.screenToFlowPosition({x:e.clientX,y:e.clientY}));t({type:"add_node",node:s})},children:[_.jsxs(cb,{nodes:a,edges:l,onNodesChange:c,onEdgesChange:d,onConnect:u,nodeTypes:Zb,edgeTypes:Jb,defaultEdgeOptions:Qb,deleteKeyCode:["Delete","Backspace"],fitView:!0,children:[_.jsx(Hb,{}),_.jsx(Lb,{}),_.jsx(bb,{})]}),_.jsx("div",{className:"absolute inset-0 pointer-events-none",children:e.nodes.map(e=>{const t=o.get(e.id);if(void 0===t)return null;const i=n.flowToScreenPosition({x:e.position.x,y:e.position.y});return i?_.jsxs("div",{className:"absolute text-xs text-muted-foreground font-mono bg-background/80 px-1 rounded",style:{left:i.x-4,top:i.y-16},children:["#",t]},`label-${e.id}`):null})})]})}const tw=/^[a-zA-Z_][a-zA-Z0-9_]*$/;function iw(e,t){const i="@"===t?/@\{([^}]*)\}/g:/\$\{([^}]*)\}/g,s=new Set,r=[];let n;for(;null!==(n=i.exec(e));){const e=n[1]??"";tw.test(e)&&!s.has(e)&&(s.add(e),r.push(e))}return r}function sw(e){return iw(e,"@")}function rw(e){return iw(e,"$")}class nw{constructor(e){a(this,"pos",0),this.tokens=e}parseExpr(){let e=this.parseTerm();for(;this.peek("op","&&")||this.peek("op","||");){const t=this.tokens[this.pos].value;this.pos++;const i=this.parseTerm();e="&&"===t?{kind:"and",left:e,right:i}:{kind:"or",left:e,right:i}}return e}parseTerm(){const e=this.parseAtom(),t=this.peekOp(["==","!=",">","<",">=","<="]);if(t){this.pos++;return{kind:"compare",op:t,left:e,right:this.parseAtom()}}return e}parseAtom(){const e=this.tokens[this.pos];if(!e)throw new Error("unexpected end of input");if("num"===e.kind)return this.pos++,{kind:"literal",value:e.value};if("str"===e.kind)return this.pos++,{kind:"literal",value:e.value};if("kw"===e.kind){this.pos++;return{kind:"literal",value:"true"===e.value||"false"!==e.value&&null}}if("ident"===e.kind)return this.pos++,{kind:"var",name:e.value};if("punc"===e.kind&&"("===e.value){this.pos++;const e=this.parseExpr(),t=this.tokens[this.pos];if(!t||"punc"!==t.kind||")"!==t.value)throw new Error("missing closing paren");return this.pos++,e}throw new Error(`unexpected token ${JSON.stringify(e)}`)}peek(e,t){const i=this.tokens[this.pos];return!!i&&(i.kind===e&&(void 0===t||i.value===t))}peekOp(e){const t=this.tokens[this.pos];return t&&"op"===t.kind&&e.includes(t.value)?t.value:null}ensureFullyConsumed(){if(this.pos<this.tokens.length)throw new Error(`extra tokens after parse: ${JSON.stringify(this.tokens[this.pos])}`)}}function ow(e){const t=function(e){const t=[];let i=0;for(;i<e.length;){const s=e[i];if(/\s/.test(s)){i++;continue}if('"'===s){const s=e.indexOf('"',i+1);if(-1===s)throw new Error(`unterminated string at position ${i}`);t.push({kind:"str",value:e.slice(i+1,s)}),i=s+1;continue}if(/[0-9]/.test(s)||"-"===s&&/[0-9]/.test(e[i+1]??"")){let r=i+("-"===s?1:0);for(;r<e.length&&/[0-9.]/.test(e[r]);)r++;const n=e.slice(i,r),o=Number(n);if(Number.isNaN(o))throw new Error(`invalid number "${n}"`);t.push({kind:"num",value:o}),i=r;continue}if(/[a-zA-Z_]/.test(s)){let s=i;for(;s<e.length&&/[a-zA-Z0-9_]/.test(e[s]);)s++;const r=e.slice(i,s);"true"===r||"false"===r||"null"===r?t.push({kind:"kw",value:r}):t.push({kind:"ident",value:r}),i=s;continue}const r=e.slice(i,i+2);if(["==","!=",">=","<=","&&","||"].includes(r))t.push({kind:"op",value:r}),i+=2;else if(">"!==s&&"<"!==s){if("("!==s&&")"!==s)throw new Error(`unexpected character '${s}' at position ${i}`);t.push({kind:"punc",value:s}),i+=1}else t.push({kind:"op",value:s}),i+=1}return t}(e);if(0===t.length)throw new Error("empty expression");const i=new nw(t),s=i.parseExpr();return i.ensureFullyConsumed(),s}const aw=/^[a-zA-Z_][a-zA-Z0-9_]*$/,lw=new Set(["claude-code","codex","qwen","gemini"]);function cw(e){const t=new Set,i=new Set(["true","false","null"]);let s=0;for(;s<e.length;){const r=e[s];if('"'===r){const t=e.indexOf('"',s+1);if(-1===t)break;s=t+1;continue}if(/[a-zA-Z_]/.test(r)){let r=s;for(;r<e.length&&/[a-zA-Z0-9_]/.test(e[r]);)r++;const n=e.slice(s,r);i.has(n)||t.add(n),s=r;continue}s++}return[...t]}function hw({flow:e,projectId:t,filename:i,dirty:s,runStatus:r,onSaved:n,onClose:o}){const[a,l]=h.useState(!1),[c,d]=h.useState(null),u="idle"===r||"completed"===r||"failed"===r||"cancelled"===r;return _.jsxs("header",{className:"border-b border-border bg-background px-3 py-2 flex items-center gap-2",children:[_.jsx(K,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7",onClick:o,title:"关闭编辑器",children:_.jsx(hi,{className:"h-4 w-4"})}),_.jsx("div",{className:"font-mono text-sm text-foreground truncate",children:i}),s&&_.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-amber-500 dark:bg-amber-400",title:"未保存的修改"}),_.jsx("div",{className:"flex-1"}),_.jsxs(K,{type:"button",size:"sm",onClick:async()=>{d(null);const s=function(e){const t=[];lw.has(e.adapter)||t.push({level:"error",message:`非法 adapter: ${e.adapter}`});const i=new Set;for(const s of e.variables)aw.test(s.key)||t.push({level:"error",message:`变量 key "${s.key}" 不是合法 identifier`,variableKey:s.key}),i.has(s.key)?t.push({level:"error",message:`变量 key "${s.key}" 重名(duplicate)`,variableKey:s.key}):i.add(s.key);for(const s of e.nodes)if("llm"===s.type){const e=sw(s.promptTemplate),r=rw(s.promptTemplate);for(const n of[...e,...r])i.has(n)||t.push({level:"error",message:`LLM 节点 ${s.id} 引用未声明变量 "${n}"`,nodeId:s.id})}else if("user_input"===s.type){0===s.fields.length&&t.push({level:"error",message:`用户输入节点 ${s.id} 至少需要 1 个字段(空列表会让运行时弹一个没字段的 dialog)`,nodeId:s.id});const e=new Set;for(const r of s.fields)i.has(r.varKey)||t.push({level:"error",message:`用户输入节点 ${s.id} 字段引用未声明变量 "${r.varKey}"`,nodeId:s.id}),e.has(r.varKey)?t.push({level:"error",message:`用户输入节点 ${s.id} 字段 "${r.varKey}" 重复(dialog 会渲染两个同 key 输入,后者覆盖前者)`,nodeId:s.id}):e.add(r.varKey)}else if("if"===s.type){let e=!0;try{ow(s.conditionExpr)}catch(ll){e=!1,t.push({level:"error",message:`if 节点 ${s.id} 条件表达式语法错误:${ll.message}`,nodeId:s.id})}if(e||!1===e)for(const r of cw(s.conditionExpr))i.has(r)||t.push({level:"error",message:`if 节点 ${s.id} 条件引用未声明变量 "${r}"`,nodeId:s.id})}{const i=new Set;for(const s of e.nodes)i.has(s.id)?t.push({level:"error",message:`节点 id 重复:"${s.id}"(运行时只会执行其中一个)`,nodeId:s.id}):i.add(s.id)}for(const s of e.nodes)"llm"===s.type&&s.promptTemplate.length>65536&&t.push({level:"warning",message:`LLM 节点 ${s.id} promptTemplate 较长(${(s.promptTemplate.length/1024).toFixed(1)}KB),Ink TUI 大段 paste 行为不可预测`,nodeId:s.id});{const i=new Map;for(const t of e.edges){const e=t.sourceHandle??"default",s=`${t.source}::${e}`,r=i.get(s)??[];r.push(t.target??"(end)"),i.set(s,r)}for(const[e,s]of i)if(s.length>1){const[i,r]=e.split("::");t.push({level:"error",message:`节点 ${i} 的 ${r} 出口连了 ${s.length} 条边(${s.join(", ")}),运行时只会走第一条`,nodeId:i})}}if(0===e.nodes.length)t.push({level:"error",message:"空 flow(无任何节点 / 缺入口)"});else{const i=new Map;for(const t of e.nodes)i.set(t.id,0);for(const t of e.edges)null!==t.target&&i.set(t.target,(i.get(t.target)??0)+1);const s=e.nodes.filter(e=>0===(i.get(e.id)??0));0===s.length?t.push({level:"error",message:"无入口节点(图中存在环且无 in-degree=0 节点)"}):s.length>1&&t.push({level:"error",message:`多入口节点(不允许):${s.map(e=>e.id).join(", ")}`})}return{ok:0===t.filter(e=>"error"===e.level).length,errors:t}}(e);if(s.ok){l(!0);try{const s=us(e.variables);await os(t,i,e,s),n()}catch(ll){d(`保存失败:${ll.message}`)}finally{l(!1)}}else d(`无法保存:${s.errors.map(e=>e.message).join("; ")}`)},disabled:a,children:[_.jsx(Bt,{className:"h-3.5 w-3.5 mr-1"}),a?"保存中…":"保存"]}),u?_.jsxs(K,{type:"button",size:"sm",onClick:()=>{s?m.error("请先保存"):window.dispatchEvent(new CustomEvent("ccweb:flow-run-request",{detail:{filename:i}}))},disabled:s,title:s?"请先保存":"运行工作轨",className:"bg-emerald-600 text-white hover:bg-emerald-700 dark:bg-emerald-600 dark:hover:bg-emerald-500",children:[_.jsx(ki,{className:"h-3.5 w-3.5 mr-1 fill-current"}),"运行"]}):_.jsxs(K,{type:"button",variant:"destructive",size:"sm",onClick:()=>{window.dispatchEvent(new CustomEvent("ccweb:flow-cancel-request"))},children:[_.jsx(ji,{className:"h-3.5 w-3.5 mr-1 fill-current"}),"取消"]}),c&&_.jsx("div",{className:"text-xs text-destructive ml-2 max-w-md truncate",title:c,children:c})]})}const dw=/^[a-zA-Z_][a-zA-Z0-9_]*$/;function uw({value:e,onChange:t,placeholder:i}){const[s,r]=h.useState(!1),n=dw.test(e)||""===e;return _.jsxs("div",{children:[_.jsx(q,{type:"text",value:e,placeholder:i,onChange:e=>t(e.target.value),onBlur:()=>r(!0),className:g("h-8 text-sm font-mono",s&&!n&&"border-destructive focus-visible:ring-destructive")}),s&&!n&&_.jsx("div",{className:"text-xs text-destructive mt-1",children:"仅允许字母/数字/下划线,不能以数字开头"})]})}function fw({flow:e}){const t=Ub();return _.jsxs("aside",{className:"w-72 border-r border-border bg-background p-3 overflow-y-auto",children:[_.jsxs("div",{className:"flex items-center justify-between mb-2",children:[_.jsx("div",{className:"text-sm font-medium text-foreground",children:"变量声明"}),_.jsxs(K,{type:"button",variant:"outline",size:"sm",onClick:()=>{const i=`var${e.variables.length+1}`;t({type:"add_variable",variable:{key:i,description:"",initialValue:null}})},className:"h-7 px-2 text-xs",children:[_.jsx(V,{className:"h-3 w-3 mr-1"}),"新增"]})]}),0===e.variables.length&&_.jsx("div",{className:"text-xs text-muted-foreground",children:"(无变量)"}),_.jsx("div",{className:"space-y-2",children:e.variables.map((e,i)=>_.jsx(pw,{variable:e,dispatch:t},i))})]})}function pw({variable:e,dispatch:t}){const i=c(),s=i=>{t({type:"update_variable",key:e.key,patch:i})},r=e=>{if(""===e||"null"===e)return null;if("true"===e)return!0;if("false"===e)return!1;const t=Number(e);return!Number.isNaN(t)&&/^[0-9.+-]+$/.test(e)?t:e};return _.jsxs("div",{className:"border border-border rounded-md p-2 bg-muted/40 space-y-1",children:[_.jsxs("div",{className:"flex gap-1 items-start",children:[_.jsx("div",{className:"flex-1",children:_.jsx(uw,{value:e.key,onChange:i=>{i!==e.key&&t({type:"update_variable",key:e.key,patch:{key:i}})},placeholder:"变量名"})}),_.jsx(K,{type:"button",variant:"ghost",size:"icon",onClick:()=>{(async()=>{await i({description:`删除变量 "${e.key}"?`,confirmLabel:"删除",destructive:!0})&&t({type:"remove_variable",key:e.key})})()},title:"删除",className:"h-6 w-6 text-muted-foreground hover:text-destructive",children:_.jsx(S,{className:"h-3 w-3"})})]}),_.jsx(q,{type:"text",value:e.description,onChange:e=>s({description:e.target.value}),placeholder:"变量描述(含义)",className:"h-8 text-sm"}),_.jsx(q,{type:"text",value:(n=e.initialValue,null==n?"":"string"==typeof n?n:JSON.stringify(n)),onChange:e=>s({initialValue:r(e.target.value)}),placeholder:"初始值(可空)",className:"h-8 text-sm font-mono"})]});var n}const mw=h.forwardRef(({className:e,...t},i)=>_.jsx("textarea",{className:g("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",e),ref:i,...t}));mw.displayName="Textarea";const _w=/^[a-zA-Z_][a-zA-Z0-9_]*$/;function gw({value:e,variables:t,onChange:i,onCreateVariable:s,rows:r=5,placeholder:n}){const o=h.useRef(null),[a,l]=h.useState(null),[c,d]=h.useState(!1),[u,f]=h.useState(""),[p,m]=h.useState(null),v=a?t.filter(e=>e.key.toLowerCase().includes(a.filter.toLowerCase())):[],y=!!s,x=v.length+(y?1:0),b=()=>l(null),w=t=>{var s,r;if(!o.current)return;const n=(null==(s=S.current)?void 0:s.startPos)??(null==a?void 0:a.startPos),l=(null==(r=S.current)?void 0:r.trigger)??(null==a?void 0:a.trigger);if(void 0===n||void 0===l)return;const c=e.slice(0,n),h=e.slice(o.current.selectionStart),d=`${l}{${t}}`;i(c+d+h);const u=c.length+d.length;setTimeout(()=>{o.current&&(o.current.focus(),o.current.setSelectionRange(u,u))},0),b(),S.current=null},S=h.useRef(null),C=()=>{a&&(S.current={startPos:a.startPos,trigger:a.trigger},f(a.filter||""),m(null),d(!0),b())},k=()=>{const e=u.trim();_w.test(e)?t.some(t=>t.key===e)?m(`变量 "${e}" 已存在`):(s&&s(e),d(!1),w(e)):m("变量名只允许字母/数字/下划线,且不能以数字开头")};return h.useEffect(()=>{if(!a)return;const e=e=>{o.current&&!o.current.contains(e.target)&&b()};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[a]),_.jsxs("div",{className:"relative",children:[_.jsx(mw,{ref:o,value:e,onChange:e=>{const t=e.target.value,s=e.target.selectionStart;i(t);const r=t[s-1];if("@"!==r&&"$"!==r||a){if(a){const e=t.slice(a.startPos+1,s);if(!/^[a-zA-Z0-9_]*$/.test(e))return void b();l({...a,filter:e,selectedIndex:0})}}else l({trigger:r,startPos:s-1,filter:"",selectedIndex:0})},onKeyDown:e=>{if(a)if("Escape"===e.key)e.preventDefault(),b();else if("ArrowDown"===e.key)e.preventDefault(),l({...a,selectedIndex:Math.min(a.selectedIndex+1,x-1)});else if("ArrowUp"===e.key)e.preventDefault(),l({...a,selectedIndex:Math.max(a.selectedIndex-1,0)});else if("Enter"===e.key||"Tab"===e.key){if(0===x)return;e.preventDefault();const t=a.selectedIndex;t<v.length?(S.current={startPos:a.startPos,trigger:a.trigger},w(v[t].key)):y&&C()}},rows:r,placeholder:n,className:"font-mono text-sm"}),a&&x>0&&_.jsxs("div",{className:"absolute left-0 right-0 top-full mt-1 max-h-60 overflow-y-auto rounded-md border border-border bg-popover text-popover-foreground shadow-md z-50",children:[v.map((e,t)=>_.jsxs("div",{className:g("px-2 py-1 cursor-pointer text-sm",t===a.selectedIndex?"bg-accent text-accent-foreground":"hover:bg-accent/50"),onMouseDown:t=>{t.preventDefault(),S.current={startPos:a.startPos,trigger:a.trigger},w(e.key)},onMouseEnter:()=>l({...a,selectedIndex:t}),children:[_.jsxs("span",{className:"font-mono",children:[a.trigger,e.key]}),e.description&&_.jsx("span",{className:"text-xs text-muted-foreground ml-2",children:e.description})]},e.key)),y&&_.jsx("div",{className:g("px-2 py-1 cursor-pointer text-sm border-t border-border text-primary",a.selectedIndex===v.length?"bg-accent":"hover:bg-accent/50"),onMouseDown:e=>{e.preventDefault(),C()},onMouseEnter:()=>l({...a,selectedIndex:v.length}),children:"+ 新建变量"})]}),_.jsx(se,{open:c,onOpenChange:e=>{e||(S.current=null,d(!1))},children:_.jsxs(re,{className:"max-w-sm",children:[_.jsxs(ne,{children:[_.jsx(oe,{children:"新建变量"}),_.jsx(ae,{children:"变量名只允许字母/数字/下划线,且不能以数字开头。"})]}),_.jsxs("div",{className:"space-y-2",children:[_.jsx(le,{htmlFor:"new-var-name",className:"text-xs text-muted-foreground",children:"变量名"}),_.jsx(q,{id:"new-var-name",autoFocus:!0,value:u,onChange:e=>{f(e.target.value),m(null)},onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),k())},placeholder:"例:query_topic",className:"font-mono"}),p&&_.jsx("div",{className:"text-xs text-destructive",children:p})]}),_.jsxs(ce,{children:[_.jsx(K,{variant:"outline",size:"sm",onClick:()=>{S.current=null,d(!1)},children:"取消"}),_.jsx(K,{size:"sm",onClick:k,children:"创建"})]})]})})]})}function vw({flow:e,selectedNodeId:t}){const i=Ub(),s=c(),r=e.nodes.find(e=>e.id===t)??null;return r?_.jsxs("aside",{className:"w-96 border-l border-border bg-background p-4 overflow-y-auto",children:[_.jsxs("div",{className:"text-xs text-muted-foreground mb-2",children:["节点 ID: ",_.jsx("span",{className:"font-mono",children:r.id})]}),_.jsxs("div",{className:"text-xs text-muted-foreground mb-3",children:["类型: ",yw(r.type)]}),_.jsxs("div",{className:"mb-3 space-y-1.5",children:[_.jsx(le,{className:"text-xs text-muted-foreground",children:"显示名(运行可视化用)"}),_.jsx(q,{type:"text",value:r.label??"",onChange:e=>{const t=e.target.value.trim();i({type:"update_node",nodeId:r.id,patch:{label:""===t?void 0:e.target.value}})},placeholder:`默认: ${yw(r.type)}`,className:"h-8 text-sm"})]}),"user_input"===r.type&&_.jsx(bw,{node:r,variables:e.variables,dispatch:i}),"llm"===r.type&&_.jsx(ww,{node:r,variables:e.variables,dispatch:i}),"if"===r.type&&_.jsx(Sw,{node:r,dispatch:i}),_.jsx("div",{className:"mt-6 pt-3 border-t border-border",children:_.jsxs(K,{type:"button",variant:"outline",size:"sm",onClick:async()=>{await s({description:`确定删除节点 "${r.id}"?相关连线一起删除。`,confirmLabel:"删除",destructive:!0})&&i({type:"remove_node",nodeId:r.id})},className:"w-full text-destructive hover:text-destructive hover:bg-destructive/10 border-destructive/40",children:[_.jsx(L,{className:"h-3.5 w-3.5 mr-1"}),"删除节点"]})})]}):_.jsx("aside",{className:"w-96 border-l border-border bg-background p-4 text-sm text-muted-foreground",children:"选中节点编辑字段"})}function yw(e){return"user_input"===e?"用户输入":"llm"===e?"LLM 调用":"逻辑判断"}const xw=["text","textarea","number","bool","enum"];function bw({node:e,variables:t,dispatch:i}){const s=t=>i({type:"update_node",nodeId:e.id,patch:t}),r=(t,i)=>s({fields:e.fields.map((e,s)=>s===t?{...e,...i}:e)});return _.jsxs("div",{className:"space-y-3",children:[_.jsx(le,{className:"text-xs text-muted-foreground",children:"绑定变量"}),0===e.fields.length&&_.jsx("div",{className:"text-xs text-muted-foreground",children:"(无字段)"}),e.fields.map((i,n)=>_.jsxs("div",{className:"border border-border rounded-md p-2 bg-muted/40 space-y-1.5",children:[_.jsxs("div",{className:"flex gap-1 items-center",children:[_.jsx("div",{className:"flex-1",children:_.jsxs(Zt,{value:i.varKey,onValueChange:e=>r(n,{varKey:e}),children:[_.jsx(Jt,{className:"h-8 text-sm",children:_.jsx(Qt,{})}),_.jsx(ei,{children:t.map(e=>_.jsxs(ti,{value:e.key,children:[_.jsx("span",{className:"font-mono",children:e.key}),e.description&&_.jsxs("span",{className:"text-muted-foreground",children:[" — ",e.description]})]},e.key))})]})}),_.jsx(K,{type:"button",variant:"ghost",size:"icon",onClick:()=>{return t=n,s({fields:e.fields.filter((e,i)=>i!==t)});var t},title:"移除字段",className:"h-7 w-7 text-muted-foreground hover:text-destructive",children:_.jsx(S,{className:"h-3 w-3"})})]}),_.jsxs(Zt,{value:i.uiHint??"text",onValueChange:e=>r(n,{uiHint:e}),children:[_.jsx(Jt,{className:"h-8 text-sm",children:_.jsx(Qt,{})}),_.jsx(ei,{children:xw.map(e=>_.jsx(ti,{value:e??"text",children:e},e))})]})]},n)),_.jsxs(K,{type:"button",variant:"outline",size:"sm",onClick:()=>{if(0===t.length)return void m.error("请先在左侧变量声明面板中添加变量");const i={varKey:t[0].key,uiHint:"text"};s({fields:[...e.fields,i]})},className:"h-7 text-xs",children:[_.jsx(V,{className:"h-3 w-3 mr-1"}),"添加字段"]})]})}function ww({node:e,variables:t,dispatch:i}){return _.jsxs("div",{className:"space-y-3",children:[_.jsxs("div",{className:"space-y-1.5",children:[_.jsx(le,{className:"text-xs text-muted-foreground",children:"Prompt 模板"}),_.jsx(gw,{value:e.promptTemplate,variables:t,onChange:t=>{var s;s={promptTemplate:t,inputs:sw(t),outputs:rw(t)},i({type:"update_node",nodeId:e.id,patch:s})},onCreateVariable:e=>{i({type:"add_variable",variable:{key:e,description:"",initialValue:null}})},rows:6,placeholder:"@{var} 引用输入,${var} 标记输出"})]}),_.jsxs("div",{className:"text-xs text-muted-foreground",children:["自动推导:",e.inputs.length," 输入(",e.inputs.join(", ")||"—",")/ ",e.outputs.length," 输出(",e.outputs.join(", ")||"—",")"]})]})}function Sw({node:e,dispatch:t}){return _.jsxs("div",{className:"space-y-3",children:[_.jsx(le,{className:"text-xs text-muted-foreground",children:"条件表达式"}),_.jsx(q,{type:"text",value:e.conditionExpr,onChange:i=>t({type:"update_node",nodeId:e.id,patch:{conditionExpr:i.target.value}}),placeholder:"例:has_error == true",className:"h-8 text-sm font-mono"}),_.jsx("div",{className:"text-xs text-muted-foreground",children:"支持:变量名、字面量(null/true/false/数字/字符串)、比较运算(==、!=、>、<、>=、<=)、逻辑(&& ||)。求值在 M2b 实现。"})]})}function Cw({flow:e,run:t}){return"idle"===t.status?null:_.jsxs("div",{className:"border-t border-border bg-muted/40 px-3 py-2 text-xs space-y-1 max-h-64 overflow-y-auto",children:[_.jsxs("div",{className:"flex items-center gap-2",children:[_.jsx("span",{className:"font-medium text-foreground",children:"运行状态:"}),_.jsx("span",{className:Ew(t.status),children:kw(t.status)}),t.runId&&_.jsx("span",{className:"text-muted-foreground font-mono",children:t.runId}),t.currentNodeId&&_.jsxs("span",{className:"text-foreground",children:["当前: ",t.currentNodeId]})]}),t.quota&&_.jsxs("div",{className:"flex gap-4 text-muted-foreground",children:[void 0!==t.quota.iterRemaining&&_.jsxs("span",{children:["节点剩余迭代: ",t.quota.iterRemaining]}),_.jsxs("span",{children:["LLM 调用剩余: ",t.quota.llmCallsRemaining]}),_.jsxs("span",{children:["运行剩余: ",Math.floor(t.quota.durationRemainingMs/1e3),"s"]})]}),t.error&&_.jsxs("div",{className:"text-destructive",children:["错误: ",t.error]}),_.jsxs("div",{className:"mt-2",children:[_.jsx("div",{className:"text-muted-foreground mb-1",children:"变量值实时:"}),_.jsx("div",{className:"font-mono space-y-0.5",children:e.variables.map(e=>_.jsxs("div",{className:"flex gap-2",children:[_.jsx("span",{className:"text-sky-700 dark:text-sky-300",children:e.key}),_.jsxs("span",{className:"text-muted-foreground",children:["(",e.description,")"]}),_.jsxs("span",{className:"text-foreground",children:["= ",Nw(t.vars[e.key]??null)]})]},e.key))})]})]})}function kw(e){switch(e){case"running":return"运行中";case"waiting_user_input":return"等待用户输入";case"completed":return"完成";case"failed":return"失败";case"cancelled":return"已取消";default:return e}}function Ew(e){switch(e){case"running":return"text-sky-600 dark:text-sky-400";case"waiting_user_input":return"text-amber-600 dark:text-amber-400";case"completed":return"text-emerald-600 dark:text-emerald-400";case"failed":return"text-destructive";default:return"text-muted-foreground"}}function Nw(e){return null==e?"null":"string"==typeof e?JSON.stringify(e):"number"==typeof e||"boolean"==typeof e?String(e):JSON.stringify(e)}const Mw={runId:null,status:"idle",nodeStates:new Map,vars:{},error:null,currentNodeId:null,pendingUserInput:null,quota:null};function jw({projectId:e,filename:t,isNew:i,runState:s,onClose:r,onDirtyChange:n}){const[o,a]=h.useReducer(Wb,function(e,t="claude-code"){return hs(e,t)}(t.replace(/\.flow$/,""))),[l,c]=h.useState(i?{kind:"ready"}:{kind:"loading"}),[d,u]=h.useState(null),[f,p]=h.useState(!1),m=s??Mw;h.useEffect(()=>{if(i)return;let s=!1;return(async()=>{try{const i=await ns(e,t);if(s)return;const r=ds(i.flow);if(!r.ok||!r.flow)return void c({kind:"error",message:`flow 解析失败:${r.reason}`});const n=i.trainJson?function(e,t){const i=new Set(e.variables.map(e=>e.key)),s=new Set(Object.keys(t)),r=[...i].filter(e=>!s.has(e)),n=[...s].filter(e=>!i.has(e));return{ok:0===r.length&&0===n.length,missingKeys:r,extraKeys:n}}(r.flow,i.trainJson):{ok:!0,missingKeys:[],extraKeys:[]};n.ok||c({kind:"desync",message:`train.json 与 variables 失同步(缺 ${n.missingKeys.length} / 多 ${n.extraKeys.length})`}),a({type:"replace",flow:r.flow}),n.ok&&c({kind:"ready"})}catch(ll){s||c({kind:"error",message:ll.message})}})(),()=>{s=!0}},[e,t,i]);const g=h.useRef(!1);h.useEffect(()=>{g.current?"ready"!==l.kind&&"desync"!==l.kind||p(!0):g.current=!0},[o]),h.useEffect(()=>{null==n||n(f)},[f,n]);if("loading"===l.kind)return _.jsx("div",{className:"flex items-center justify-center h-full bg-background text-muted-foreground",children:"加载中…"});const v="running"===m.status||"waiting_user_input"===m.status;return"error"===l.kind?_.jsxs("div",{className:"flex flex-col items-center justify-center h-full bg-background text-destructive gap-2 max-w-md mx-auto p-6",children:[_.jsx("div",{className:"font-medium",children:"加载失败"}),_.jsx("div",{className:"text-sm",children:l.message}),_.jsx(K,{onClick:r,variant:"outline",size:"sm",className:"mt-2",children:"关闭"})]}):_.jsx(tb,{children:_.jsx(Kb,{value:{dispatch:a,nodeStates:m.nodeStates},children:_.jsxs("div",{className:"flex flex-col h-full bg-background text-foreground",children:[_.jsx(hw,{flow:o,projectId:e,filename:t,dirty:f,runStatus:m.status,onSaved:()=>p(!1),onClose:()=>r()}),"desync"===l.kind&&_.jsxs("div",{className:"bg-amber-50 dark:bg-amber-950/40 border-b border-amber-200 dark:border-amber-900 px-3 py-1 text-xs text-amber-800 dark:text-amber-200",children:["⚠ ",l.message,"(保存时将以当前 variables 重新派生 train.json)"]}),_.jsxs("div",{className:"flex-1 flex overflow-hidden",children:[!v&&_.jsx(Xb,{}),!v&&_.jsx(fw,{flow:o}),_.jsx(ew,{flow:o,dispatch:a,selectedNodeId:d,onSelect:u}),!v&&_.jsx(vw,{flow:o,selectedNodeId:d})]}),_.jsx(Cw,{flow:o,run:m})]})})})}function Dw({projectId:e,filename:t,open:i,runState:s,onClose:r}){const n=c(),[o,a]=h.useState(!1),l=async()=>{if(o){if(!(await n({description:"未保存的修改将丢失。确认关闭吗?",confirmLabel:"关闭",destructive:!0})))return}window.dispatchEvent(new CustomEvent("ccweb:track-editor-closed")),r()};return _.jsx(se,{open:i,onOpenChange:e=>{e||l()},children:_.jsxs(re,{className:"max-w-[90vw] w-[90vw] h-[85vh] p-0 gap-0 flex flex-col overflow-hidden sm:rounded-lg [&>button.absolute]:hidden",onEscapeKeyDown:e=>{e.preventDefault(),l()},onPointerDownOutside:e=>{e.preventDefault(),l()},onInteractOutside:e=>{e.preventDefault()},children:[_.jsx(ne,{className:"sr-only",children:_.jsxs(oe,{children:["工作轨编辑器:",t]})}),_.jsx(jw,{projectId:e,filename:t,isNew:!1,runState:s,onClose:()=>{l()},onDirtyChange:a})]})})}function Rw({open:e,flow:t,pending:i,onSubmit:s,onCancel:r}){const[n,o]=h.useState({});h.useEffect(()=>{e&&o({})},[e,i.nodeId]);const a=(e,t)=>o(i=>({...i,[e]:t}));return _.jsx(se,{open:e,onOpenChange:e=>{e||r()},children:_.jsxs(mt,{children:[_.jsx(_t,{className:"z-[70]"}),_.jsxs(gt,{className:g("fixed left-[50%] top-[50%] z-[70] grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200","data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95","sm:rounded-xl"),children:[_.jsx(ne,{children:_.jsx(oe,{children:"需要您输入"})}),_.jsx("div",{className:"space-y-3",children:i.fields.map(e=>{const i=t.variables.find(t=>t.key===e.varKey),s=i?`${e.varKey}(${i.description})`:e.varKey,r=n[e.varKey]??"";return _.jsxs("div",{className:"space-y-1.5",children:[_.jsx(le,{className:"text-xs text-muted-foreground",children:s}),"textarea"===e.uiHint?_.jsx(mw,{value:r,onChange:t=>a(e.varKey,t.target.value),rows:4,className:"font-mono"}):"enum"===e.uiHint&&e.variants?_.jsxs(Zt,{value:r,onValueChange:t=>a(e.varKey,t),children:[_.jsx(Jt,{children:_.jsx(Qt,{placeholder:"(请选择)"})}),_.jsx(ei,{children:e.variants.map(e=>_.jsx(ti,{value:e,children:e},e))})]}):"number"===e.uiHint?_.jsx(q,{type:"number",value:r,onChange:t=>{const i=t.target.value;if(""===i)a(e.varKey,"");else{const t=Number(i);a(e.varKey,Number.isNaN(t)?i:t)}},className:"font-mono"}):"bool"===e.uiHint?_.jsxs("div",{className:"flex items-center gap-2",children:[_.jsx("input",{id:`flow-input-${e.varKey}`,type:"checkbox",checked:!!n[e.varKey],onChange:t=>a(e.varKey,t.target.checked),className:"h-4 w-4 accent-primary"}),_.jsx(le,{htmlFor:`flow-input-${e.varKey}`,className:"text-sm font-normal",children:n[e.varKey]?"是":"否"})]}):_.jsx(q,{type:"text",value:r,onChange:t=>a(e.varKey,t.target.value),className:"font-mono"})]},e.varKey)})}),_.jsxs(ce,{children:[_.jsx(K,{variant:"outline",size:"sm",onClick:r,children:"取消运行"}),_.jsx(K,{size:"sm",onClick:()=>{s(n)},children:"提交"})]})]})]})})}const Pw={runId:null,status:"idle",nodeStates:new Map,vars:{},error:null,currentNodeId:null,pendingUserInput:null,quota:null};function Lw(){const[e,t]=h.useState(Pw),i=h.useRef(null),s=h.useCallback(()=>{i.current=null,t(Pw)},[]),r=h.useCallback(e=>{i.current=e,t(t=>({...t,runId:e,status:"running",nodeStates:new Map,vars:{},error:null}))},[]),n=h.useCallback(e=>{var s;i.current=e.runId,t({runId:e.runId,status:e.status,nodeStates:new Map(Object.entries(e.nodeStates)),vars:e.snapshot,error:(null==(s=e.error)?void 0:s.message)??null,currentNodeId:e.currentNodeId,pendingUserInput:e.pendingUserInput??null,quota:e.quota??null})},[]);return h.useEffect(()=>{const e=e=>{const s=e.detail;(null==s?void 0:s.type)&&s.type.startsWith("flow_")&&i.current&&(s.runId&&s.runId!==i.current||t(e=>function(e,t){var i;const s=t.type;if("flow_started"===s)return{...e,status:"running",vars:t.initialVars??{}};if("flow_node_active"===s){const i=new Map(e.nodeStates);return i.set(t.nodeId,"active"),{...e,currentNodeId:t.nodeId,nodeStates:i,quota:t.quota??e.quota}}if("flow_node_completed"===s){const s=new Map(e.nodeStates);s.set(t.nodeId,"completed");const r=(null==(i=e.pendingUserInput)?void 0:i.nodeId)===t.nodeId;return{...e,nodeStates:s,pendingUserInput:r?null:e.pendingUserInput,status:r&&"waiting_user_input"===e.status?"running":e.status}}if("flow_node_failed"===s){const i=new Map(e.nodeStates);return t.nodeId&&i.set(t.nodeId,"failed"),{...e,status:"failed",nodeStates:i,error:t.reason??null,pendingUserInput:null}}if("flow_var_changed"===s)return{...e,vars:{...e.vars,[t.key]:t.value}};if("flow_user_input_required"===s)return{...e,status:"waiting_user_input",pendingUserInput:{nodeId:t.nodeId,fields:t.fields}};if("flow_done"===s)return{...e,status:"completed",currentNodeId:null,pendingUserInput:null};if("flow_cancelled"===s)return{...e,status:"cancelled",pendingUserInput:null};if("flow_error"===s)return{...e,status:"failed",error:t.message??"unknown",pendingUserInput:null};return e}(e,s)))};return window.addEventListener("ccweb:flow-msg",e),()=>window.removeEventListener("ccweb:flow-msg",e)},[]),{state:e,attachRunId:r,reset:s,hydrateFromBackend:n}}const Iw=200,Tw=520;const Bw=Object.freeze(Object.defineProperty({__proto__:null,ProjectPage:function(){const{id:e}=vt(),t=Je(),[i,s]=h.useState(null),[r,n]=h.useState(!0),[o,a]=h.useState(!1),[l,c]=h.useState(null),d=h.useCallback(e=>{c({filename:e})},[]),{state:u,attachRunId:f,reset:p,hydrateFromBackend:m}=Lw(),[v,y]=h.useState(null);h.useEffect(()=>{const e=e=>{const t=e.detail;(null==t?void 0:t.type)&&(t.type.startsWith("flow_")&&!t.runId||("flow_started"===t.type||"flow_user_input_required"===t.type?a(!0):"flow_done"!==t.type&&"flow_cancelled"!==t.type&&"flow_error"!==t.type&&"flow_node_failed"!==t.type||a(!1)))};return window.addEventListener("ccweb:flow-msg",e),()=>window.removeEventListener("ccweb:flow-msg",e)},[]),h.useEffect(()=>{if(!e)return;const t=e,i=e=>{const{filename:i}=e.detail??{};i&&(async()=>{var e;try{const e=ds((await ns(t,i)).flow);if(!e.ok||!e.flow)return void alert(`加载 flow 失败:${e.reason??"unknown"}`);y({filename:i,flow:e.flow});const{runId:s}=await function(e,t){return rs("POST",`/api/projects/${e}/track-flows/file/${encodeURIComponent(t)}/run`,{})}(t,i);f(s)}catch(ll){const s=ll;if(409===s.status&&"FLOW_ALREADY_RUNNING"===(null==(e=s.detail)?void 0:e.code)&&s.detail.runId){try{const e=await ls(t,s.detail.runId),i="pending"===e.status?"running":e.status;m({...e,status:i})}catch{f(s.detail.runId)}return}alert(`运行失败:${s.message}`),y(null)}})()},s=()=>{const e=null==v?void 0:v.filename;e&&as(t,e,u.runId??void 0).catch(()=>{})};return window.addEventListener("ccweb:flow-run-request",i),window.addEventListener("ccweb:flow-cancel-request",s),()=>{window.removeEventListener("ccweb:flow-run-request",i),window.removeEventListener("ccweb:flow-cancel-request",s)}},[e,f,m,u.runId,null==v?void 0:v.filename]),h.useEffect(()=>{if("completed"===u.status||"failed"===u.status||"cancelled"===u.status){const e=setTimeout(()=>{p(),y(null)},100);return()=>clearTimeout(e)}},[u.status,p]);const x=async t=>{if(e&&u.runId&&v)try{await function(e,t,i,s){return rs("POST",`/api/projects/${e}/track-flows/file/${encodeURIComponent(t)}/user_input`,{runId:i,values:s})}(e,v.filename,u.runId,t)}catch(ll){alert(`提交失败:${ll.message}`)}},[b,w]=he(E.panelFileTree,"true"),[S,C]=he(E.panelShortcuts,"true"),[k,N]=he(E.chatOverlay(e??""),"true"),M=h.useCallback(()=>N(e=>"true"===e?"false":"true"),[N]),[j,D]=h.useState([]),[R,P]=h.useState(!1),[L,I]=h.useState([]),B=h.useRef(0),O=h.useCallback(e=>{B.current+=1;const t={...e,seq:B.current};I(e=>{const i=[...e,t];return i.length>500?i.slice(-500):i})},[]),[A,z]=h.useState(null),W=h.useCallback(e=>O(e),[O]),F=h.useCallback(e=>O(e),[O]),U=h.useCallback(e=>{D(t=>{const i=[...t,e];return i.length>200?i.slice(-200):i})},[]),V=h.useCallback(()=>{D([]),z(null),P(!0)},[]),q=h.useCallback(()=>{P(!1)},[]),Y=h.useCallback(async e=>{var t,i;if(e.endsWith("\r")){const i=e.slice(0,-1);if(re.current){if("failed"===await re.current.sendCommand(i))throw new Error("chat send failed");return}const s=i.trimStart().startsWith("/")?i.replace(/\n/g,"\r")+"\r":yt(i);return void(null==(t=se.current)||t.sendTerminalInput(s))}null==(i=se.current)||i.sendTerminalInput(e)},[]),[X,G]=he(E.panelLeftWidth,String(224)),[Z,J]=he(E.panelRightWidth,String(208)),Q=parseInt(X,10)||224,ee=parseInt(Z,10)||208,te=h.useRef(null),ie=h.useRef(null),se=h.useRef(null),re=h.useRef(null);h.useEffect(()=>{const e=e=>{(e.ctrlKey||e.metaKey)&&"i"===e.key&&"terminal"!==(null==i?void 0:i.cliTool)&&(e.preventDefault(),M())};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[M,null==i?void 0:i.cliTool]);const ne=h.useRef(null);h.useEffect(()=>{const e=(null==i?void 0:i.cliTool)??null;e&&ne.current&&e!==ne.current&&(D([]),I([]),B.current=0,z(null)),ne.current=e},[null==i?void 0:i.cliTool]);const[oe,ae]=h.useState("terminal"),[le,ce]=h.useState(()=>window.innerWidth<768);h.useEffect(()=>{const e=()=>ce(window.innerWidth<768);return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]);const{fetchProjects:de,hasFetched:ue}=et();return h.useEffect(()=>{if(!e)return;(async()=>{ue||await de();const t=et.getState().projects.find(t=>t.id===e)??null;s(t),n(!1)})()},[e,ue,de]),r?_.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:_.jsx("span",{className:"text-muted-foreground text-sm",children:"Loading…"})}):i&&e?_.jsxs("div",{className:"h-screen flex flex-col bg-background",children:[_.jsx(zn,{project:i,projectId:e,showFileTree:"true"===b,showShortcuts:"true"===S,showChatOverlay:"true"===k,onToggleFileTree:()=>w(e=>"true"===e?"false":"true"),onToggleShortcuts:()=>C(e=>"true"===e?"false":"true"),onToggleChatOverlay:M,onProjectUpdate:s}),le?_.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col min-h-0",children:[_.jsxs("div",{className:"flex-1 overflow-hidden min-h-0",children:["files"===oe&&_.jsx(ys,{projectPath:i.folderPath,projectId:e,cliTool:i.cliTool,onSend:Y,onOpenTrackEditor:d}),"terminal"===oe&&_.jsx(pf,{ref:se,projectId:e,project:i,onStatusChange:e=>s(t=>t?{...t,status:e}:t)}),"panel"===oe&&_.jsx(Cn,{projectId:e,onSend:Y})]}),_.jsx("div",{className:"flex-shrink-0 flex border-t border-border bg-background pb-[env(safe-area-inset-bottom)]",children:[{id:"files",icon:T,label:"文件"},{id:"terminal",icon:xt,label:"终端"},{id:"panel",icon:Ci,label:"快捷"}].map(({id:e,icon:t,label:i})=>_.jsxs("button",{onClick:()=>ae(e),className:g("flex-1 flex flex-col items-center gap-0.5 py-2 text-[10px] transition-colors",oe===e?"text-blue-400":"text-muted-foreground hover:text-foreground"),children:[_.jsx(t,{className:"h-4 w-4"}),i]},e))})]}):_.jsxs("div",{className:"flex-1 overflow-hidden flex min-h-0",children:[_.jsx($,{initial:!1,children:"true"===b&&_.jsx(H.div,{ref:te,initial:{width:0,opacity:0},animate:{width:Q,opacity:1},exit:{width:0,opacity:0},transition:{duration:.2,ease:"easeInOut"},className:"flex-shrink-0 overflow-hidden",children:_.jsx(ys,{projectPath:i.folderPath,projectId:e,cliTool:i.cliTool,onSend:Y,onOpenTrackEditor:d})})}),"true"===b&&_.jsx("div",{onMouseDown:e=>{var t;e.preventDefault();const i=e.clientX,s=(null==(t=te.current)?void 0:t.offsetWidth)??Q;document.body.style.cursor="col-resize",document.body.style.userSelect="none";const r=e=>{const t=Math.max(Iw,Math.min(Tw,s+(e.clientX-i)));te.current&&(te.current.style.width=t+"px")},n=e=>{const t=Math.max(Iw,Math.min(Tw,s+(e.clientX-i)));G(String(t)),document.body.style.cursor="",document.body.style.userSelect="",window.removeEventListener("mousemove",r),window.removeEventListener("mouseup",n)};window.addEventListener("mousemove",r),window.addEventListener("mouseup",n)},className:"w-1 flex-shrink-0 bg-border hover:bg-blue-500/60 active:bg-blue-500/80 cursor-col-resize transition-colors"}),_.jsxs("div",{className:"flex-1 overflow-hidden min-w-0 relative flex flex-col",children:[_.jsx(gf,{projectId:e}),_.jsx(pf,{ref:se,projectId:e,project:i,onStatusChange:e=>s(t=>t?{...t,status:e}:t),onChatMessage:U,onWsConnected:V,onWsDisconnected:q,onApprovalRequest:W,onApprovalResolved:F,onSemanticUpdate:z}),_.jsx($,{children:"true"===k&&"terminal"!==i.cliTool&&_.jsx(Tt,{ref:re,projectId:e,project:i,liveMessages:j,approvalEvents:L,semanticUpdate:A,wsConnected:R,onSend:e=>{var t;return null==(t=se.current)?void 0:t.sendTerminalInput(e)},onClose:M,flowActive:o},"chat-overlay")})]}),"true"===S&&_.jsx("div",{onMouseDown:e=>{var t;e.preventDefault();const i=e.clientX,s=(null==(t=ie.current)?void 0:t.offsetWidth)??ee;document.body.style.cursor="col-resize",document.body.style.userSelect="none";const r=e=>{const t=Math.max(Iw,Math.min(Tw,s-(e.clientX-i)));ie.current&&(ie.current.style.width=t+"px")},n=e=>{const t=Math.max(Iw,Math.min(Tw,s-(e.clientX-i)));J(String(t)),document.body.style.cursor="",document.body.style.userSelect="",window.removeEventListener("mousemove",r),window.removeEventListener("mouseup",n)};window.addEventListener("mousemove",r),window.addEventListener("mouseup",n)},className:"w-1 flex-shrink-0 bg-border hover:bg-blue-500/60 active:bg-blue-500/80 cursor-col-resize transition-colors"}),_.jsx($,{initial:!1,children:"true"===S&&_.jsx(H.div,{ref:ie,initial:{width:0,opacity:0},animate:{width:ee,opacity:1},exit:{width:0,opacity:0},transition:{duration:.2,ease:"easeInOut"},className:"flex-shrink-0 overflow-hidden",children:_.jsx(Cn,{projectId:e,onSend:Y})})})]}),l&&_.jsx(Dw,{projectId:e,filename:l.filename,runState:(null==v?void 0:v.filename)===l.filename?u:null,open:!0,onClose:()=>c(null)}),u.pendingUserInput&&(null==v?void 0:v.flow)&&_.jsx(Rw,{open:!0,flow:v.flow,pending:u.pendingUserInput,onSubmit:e=>{x(e)},onCancel:()=>{(async()=>{if(e&&u.runId&&v){try{await as(e,v.filename,u.runId)}catch{}p(),y(null)}})()}})]}):_.jsxs("div",{className:"min-h-screen flex flex-col items-center justify-center gap-4 bg-background",children:[_.jsx("p",{className:"text-muted-foreground",children:"Project not found."}),_.jsxs(K,{variant:"outline",onClick:()=>t("/"),children:[_.jsx(qe,{className:"h-4 w-4 mr-2"}),"Back to Dashboard"]})]})}},Symbol.toStringTag,{value:"Module"}));export{Bw as P,Pi as Z,Li as a};
26
+ */var $n=Object.defineProperty,Hn=Object.getOwnPropertyDescriptor,Wn=(e,t,i,s)=>{for(var r,n=s>1?void 0:s?Hn(t,i):t,o=e.length-1;o>=0;o--)(r=e[o])&&(n=(s?r(t,i,n):r(n))||n);return s&&n&&$n(t,i,n),n},Fn=(e,t)=>(i,s)=>t(i,s,e),Kn="Terminal input",Un=()=>Kn,Vn=e=>Kn=e,qn="Too much output to announce, navigate to rows manually to read",Yn=()=>qn,Xn=e=>qn=e;function Gn(e,t,i,s){e=function(e,t){return t?"[200~"+e+"[201~":e}(e=function(e){return e.replace(/\r?\n/g,"\r")}(e),i.decPrivateModes.bracketedPasteMode&&!0!==s.rawOptions.ignoreBracketedPasteMode),i.triggerDataEvent(e,!0),t.value=""}function Zn(e,t,i){let s=i.getBoundingClientRect(),r=e.clientX-s.left-10,n=e.clientY-s.top-10;t.style.width="20px",t.style.height="20px",t.style.left=`${r}px`,t.style.top=`${n}px`,t.style.zIndex="1000",t.focus()}function Jn(e,t,i,s,r){Zn(e,t,i),r&&s.rightClickSelect(e),t.value=s.selectionText,t.select()}function Qn(e){return e>65535?(e-=65536,String.fromCharCode(55296+(e>>10))+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function eo(e,t=0,i=e.length){let s="";for(let r=t;r<i;++r){let t=e[r];t>65535?(t-=65536,s+=String.fromCharCode(55296+(t>>10))+String.fromCharCode(t%1024+56320)):s+=String.fromCharCode(t)}return s}var to=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let i=e.length;if(!i)return 0;let s=0,r=0;if(this._interim){let i=e.charCodeAt(r++);56320<=i&&i<=57343?t[s++]=1024*(this._interim-55296)+i-56320+65536:(t[s++]=this._interim,t[s++]=i),this._interim=0}for(let n=r;n<i;++n){let r=e.charCodeAt(n);if(55296<=r&&r<=56319){if(++n>=i)return this._interim=r,s;let o=e.charCodeAt(n);56320<=o&&o<=57343?t[s++]=1024*(r-55296)+o-56320+65536:(t[s++]=r,t[s++]=o);continue}65279!==r&&(t[s++]=r)}return s}},io=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let i=e.length;if(!i)return 0;let s,r,n,o,a=0,l=0,c=0;if(this.interim[0]){let s=!1,r=this.interim[0];r&=192==(224&r)?31:224==(240&r)?15:7;let n,o=0;for(;(n=63&this.interim[++o])&&o<4;)r<<=6,r|=n;let l=192==(224&this.interim[0])?2:224==(240&this.interim[0])?3:4,h=l-o;for(;c<h;){if(c>=i)return 0;if(n=e[c++],128!=(192&n)){c--,s=!0;break}this.interim[o++]=n,r<<=6,r|=63&n}s||(2===l?r<128?c--:t[a++]=r:3===l?r<2048||r>=55296&&r<=57343||65279===r||(t[a++]=r):r<65536||r>1114111||(t[a++]=r)),this.interim.fill(0)}let h=i-4,d=c;for(;d<i;){for(;!(!(d<h)||128&(s=e[d])||128&(r=e[d+1])||128&(n=e[d+2])||128&(o=e[d+3]));)t[a++]=s,t[a++]=r,t[a++]=n,t[a++]=o,d+=4;if(s=e[d++],s<128)t[a++]=s;else if(192==(224&s)){if(d>=i)return this.interim[0]=s,a;if(r=e[d++],128!=(192&r)){d--;continue}if(l=(31&s)<<6|63&r,l<128){d--;continue}t[a++]=l}else if(224==(240&s)){if(d>=i)return this.interim[0]=s,a;if(r=e[d++],128!=(192&r)){d--;continue}if(d>=i)return this.interim[0]=s,this.interim[1]=r,a;if(n=e[d++],128!=(192&n)){d--;continue}if(l=(15&s)<<12|(63&r)<<6|63&n,l<2048||l>=55296&&l<=57343||65279===l)continue;t[a++]=l}else if(240==(248&s)){if(d>=i)return this.interim[0]=s,a;if(r=e[d++],128!=(192&r)){d--;continue}if(d>=i)return this.interim[0]=s,this.interim[1]=r,a;if(n=e[d++],128!=(192&n)){d--;continue}if(d>=i)return this.interim[0]=s,this.interim[1]=r,this.interim[2]=n,a;if(o=e[d++],128!=(192&o)){d--;continue}if(l=(7&s)<<18|(63&r)<<12|(63&n)<<6|63&o,l<65536||l>1114111)continue;t[a++]=l}}return a}},so=" ",ro=class e{constructor(){this.fg=0,this.bg=0,this.extended=new no}static toColorRGB(e){return[e>>>16&255,e>>>8&255,255&e]}static fromColorRGB(e){return(255&e[0])<<16|(255&e[1])<<8|255&e[2]}clone(){let t=new e;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return 67108864&this.fg}isBold(){return 134217728&this.fg}isUnderline(){return this.hasExtendedAttrs()&&0!==this.extended.underlineStyle?1:268435456&this.fg}isBlink(){return 536870912&this.fg}isInvisible(){return 1073741824&this.fg}isItalic(){return 67108864&this.bg}isDim(){return 134217728&this.bg}isStrikethrough(){return 2147483648&this.fg}isProtected(){return 536870912&this.bg}isOverline(){return 1073741824&this.bg}getFgColorMode(){return 50331648&this.fg}getBgColorMode(){return 50331648&this.bg}isFgRGB(){return!(50331648&~this.fg)}isBgRGB(){return!(50331648&~this.bg)}isFgPalette(){return 16777216==(50331648&this.fg)||33554432==(50331648&this.fg)}isBgPalette(){return 16777216==(50331648&this.bg)||33554432==(50331648&this.bg)}isFgDefault(){return!(50331648&this.fg)}isBgDefault(){return!(50331648&this.bg)}isAttributeDefault(){return 0===this.fg&&0===this.bg}getFgColor(){switch(50331648&this.fg){case 16777216:case 33554432:return 255&this.fg;case 50331648:return 16777215&this.fg;default:return-1}}getBgColor(){switch(50331648&this.bg){case 16777216:case 33554432:return 255&this.bg;case 50331648:return 16777215&this.bg;default:return-1}}hasExtendedAttrs(){return 268435456&this.bg}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(268435456&this.bg&&~this.extended.underlineColor)switch(50331648&this.extended.underlineColor){case 16777216:case 33554432:return 255&this.extended.underlineColor;case 50331648:return 16777215&this.extended.underlineColor;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return 268435456&this.bg&&~this.extended.underlineColor?50331648&this.extended.underlineColor:this.getFgColorMode()}isUnderlineColorRGB(){return 268435456&this.bg&&~this.extended.underlineColor?!(50331648&~this.extended.underlineColor):this.isFgRGB()}isUnderlineColorPalette(){return 268435456&this.bg&&~this.extended.underlineColor?16777216==(50331648&this.extended.underlineColor)||33554432==(50331648&this.extended.underlineColor):this.isFgPalette()}isUnderlineColorDefault(){return 268435456&this.bg&&~this.extended.underlineColor?!(50331648&this.extended.underlineColor):this.isFgDefault()}getUnderlineStyle(){return 268435456&this.fg?268435456&this.bg?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},no=class e{constructor(e=0,t=0){this._ext=0,this._urlId=0,this._ext=e,this._urlId=t}get ext(){return this._urlId?-469762049&this._ext|this.underlineStyle<<26:this._ext}set ext(e){this._ext=e}get underlineStyle(){return this._urlId?5:(469762048&this._ext)>>26}set underlineStyle(e){this._ext&=-469762049,this._ext|=e<<26&469762048}get underlineColor(){return 67108863&this._ext}set underlineColor(e){this._ext&=-67108864,this._ext|=67108863&e}get urlId(){return this._urlId}set urlId(e){this._urlId=e}get underlineVariantOffset(){let e=(3758096384&this._ext)>>29;return e<0?4294967288^e:e}set underlineVariantOffset(e){this._ext&=536870911,this._ext|=e<<29&3758096384}clone(){return new e(this._ext,this._urlId)}isEmpty(){return 0===this.underlineStyle&&0===this._urlId}},oo=class e extends ro{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new no,this.combinedData=""}static fromCharData(t){let i=new e;return i.setFromCharData(t),i}isCombined(){return 2097152&this.content}getWidth(){return this.content>>22}getChars(){return 2097152&this.content?this.combinedData:2097151&this.content?Qn(2097151&this.content):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):2097151&this.content}setFromCharData(e){this.fg=e[0],this.bg=0;let t=!1;if(e[1].length>2)t=!0;else if(2===e[1].length){let i=e[1].charCodeAt(0);if(55296<=i&&i<=56319){let s=e[1].charCodeAt(1);56320<=s&&s<=57343?this.content=1024*(i-55296)+s-56320+65536|e[2]<<22:t=!0}else t=!0}else this.content=e[1].charCodeAt(0)|e[2]<<22;t&&(this.combinedData=e[1],this.content=2097152|e[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},ao="di$target",lo="di$dependencies",co=new Map;function ho(e){if(co.has(e))return co.get(e);let t=function(e,i,s){if(3!==arguments.length)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");!function(e,t,i){t[ao]===t?t[lo].push({id:e,index:i}):(t[lo]=[{id:e,index:i}],t[ao]=t)}(t,e,s)};return t._id=e,co.set(e,t),t}var uo=ho("BufferService"),fo=ho("CoreMouseService"),po=ho("CoreService"),mo=ho("CharsetService"),_o=ho("InstantiationService"),go=ho("LogService"),vo=ho("OptionsService"),yo=ho("OscLinkService"),xo=ho("UnicodeService"),bo=ho("DecorationService"),wo=class{constructor(e,t,i){this._bufferService=e,this._optionsService=t,this._oscLinkService=i}provideLinks(e,t){var i;let s=this._bufferService.buffer.lines.get(e-1);if(!s)return void t(void 0);let r=[],n=this._optionsService.rawOptions.linkHandler,o=new oo,a=s.getTrimmedLength(),l=-1,c=-1,h=!1;for(let d=0;d<a;d++)if(-1!==c||s.hasContent(d)){if(s.loadCell(d,o),o.hasExtendedAttrs()&&o.extended.urlId){if(-1===c){c=d,l=o.extended.urlId;continue}h=o.extended.urlId!==l}else-1!==c&&(h=!0);if(h||-1!==c&&d===a-1){let t=null==(i=this._oscLinkService.getLinkData(l))?void 0:i.uri;if(t){let i={start:{x:c+1,y:e},end:{x:d+(h||d!==a-1?0:1),y:e}},s=!1;if(!(null==n?void 0:n.allowNonHttpProtocols))try{let e=new URL(t);["http:","https:"].includes(e.protocol)||(s=!0)}catch{s=!0}s||r.push({text:t,range:i,activate:(e,t)=>n?n.activate(e,t,i):So(e,t),hover:(e,t)=>{var s;return null==(s=null==n?void 0:n.hover)?void 0:s.call(n,e,t,i)},leave:(e,t)=>{var s;return null==(s=null==n?void 0:n.leave)?void 0:s.call(n,e,t,i)}})}h=!1,o.hasExtendedAttrs()&&o.extended.urlId?(c=d,l=o.extended.urlId):(c=-1,l=-1)}}t(r)}};function So(e,t){if(confirm(`Do you want to navigate to ${t}?\n\nWARNING: This link could potentially be dangerous`)){let e=window.open();if(e){try{e.opener=null}catch{}e.location.href=t}else console.warn("Opening link blocked as opener could not be cleared")}}wo=Wn([Fn(0,uo),Fn(1,vo),Fn(2,yo)],wo);var Co=ho("CharSizeService"),ko=ho("CoreBrowserService"),Eo=ho("MouseService"),No=ho("RenderService"),Mo=ho("SelectionService"),jo=ho("CharacterJoinerService"),Do=ho("ThemeService"),Ro=ho("LinkProviderService"),Po=new class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?zo.isErrorNoTelemetry(e)?new zo(e.message+"\n\n"+e.stack):new Error(e.message+"\n\n"+e.stack):e},0)}}addListener(e){return this.listeners.push(e),()=>{this._removeListener(e)}}emit(e){this.listeners.forEach(t=>{t(e)})}_removeListener(e){this.listeners.splice(this.listeners.indexOf(e),1)}setUnexpectedErrorHandler(e){this.unexpectedErrorHandler=e}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(e){this.unexpectedErrorHandler(e),this.emit(e)}onUnexpectedExternalError(e){this.unexpectedErrorHandler(e)}};function Lo(e){(function(e){return e instanceof Io||e instanceof Error&&e.name===To&&e.message===To})(e)||Po.onUnexpectedError(e)}var To="Canceled";var Io=class extends Error{constructor(){super(To),this.name=this.message}};var Bo,Oo,Ao,zo=class e extends Error{constructor(e){super(e),this.name="CodeExpectedError"}static fromError(t){if(t instanceof e)return t;let i=new e;return i.message=t.message,i.stack=t.stack,i}static isErrorNoTelemetry(e){return"CodeExpectedError"===e.name}},$o=class e extends Error{constructor(t){super(t||"An unexpected bug occurred."),Object.setPrototypeOf(this,e.prototype)}};function Ho(e,t=0){return e[e.length-(1+t)]}function Wo(e,t){let i,s=this,r=!1;return function(){return r||(r=!0,t||(i=e.apply(s,arguments))),i}}function Fo(e){if(Ao.is(e)){let t=[];for(let i of e)if(i)try{i.dispose()}catch(Pa){t.push(Pa)}if(1===t.length)throw t[0];if(t.length>1)throw new AggregateError(t,"Encountered errors while disposing of store");return Array.isArray(e)?[]:e}if(e)return e.dispose(),e}function Ko(e){return{dispose:Wo(()=>{e()})}}(Oo=Bo||(Bo={})).isLessThan=function(e){return e<0},Oo.isLessThanOrEqual=function(e){return e<=0},Oo.isGreaterThan=function(e){return e>0},Oo.isNeitherLessOrGreaterThan=function(e){return 0===e},Oo.greaterThan=1,Oo.lessThan=-1,Oo.neitherLessOrGreaterThan=0,(e=>{function t(e){return e&&"object"==typeof e&&"function"==typeof e[Symbol.iterator]}e.is=t;let i=Object.freeze([]);function*s(e){yield e}e.empty=function(){return i},e.single=s,e.wrap=function(e){return t(e)?e:s(e)},e.from=function(e){return e||i},e.reverse=function*(e){for(let t=e.length-1;t>=0;t--)yield e[t]},e.isEmpty=function(e){return!e||!0===e[Symbol.iterator]().next().done},e.first=function(e){return e[Symbol.iterator]().next().value},e.some=function(e,t){let i=0;for(let s of e)if(t(s,i++))return!0;return!1},e.find=function(e,t){for(let i of e)if(t(i))return i},e.filter=function*(e,t){for(let i of e)t(i)&&(yield i)},e.map=function*(e,t){let i=0;for(let s of e)yield t(s,i++)},e.flatMap=function*(e,t){let i=0;for(let s of e)yield*t(s,i++)},e.concat=function*(...e){for(let t of e)yield*t},e.reduce=function(e,t,i){let s=i;for(let r of e)s=t(s,r);return s},e.slice=function*(e,t,i=e.length){for(t<0&&(t+=e.length),i<0?i+=e.length:i>e.length&&(i=e.length);t<i;t++)yield e[t]},e.consume=function(t,i=Number.POSITIVE_INFINITY){let s=[];if(0===i)return[s,t];let r=t[Symbol.iterator]();for(let n=0;n<i;n++){let t=r.next();if(t.done)return[s,e.empty()];s.push(t.value)}return[s,{[Symbol.iterator]:()=>r}]},e.asyncToArray=async function(e){let t=[];for await(let i of e)t.push(i);return Promise.resolve(t)}})(Ao||(Ao={}));var Uo=class e{constructor(){this._toDispose=new Set,this._isDisposed=!1}dispose(){this._isDisposed||(this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(0!==this._toDispose.size)try{Fo(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw new Error("Cannot register a disposable on itself!");return this._isDisposed?e.DISABLE_DISPOSED_WARNING||console.warn(new Error("Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!").stack):this._toDispose.add(t),t}delete(e){if(e){if(e===this)throw new Error("Cannot dispose a disposable on itself!");this._toDispose.delete(e),e.dispose()}}deleteAndLeak(e){e&&this._toDispose.has(e)&&this._toDispose.delete(e)}};Uo.DISABLE_DISPOSED_WARNING=!1;var Vo=Uo,qo=class{constructor(){this._store=new Vo,this._store}dispose(){this._store.dispose()}_register(e){if(e===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(e)}};qo.None=Object.freeze({dispose(){}});var Yo=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(e){var t;this._isDisposed||e===this._value||(null==(t=this._value)||t.dispose(),this._value=e)}clear(){this.value=void 0}dispose(){var e;this._isDisposed=!0,null==(e=this._value)||e.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e}},Xo="object"==typeof window?window:globalThis,Go=class e{constructor(t){this.element=t,this.next=e.Undefined,this.prev=e.Undefined}};Go.Undefined=new Go(void 0);var Zo,Jo=Go,Qo=class{constructor(){this._first=Jo.Undefined,this._last=Jo.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===Jo.Undefined}clear(){let e=this._first;for(;e!==Jo.Undefined;){let t=e.next;e.prev=Jo.Undefined,e.next=Jo.Undefined,e=t}this._first=Jo.Undefined,this._last=Jo.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let i=new Jo(e);if(this._first===Jo.Undefined)this._first=i,this._last=i;else if(t){let e=this._last;this._last=i,i.prev=e,e.next=i}else{let e=this._first;this._first=i,i.next=e,e.prev=i}this._size+=1;let s=!1;return()=>{s||(s=!0,this._remove(i))}}shift(){if(this._first!==Jo.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==Jo.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==Jo.Undefined&&e.next!==Jo.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===Jo.Undefined&&e.next===Jo.Undefined?(this._first=Jo.Undefined,this._last=Jo.Undefined):e.next===Jo.Undefined?(this._last=this._last.prev,this._last.next=Jo.Undefined):e.prev===Jo.Undefined&&(this._first=this._first.next,this._first.prev=Jo.Undefined);this._size-=1}*[Symbol.iterator](){let e=this._first;for(;e!==Jo.Undefined;)yield e.element,e=e.next}},ea=globalThis.performance&&"function"==typeof globalThis.performance.now,ta=class e{static create(t){return new e(t)}constructor(e){this._now=ea&&!1===e?Date.now:globalThis.performance.now.bind(globalThis.performance),this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=this._now(),this._stopTime=-1}elapsed(){return-1!==this._stopTime?this._stopTime-this._startTime:this._now()-this._startTime}};(e=>{function t(e){return(t,i=null,s)=>{let r,n=!1;return r=e(e=>{if(!n)return r?r.dispose():n=!0,t.call(i,e)},null,s),n&&r.dispose(),r}}function i(e,t,i){return r((i,s=null,r)=>e(e=>i.call(s,t(e)),null,r),i)}function s(e,t,i){return r((i,s=null,r)=>e(e=>t(e)&&i.call(s,e),null,r),i)}function r(e,t){let i,s=new da({onWillAddFirstListener(){i=e(s.fire,s)},onDidRemoveLastListener(){null==i||i.dispose()}});return null==t||t.add(s),s.event}function n(e,t,i=100,s=!1,r=!1,n,o){let a,l,c,h,d=0,u=new da({leakWarningThreshold:n,onWillAddFirstListener(){a=e(e=>{d++,l=t(l,e),s&&!c&&(u.fire(l),l=void 0),h=()=>{let e=l;l=void 0,c=void 0,(!s||d>1)&&u.fire(e),d=0},"number"==typeof i?(clearTimeout(c),c=setTimeout(h,i)):void 0===c&&(c=0,queueMicrotask(h))})},onWillRemoveListener(){r&&d>0&&(null==h||h())},onDidRemoveLastListener(){h=void 0,a.dispose()}});return null==o||o.add(u),u.event}e.None=()=>qo.None,e.defer=function(e,t){return n(e,()=>{},0,void 0,!0,void 0,t)},e.once=t,e.map=i,e.forEach=function(e,t,i){return r((i,s=null,r)=>e(e=>{t(e),i.call(s,e)},null,r),i)},e.filter=s,e.signal=function(e){return e},e.any=function(...e){return(t,i=null,s)=>function(e,t){return t instanceof Array?t.push(e):t&&t.add(e),e}(function(...e){return Ko(()=>Fo(e))}(...e.map(e=>e(e=>t.call(i,e)))),s)},e.reduce=function(e,t,s,r){let n=s;return i(e,e=>(n=t(n,e),n),r)},e.debounce=n,e.accumulate=function(t,i=0,s){return e.debounce(t,(e,t)=>e?(e.push(t),e):[t],i,void 0,!0,void 0,s)},e.latch=function(e,t=(e,t)=>e===t,i){let r,n=!0;return s(e,e=>{let i=n||!t(e,r);return n=!1,r=e,i},i)},e.split=function(t,i,s){return[e.filter(t,i,s),e.filter(t,e=>!i(e),s)]},e.buffer=function(e,t=!1,i=[],s){let r=i.slice(),n=e(e=>{r?r.push(e):a.fire(e)});s&&s.add(n);let o=()=>{null==r||r.forEach(e=>a.fire(e)),r=null},a=new da({onWillAddFirstListener(){n||(n=e(e=>a.fire(e)),s&&s.add(n))},onDidAddFirstListener(){r&&(t?setTimeout(o):o())},onDidRemoveLastListener(){n&&n.dispose(),n=null}});return s&&s.add(a),a.event},e.chain=function(e,t){return(i,s,r)=>{let n=t(new a);return e(function(e){let t=n.evaluate(e);t!==o&&i.call(s,t)},void 0,r)}};let o=Symbol("HaltChainable");class a{constructor(){this.steps=[]}map(e){return this.steps.push(e),this}forEach(e){return this.steps.push(t=>(e(t),t)),this}filter(e){return this.steps.push(t=>e(t)?t:o),this}reduce(e,t){let i=t;return this.steps.push(t=>(i=e(i,t),i)),this}latch(e=(e,t)=>e===t){let t,i=!0;return this.steps.push(s=>{let r=i||!e(s,t);return i=!1,t=s,r?s:o}),this}evaluate(e){for(let t of this.steps)if((e=t(e))===o)break;return e}}e.fromNodeEventEmitter=function(e,t,i=e=>e){let s=(...e)=>r.fire(i(...e)),r=new da({onWillAddFirstListener:()=>e.on(t,s),onDidRemoveLastListener:()=>e.removeListener(t,s)});return r.event},e.fromDOMEventEmitter=function(e,t,i=e=>e){let s=(...e)=>r.fire(i(...e)),r=new da({onWillAddFirstListener:()=>e.addEventListener(t,s),onDidRemoveLastListener:()=>e.removeEventListener(t,s)});return r.event},e.toPromise=function(e){return new Promise(i=>t(e)(i))},e.fromPromise=function(e){let t=new da;return e.then(e=>{t.fire(e)},()=>{t.fire(void 0)}).finally(()=>{t.dispose()}),t.event},e.forward=function(e,t){return e(e=>t.fire(e))},e.runAndSubscribe=function(e,t,i){return t(i),e(e=>t(e))};class l{constructor(e,t){this._observable=e,this._counter=0,this._hasChanged=!1;let i={onWillAddFirstListener:()=>{e.addObserver(this)},onDidRemoveLastListener:()=>{e.removeObserver(this)}};this.emitter=new da(i),t&&t.add(this.emitter)}beginUpdate(e){this._counter++}handlePossibleChange(e){}handleChange(e,t){this._hasChanged=!0}endUpdate(e){this._counter--,0===this._counter&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}e.fromObservable=function(e,t){return new l(e,t).emitter.event},e.fromObservableLight=function(e){return(t,i,s)=>{let r=0,n=!1,o={beginUpdate(){r++},endUpdate(){r--,0===r&&(e.reportChanges(),n&&(n=!1,t.call(i)))},handlePossibleChange(){},handleChange(){n=!0}};e.addObserver(o),e.reportChanges();let a={dispose(){e.removeObserver(o)}};return s instanceof Vo?s.add(a):Array.isArray(s)&&s.push(a),a}}})(Zo||(Zo={}));var ia=class e{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${e._idPool++}`,e.all.add(this)}start(e){this._stopWatch=new ta,this.listenerCount=e}stop(){if(this._stopWatch){let e=this._stopWatch.elapsed();this.durations.push(e),this.elapsedOverall+=e,this.invocationCount+=1,this._stopWatch=void 0}}};ia.all=new Set,ia._idPool=0;var sa=ia,ra=class e{constructor(t,i,s=(e._idPool++).toString(16).padStart(3,"0")){this._errorHandler=t,this.threshold=i,this.name=s,this._warnCountdown=0}dispose(){var e;null==(e=this._stacks)||e.clear()}check(e,t){let i=this.threshold;if(i<=0||t<i)return;this._stacks||(this._stacks=new Map);let s=this._stacks.get(e.value)||0;if(this._stacks.set(e.value,s+1),this._warnCountdown-=1,this._warnCountdown<=0){this._warnCountdown=.5*i;let[e,s]=this.getMostFrequentStack(),r=`[${this.name}] potential listener LEAK detected, having ${t} listeners already. MOST frequent listener (${s}):`;console.warn(r),console.warn(e);let n=new aa(r,e);this._errorHandler(n)}return()=>{let t=this._stacks.get(e.value)||0;this._stacks.set(e.value,t-1)}}getMostFrequentStack(){if(!this._stacks)return;let e,t=0;for(let[i,s]of this._stacks)(!e||t<s)&&(e=[i,s],t=s);return e}};ra._idPool=1;var na=ra,oa=class e{constructor(e){this.value=e}static create(){let t=new Error;return new e(t.stack??"")}print(){console.warn(this.value.split("\n").slice(2).join("\n"))}},aa=class extends Error{constructor(e,t){super(e),this.name="ListenerLeakError",this.stack=t}},la=class extends Error{constructor(e,t){super(e),this.name="ListenerRefusalError",this.stack=t}},ca=0,ha=class{constructor(e){this.value=e,this.id=ca++}},da=class{constructor(e){var t,i,s,r;this._size=0,this._options=e,this._leakageMon=(null==(t=this._options)?void 0:t.leakWarningThreshold)?new na((null==e?void 0:e.onListenerError)??Lo,(null==(i=this._options)?void 0:i.leakWarningThreshold)??-1):void 0,this._perfMon=(null==(s=this._options)?void 0:s._profName)?new sa(this._options._profName):void 0,this._deliveryQueue=null==(r=this._options)?void 0:r.deliveryQueue}dispose(){var e,t,i,s;this._disposed||(this._disposed=!0,(null==(e=this._deliveryQueue)?void 0:e.current)===this&&this._deliveryQueue.reset(),this._listeners&&(this._listeners=void 0,this._size=0),null==(i=null==(t=this._options)?void 0:t.onDidRemoveLastListener)||i.call(t),null==(s=this._leakageMon)||s.dispose())}get event(){return this._event??(this._event=(e,t,i)=>{var s,r,n,o,a;if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let e=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(e);let t=this._leakageMon.getMostFrequentStack()??["UNKNOWN stack",-1],i=new la(`${e}. HINT: Stack shows most frequent listener (${t[1]}-times)`,t[0]);return((null==(s=this._options)?void 0:s.onListenerError)||Lo)(i),qo.None}if(this._disposed)return qo.None;t&&(e=e.bind(t));let l,c=new ha(e);this._leakageMon&&this._size>=Math.ceil(.2*this._leakageMon.threshold)&&(c.stack=oa.create(),l=this._leakageMon.check(c.stack,this._size+1)),this._listeners?this._listeners instanceof ha?(this._deliveryQueue??(this._deliveryQueue=new ua),this._listeners=[this._listeners,c]):this._listeners.push(c):(null==(n=null==(r=this._options)?void 0:r.onWillAddFirstListener)||n.call(r,this),this._listeners=c,null==(a=null==(o=this._options)?void 0:o.onDidAddFirstListener)||a.call(o,this)),this._size++;let h=Ko(()=>{null==l||l(),this._removeListener(c)});return i instanceof Vo?i.add(h):Array.isArray(i)&&i.push(h),h}),this._event}_removeListener(e){var t,i,s,r;if(null==(i=null==(t=this._options)?void 0:t.onWillRemoveListener)||i.call(t,this),!this._listeners)return;if(1===this._size)return this._listeners=void 0,null==(r=null==(s=this._options)?void 0:s.onDidRemoveLastListener)||r.call(s,this),void(this._size=0);let n=this._listeners,o=n.indexOf(e);if(-1===o)throw console.log("disposed?",this._disposed),console.log("size?",this._size),console.log("arr?",JSON.stringify(this._listeners)),new Error("Attempted to dispose unknown listener");this._size--,n[o]=void 0;let a=this._deliveryQueue.current===this;if(2*this._size<=n.length){let e=0;for(let t=0;t<n.length;t++)n[t]?n[e++]=n[t]:a&&(this._deliveryQueue.end--,e<this._deliveryQueue.i&&this._deliveryQueue.i--);n.length=e}}_deliver(e,t){var i;if(!e)return;let s=(null==(i=this._options)?void 0:i.onListenerError)||Lo;if(s)try{e.value(t)}catch(r){s(r)}else e.value(t)}_deliverQueue(e){let t=e.current._listeners;for(;e.i<e.end;)this._deliver(t[e.i++],e.value);e.reset()}fire(e){var t,i,s,r;if((null==(t=this._deliveryQueue)?void 0:t.current)&&(this._deliverQueue(this._deliveryQueue),null==(i=this._perfMon)||i.stop()),null==(s=this._perfMon)||s.start(this._size),this._listeners)if(this._listeners instanceof ha)this._deliver(this._listeners,e);else{let t=this._deliveryQueue;t.enqueue(this,e,this._listeners.length),this._deliverQueue(t)}null==(r=this._perfMon)||r.stop()}hasListeners(){return this._size>0}},ua=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,i){this.i=0,this.end=i,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},fa=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new da,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new da,this.onDidChangeFullscreen=this._onDidChangeFullscreen.event,this.mapWindowIdToFullScreen=new Map}getZoomLevel(e){return this.mapWindowIdToZoomLevel.get(this.getWindowId(e))??0}setZoomLevel(e,t){if(this.getZoomLevel(t)===e)return;let i=this.getWindowId(t);this.mapWindowIdToZoomLevel.set(i,e),this._onDidChangeZoomLevel.fire(i)}getZoomFactor(e){return this.mapWindowIdToZoomFactor.get(this.getWindowId(e))??1}setZoomFactor(e,t){this.mapWindowIdToZoomFactor.set(this.getWindowId(t),e)}setFullscreen(e,t){if(this.isFullscreen(t)===e)return;let i=this.getWindowId(t);this.mapWindowIdToFullScreen.set(i,e),this._onDidChangeFullscreen.fire(i)}isFullscreen(e){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(e))}getWindowId(e){return e.vscodeWindowId}};fa.INSTANCE=new fa;var pa=fa;pa.INSTANCE.onDidChangeZoomLevel,pa.INSTANCE.onDidChangeFullscreen;var ma="object"==typeof navigator?navigator.userAgent:"",_a=ma.indexOf("Firefox")>=0,ga=ma.indexOf("AppleWebKit")>=0,va=ma.indexOf("Chrome")>=0,ya=!va&&ma.indexOf("Safari")>=0;ma.indexOf("Electron/"),ma.indexOf("Android");var xa=!1;if("function"==typeof Xo.matchMedia){let e=Xo.matchMedia("(display-mode: standalone) or (display-mode: window-controls-overlay)"),t=Xo.matchMedia("(display-mode: fullscreen)");xa=e.matches,function(e,t,i){"string"==typeof t&&(t=e.matchMedia(t)),t.addEventListener("change",i)}(Xo,e,({matches:e})=>{xa&&t.matches||(xa=e)})}var ba,wa,Sa="en",Ca=!1,ka=!1,Ea=!1,Na=!1,Ma=Sa,ja=globalThis;typeof ja.vscode<"u"&&typeof ja.vscode.process<"u"?wa=ja.vscode.process:typeof process<"u"&&"string"==typeof(null==(e=null==process?void 0:process.versions)?void 0:e.node)&&(wa=process);var Da="string"==typeof(null==(t=null==wa?void 0:wa.versions)?void 0:t.electron)&&"renderer"===(null==wa?void 0:wa.type);if("object"==typeof wa){Ca="win32"===wa.platform,ka="darwin"===wa.platform,(Ea="linux"===wa.platform)&&!!wa.env.SNAP&&wa.env.SNAP_REVISION,!!wa.env.CI||wa.env.BUILD_ARTIFACTSTAGINGDIRECTORY,Ma=Sa;let e=wa.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);t.userLocale,t.osLocale,Ma=t.resolvedLanguage||Sa,null==(i=t.languagePack)?void 0:i.translationsConfigFile}catch{}Na=!0}else"object"!=typeof navigator||Da?console.error("Unable to resolve platform."):(Ca=(ba=navigator.userAgent).indexOf("Windows")>=0,ka=ba.indexOf("Macintosh")>=0,(ba.indexOf("Macintosh")>=0||ba.indexOf("iPad")>=0||ba.indexOf("iPhone")>=0)&&!!navigator.maxTouchPoints&&navigator.maxTouchPoints,Ea=ba.indexOf("Linux")>=0,null==ba||ba.indexOf("Mobi"),Ma=globalThis._VSCODE_NLS_LANGUAGE||Sa,navigator.language.toLowerCase());var Ra,Pa,La=Ca,Ta=ka,Ia=Ea,Ba=Na,Oa=ba,Aa=Ma;(Pa=Ra||(Ra={})).value=function(){return Aa},Pa.isDefaultVariant=function(){return 2===Aa.length?"en"===Aa:Aa.length>=3&&"e"===Aa[0]&&"n"===Aa[1]&&"-"===Aa[2]},Pa.isDefault=function(){return"en"===Aa};var za="function"==typeof ja.postMessage&&!ja.importScripts;(()=>{if(za){let e=[];ja.addEventListener("message",t=>{if(t.data&&t.data.vscodeScheduleAsyncWork)for(let i=0,s=e.length;i<s;i++){let s=e[i];if(s.id===t.data.vscodeScheduleAsyncWork)return e.splice(i,1),void s.callback()}});let t=0;return i=>{let s=++t;e.push({id:s,callback:i}),ja.postMessage({vscodeScheduleAsyncWork:s},"*")}}})();var $a=!!(Oa&&Oa.indexOf("Chrome")>=0);Oa&&Oa.indexOf("Firefox"),!$a&&Oa&&Oa.indexOf("Safari"),Oa&&Oa.indexOf("Edg/"),Oa&&Oa.indexOf("Android");var Ha="object"==typeof navigator?navigator:{};Ba||document.queryCommandSupported&&document.queryCommandSupported("copy")||Ha&&Ha.clipboard&&Ha.clipboard.writeText,Ba||Ha&&Ha.clipboard&&Ha.clipboard.readText;var Wa,Fa,Ka=class{constructor(){this._keyCodeToStr=[],this._strToKeyCode=Object.create(null)}define(e,t){this._keyCodeToStr[e]=t,this._strToKeyCode[t.toLowerCase()]=e}keyCodeToStr(e){return this._keyCodeToStr[e]}strToKeyCode(e){return this._strToKeyCode[e.toLowerCase()]||0}},Ua=new Ka,Va=new Ka,qa=new Ka,Ya=new Array(230);(Fa=Wa||(Wa={})).toString=function(e){return Ua.keyCodeToStr(e)},Fa.fromString=function(e){return Ua.strToKeyCode(e)},Fa.toUserSettingsUS=function(e){return Va.keyCodeToStr(e)},Fa.toUserSettingsGeneral=function(e){return qa.keyCodeToStr(e)},Fa.fromUserSettings=function(e){return Va.strToKeyCode(e)||qa.strToKeyCode(e)},Fa.toElectronAccelerator=function(e){if(e>=98&&e<=113)return null;switch(e){case 16:return"Up";case 18:return"Down";case 15:return"Left";case 17:return"Right"}return Ua.keyCodeToStr(e)};var Xa=class e{constructor(e,t,i,s,r){this.ctrlKey=e,this.shiftKey=t,this.altKey=i,this.metaKey=s,this.keyCode=r}equals(t){return t instanceof e&&this.ctrlKey===t.ctrlKey&&this.shiftKey===t.shiftKey&&this.altKey===t.altKey&&this.metaKey===t.metaKey&&this.keyCode===t.keyCode}getHashCode(){return`K${this.ctrlKey?"1":"0"}${this.shiftKey?"1":"0"}${this.altKey?"1":"0"}${this.metaKey?"1":"0"}${this.keyCode}`}isModifierKey(){return 0===this.keyCode||5===this.keyCode||57===this.keyCode||6===this.keyCode||4===this.keyCode}toKeybinding(){return new Ga([this])}isDuplicateModifierCase(){return this.ctrlKey&&5===this.keyCode||this.shiftKey&&4===this.keyCode||this.altKey&&6===this.keyCode||this.metaKey&&57===this.keyCode}},Ga=class{constructor(e){if(0===e.length)throw new Error(`Illegal argument: ${"chords"}`);this.chords=e}getHashCode(){let e="";for(let t=0,i=this.chords.length;t<i;t++)0!==t&&(e+=";"),e+=this.chords[t].getHashCode();return e}equals(e){if(null===e||this.chords.length!==e.chords.length)return!1;for(let t=0;t<this.chords.length;t++)if(!this.chords[t].equals(e.chords[t]))return!1;return!0}};var Za=Ta?256:2048,Ja=Ta?2048:256,Qa=class{constructor(e){var t;this._standardKeyboardEventBrand=!0;let i=e;this.browserEvent=i,this.target=i.target,this.ctrlKey=i.ctrlKey,this.shiftKey=i.shiftKey,this.altKey=i.altKey,this.metaKey=i.metaKey,this.altGraphKey=null==(t=i.getModifierState)?void 0:t.call(i,"AltGraph"),this.keyCode=function(e){if(e.charCode){let t=String.fromCharCode(e.charCode).toUpperCase();return Wa.fromString(t)}let t=e.keyCode;if(3===t)return 7;if(_a)switch(t){case 59:return 85;case 60:if(Ia)return 97;break;case 61:return 86;case 107:return 109;case 109:return 111;case 173:return 88;case 224:if(Ta)return 57}else if(ga){if(Ta&&93===t)return 57;if(!Ta&&92===t)return 57}return Ya[t]||0}(i),this.code=i.code,this.ctrlKey=this.ctrlKey||5===this.keyCode,this.altKey=this.altKey||6===this.keyCode,this.shiftKey=this.shiftKey||4===this.keyCode,this.metaKey=this.metaKey||57===this.keyCode,this._asKeybinding=this._computeKeybinding(),this._asKeyCodeChord=this._computeKeyCodeChord()}preventDefault(){this.browserEvent&&this.browserEvent.preventDefault&&this.browserEvent.preventDefault()}stopPropagation(){this.browserEvent&&this.browserEvent.stopPropagation&&this.browserEvent.stopPropagation()}toKeyCodeChord(){return this._asKeyCodeChord}equals(e){return this._asKeybinding===e}_computeKeybinding(){let e=0;5!==this.keyCode&&4!==this.keyCode&&6!==this.keyCode&&57!==this.keyCode&&(e=this.keyCode);let t=0;return this.ctrlKey&&(t|=Za),this.altKey&&(t|=512),this.shiftKey&&(t|=1024),this.metaKey&&(t|=Ja),t|=e,t}_computeKeyCodeChord(){let e=0;return 5!==this.keyCode&&4!==this.keyCode&&6!==this.keyCode&&57!==this.keyCode&&(e=this.keyCode),new Xa(this.ctrlKey,this.shiftKey,this.altKey,this.metaKey,e)}},el=new WeakMap;function tl(e){if(!e.parent||e.parent===e)return null;try{let t=e.location,i=e.parent.location;if("null"!==t.origin&&"null"!==i.origin&&t.origin!==i.origin)return null}catch{return null}return e.parent}var il,sl=class{static getSameOriginWindowChain(e){let t=el.get(e);if(!t){t=[],el.set(e,t);let i,s=e;do{i=tl(s),i?t.push({window:new WeakRef(s),iframeElement:s.frameElement||null}):t.push({window:new WeakRef(s),iframeElement:null}),s=i}while(s)}return t.slice(0)}static getPositionOfChildWindowRelativeToAncestorWindow(e,t){if(!t||e===t)return{top:0,left:0};let i=0,s=0,r=this.getSameOriginWindowChain(e);for(let n of r){let e=n.window.deref();if(i+=(null==e?void 0:e.scrollY)??0,s+=(null==e?void 0:e.scrollX)??0,e===t||!n.iframeElement)break;let r=n.iframeElement.getBoundingClientRect();i+=r.top,s+=r.left}return{top:i,left:s}}},rl=class{constructor(e,t){this.timestamp=Date.now(),this.browserEvent=t,this.leftButton=0===t.button,this.middleButton=1===t.button,this.rightButton=2===t.button,this.buttons=t.buttons,this.target=t.target,this.detail=t.detail||1,"dblclick"===t.type&&(this.detail=2),this.ctrlKey=t.ctrlKey,this.shiftKey=t.shiftKey,this.altKey=t.altKey,this.metaKey=t.metaKey,"number"==typeof t.pageX?(this.posx=t.pageX,this.posy=t.pageY):(this.posx=t.clientX+this.target.ownerDocument.body.scrollLeft+this.target.ownerDocument.documentElement.scrollLeft,this.posy=t.clientY+this.target.ownerDocument.body.scrollTop+this.target.ownerDocument.documentElement.scrollTop);let i=sl.getPositionOfChildWindowRelativeToAncestorWindow(e,t.view);this.posx-=i.left,this.posy-=i.top}preventDefault(){this.browserEvent.preventDefault()}stopPropagation(){this.browserEvent.stopPropagation()}},nl=class{constructor(e,t=0,i=0){var s;this.browserEvent=e||null,this.target=e?e.target||e.targetNode||e.srcElement:null,this.deltaY=i,this.deltaX=t;let r=!1;if(va){let e=navigator.userAgent.match(/Chrome\/(\d+)/);r=(e?parseInt(e[1]):123)<=122}if(e){let t=e,i=e,n=(null==(s=e.view)?void 0:s.devicePixelRatio)||1;if(typeof t.wheelDeltaY<"u")this.deltaY=r?t.wheelDeltaY/(120*n):t.wheelDeltaY/120;else if(typeof i.VERTICAL_AXIS<"u"&&i.axis===i.VERTICAL_AXIS)this.deltaY=-i.detail/3;else if("wheel"===e.type){let t=e;t.deltaMode===t.DOM_DELTA_LINE?this.deltaY=_a&&!Ta?-e.deltaY/3:-e.deltaY:this.deltaY=-e.deltaY/40}if(typeof t.wheelDeltaX<"u")this.deltaX=ya&&La?-t.wheelDeltaX/120:r?t.wheelDeltaX/(120*n):t.wheelDeltaX/120;else if(typeof i.HORIZONTAL_AXIS<"u"&&i.axis===i.HORIZONTAL_AXIS)this.deltaX=-e.detail/3;else if("wheel"===e.type){let t=e;t.deltaMode===t.DOM_DELTA_LINE?this.deltaX=_a&&!Ta?-e.deltaX/3:-e.deltaX:this.deltaX=-e.deltaX/40}0===this.deltaY&&0===this.deltaX&&e.wheelDelta&&(this.deltaY=r?e.wheelDelta/(120*n):e.wheelDelta/120)}}preventDefault(){var e;null==(e=this.browserEvent)||e.preventDefault()}stopPropagation(){var e;null==(e=this.browserEvent)||e.stopPropagation()}},ol=Object.freeze(function(e,t){let i=setTimeout(e.bind(t),0);return{dispose(){clearTimeout(i)}}});(e=>{e.isCancellationToken=function(t){return t===e.None||t===e.Cancelled||t instanceof cl||!(!t||"object"!=typeof t)&&("boolean"==typeof t.isCancellationRequested&&"function"==typeof t.onCancellationRequested)},e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:Zo.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:ol})})(il||(il={}));var al,ll,cl=class{constructor(){this._isCancelled=!1,this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?ol:(this._emitter||(this._emitter=new da),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}},hl=class{constructor(e,t){this._isDisposed=!1,this._token=-1,"function"==typeof e&&"number"==typeof t&&this.setIfNotSet(e,t)}dispose(){this.cancel(),this._isDisposed=!0}cancel(){-1!==this._token&&(clearTimeout(this._token),this._token=-1)}cancelAndSet(e,t){if(this._isDisposed)throw new $o("Calling 'cancelAndSet' on a disposed TimeoutTimer");this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){if(this._isDisposed)throw new $o("Calling 'setIfNotSet' on a disposed TimeoutTimer");-1===this._token&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}},dl=class{constructor(){this.disposable=void 0,this.isDisposed=!1}cancel(){var e;null==(e=this.disposable)||e.dispose(),this.disposable=void 0}cancelAndSet(e,t,i=globalThis){if(this.isDisposed)throw new $o("Calling 'cancelAndSet' on a disposed IntervalTimer");this.cancel();let s=i.setInterval(()=>{e()},t);this.disposable=Ko(()=>{i.clearInterval(s),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}};(ll=al||(al={})).settled=async function(e){let t,i=await Promise.all(e.map(e=>e.then(e=>e,e=>{t||(t=e)})));if(typeof t<"u")throw t;return i},ll.withAsyncBody=function(e){return new Promise(async(t,i)=>{try{await e(t,i)}catch(Fa){i(Fa)}})};var ul=class e{static fromArray(t){return new e(e=>{e.emitMany(t)})}static fromPromise(t){return new e(async e=>{e.emitMany(await t)})}static fromPromises(t){return new e(async e=>{await Promise.all(t.map(async t=>e.emitOne(await t)))})}static merge(t){return new e(async e=>{await Promise.all(t.map(async t=>{for await(let i of t)e.emitOne(i)}))})}constructor(e,t){this._state=0,this._results=[],this._error=null,this._onReturn=t,this._onStateChanged=new da,queueMicrotask(async()=>{let t={emitOne:e=>this.emitOne(e),emitMany:e=>this.emitMany(e),reject:e=>this.reject(e)};try{await Promise.resolve(e(t)),this.resolve()}catch(i){this.reject(i)}finally{t.emitOne=void 0,t.emitMany=void 0,t.reject=void 0}})}[Symbol.asyncIterator](){let e=0;return{next:async()=>{for(;;){if(2===this._state)throw this._error;if(e<this._results.length)return{done:!1,value:this._results[e++]};if(1===this._state)return{done:!0,value:void 0};await Zo.toPromise(this._onStateChanged.event)}},return:async()=>{var e;return null==(e=this._onReturn)||e.call(this),{done:!0,value:void 0}}}}static map(t,i){return new e(async e=>{for await(let s of t)e.emitOne(i(s))})}map(t){return e.map(this,t)}static filter(t,i){return new e(async e=>{for await(let s of t)i(s)&&e.emitOne(s)})}filter(t){return e.filter(this,t)}static coalesce(t){return e.filter(t,e=>!!e)}coalesce(){return e.coalesce(this)}static async toPromise(e){let t=[];for await(let i of e)t.push(i);return t}toPromise(){return e.toPromise(this)}emitOne(e){0===this._state&&(this._results.push(e),this._onStateChanged.fire())}emitMany(e){0===this._state&&(this._results=this._results.concat(e),this._onStateChanged.fire())}resolve(){0===this._state&&(this._state=1,this._onStateChanged.fire())}reject(e){0===this._state&&(this._state=2,this._error=e,this._onStateChanged.fire())}};ul.EMPTY=ul.fromArray([]);var{getWindow:fl,getWindowId:pl,onDidRegisterWindow:ml}=function(){let e=new Map,t={window:Xo,disposables:new Vo};e.set(Xo.vscodeWindowId,t);let i=new da,s=new da,r=new da;return{onDidRegisterWindow:i.event,onWillUnregisterWindow:r.event,onDidUnregisterWindow:s.event,registerWindow(t){if(e.has(t.vscodeWindowId))return qo.None;let n=new Vo,o={window:t,disposables:n.add(new Vo)};return e.set(t.vscodeWindowId,o),n.add(Ko(()=>{e.delete(t.vscodeWindowId),s.fire(t)})),n.add(gl(t,wl.BEFORE_UNLOAD,()=>{r.fire(t)})),i.fire(o),n},getWindows:()=>e.values(),getWindowsCount:()=>e.size,getWindowId:e=>e.vscodeWindowId,hasWindow:t=>e.has(t),getWindowById:function(i,s){return("number"==typeof i?e.get(i):void 0)??(s?t:void 0)},getWindow(e){var t;let i=e;if(null==(t=null==i?void 0:i.ownerDocument)?void 0:t.defaultView)return i.ownerDocument.defaultView.window;let s=e;return(null==s?void 0:s.view)?s.view.window:Xo},getDocument:e=>fl(e).document}}(),_l=class{constructor(e,t,i,s){this._node=e,this._type=t,this._handler=i,this._options=s||!1,this._node.addEventListener(this._type,this._handler,this._options)}dispose(){this._handler&&(this._node.removeEventListener(this._type,this._handler,this._options),this._node=null,this._handler=null)}};function gl(e,t,i,s){return new _l(e,t,i,s)}var vl,yl=function(e,t,i,s){return gl(e,t,i,s)},xl=class extends dl{constructor(e){super(),this.defaultTarget=e&&fl(e)}cancelAndSet(e,t,i){return super.cancelAndSet(e,t,i??this.defaultTarget)}},bl=class{constructor(e,t=0){this._runner=e,this.priority=t,this._canceled=!1}dispose(){this._canceled=!0}execute(){if(!this._canceled)try{this._runner()}catch(Qu){Lo(Qu)}}static sort(e,t){return t.priority-e.priority}};!function(){let e=new Map,t=new Map,i=new Map,s=new Map;vl=(r,n,o=0)=>{let a=pl(r),l=new bl(n,o),c=e.get(a);return c||(c=[],e.set(a,c)),c.push(l),i.get(a)||(i.set(a,!0),r.requestAnimationFrame(()=>(r=>{i.set(r,!1);let n=e.get(r)??[];for(t.set(r,n),e.set(r,[]),s.set(r,!0);n.length>0;)n.sort(bl.sort),n.shift().execute();s.set(r,!1)})(a))),l}}();var wl={CLICK:"click",MOUSE_DOWN:"mousedown",MOUSE_OVER:"mouseover",MOUSE_LEAVE:"mouseleave",MOUSE_WHEEL:"wheel",POINTER_UP:"pointerup",POINTER_DOWN:"pointerdown",POINTER_MOVE:"pointermove",KEY_DOWN:"keydown",KEY_UP:"keyup",BEFORE_UNLOAD:"beforeunload",CHANGE:"change",FOCUS:"focus",BLUR:"blur",INPUT:"input"},Sl=class{constructor(e){this.domNode=e,this._maxWidth="",this._width="",this._height="",this._top="",this._left="",this._bottom="",this._right="",this._paddingTop="",this._paddingLeft="",this._paddingBottom="",this._paddingRight="",this._fontFamily="",this._fontWeight="",this._fontSize="",this._fontStyle="",this._fontFeatureSettings="",this._fontVariationSettings="",this._textDecoration="",this._lineHeight="",this._letterSpacing="",this._className="",this._display="",this._position="",this._visibility="",this._color="",this._backgroundColor="",this._layerHint=!1,this._contain="none",this._boxShadow=""}setMaxWidth(e){let t=Cl(e);this._maxWidth!==t&&(this._maxWidth=t,this.domNode.style.maxWidth=this._maxWidth)}setWidth(e){let t=Cl(e);this._width!==t&&(this._width=t,this.domNode.style.width=this._width)}setHeight(e){let t=Cl(e);this._height!==t&&(this._height=t,this.domNode.style.height=this._height)}setTop(e){let t=Cl(e);this._top!==t&&(this._top=t,this.domNode.style.top=this._top)}setLeft(e){let t=Cl(e);this._left!==t&&(this._left=t,this.domNode.style.left=this._left)}setBottom(e){let t=Cl(e);this._bottom!==t&&(this._bottom=t,this.domNode.style.bottom=this._bottom)}setRight(e){let t=Cl(e);this._right!==t&&(this._right=t,this.domNode.style.right=this._right)}setPaddingTop(e){let t=Cl(e);this._paddingTop!==t&&(this._paddingTop=t,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(e){let t=Cl(e);this._paddingLeft!==t&&(this._paddingLeft=t,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(e){let t=Cl(e);this._paddingBottom!==t&&(this._paddingBottom=t,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(e){let t=Cl(e);this._paddingRight!==t&&(this._paddingRight=t,this.domNode.style.paddingRight=this._paddingRight)}setFontFamily(e){this._fontFamily!==e&&(this._fontFamily=e,this.domNode.style.fontFamily=this._fontFamily)}setFontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this.domNode.style.fontWeight=this._fontWeight)}setFontSize(e){let t=Cl(e);this._fontSize!==t&&(this._fontSize=t,this.domNode.style.fontSize=this._fontSize)}setFontStyle(e){this._fontStyle!==e&&(this._fontStyle=e,this.domNode.style.fontStyle=this._fontStyle)}setFontFeatureSettings(e){this._fontFeatureSettings!==e&&(this._fontFeatureSettings=e,this.domNode.style.fontFeatureSettings=this._fontFeatureSettings)}setFontVariationSettings(e){this._fontVariationSettings!==e&&(this._fontVariationSettings=e,this.domNode.style.fontVariationSettings=this._fontVariationSettings)}setTextDecoration(e){this._textDecoration!==e&&(this._textDecoration=e,this.domNode.style.textDecoration=this._textDecoration)}setLineHeight(e){let t=Cl(e);this._lineHeight!==t&&(this._lineHeight=t,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(e){let t=Cl(e);this._letterSpacing!==t&&(this._letterSpacing=t,this.domNode.style.letterSpacing=this._letterSpacing)}setClassName(e){this._className!==e&&(this._className=e,this.domNode.className=this._className)}toggleClassName(e,t){this.domNode.classList.toggle(e,t),this._className=this.domNode.className}setDisplay(e){this._display!==e&&(this._display=e,this.domNode.style.display=this._display)}setPosition(e){this._position!==e&&(this._position=e,this.domNode.style.position=this._position)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this.domNode.style.visibility=this._visibility)}setColor(e){this._color!==e&&(this._color=e,this.domNode.style.color=this._color)}setBackgroundColor(e){this._backgroundColor!==e&&(this._backgroundColor=e,this.domNode.style.backgroundColor=this._backgroundColor)}setLayerHinting(e){this._layerHint!==e&&(this._layerHint=e,this.domNode.style.transform=this._layerHint?"translate3d(0px, 0px, 0px)":"")}setBoxShadow(e){this._boxShadow!==e&&(this._boxShadow=e,this.domNode.style.boxShadow=e)}setContain(e){this._contain!==e&&(this._contain=e,this.domNode.style.contain=this._contain)}setAttribute(e,t){this.domNode.setAttribute(e,t)}removeAttribute(e){this.domNode.removeAttribute(e)}appendChild(e){this.domNode.appendChild(e.domNode)}removeChild(e){this.domNode.removeChild(e.domNode)}};function Cl(e){return"number"==typeof e?`${e}px`:e}function kl(e){return new Sl(e)}var El,Nl,Ml=class{constructor(){this._hooks=new Vo,this._pointerMoveCallback=null,this._onStopCallback=null}dispose(){this.stopMonitoring(!1),this._hooks.dispose()}stopMonitoring(e,t){if(!this.isMonitoring())return;this._hooks.clear(),this._pointerMoveCallback=null;let i=this._onStopCallback;this._onStopCallback=null,e&&i&&i(t)}isMonitoring(){return!!this._pointerMoveCallback}startMonitoring(e,t,i,s,r){this.isMonitoring()&&this.stopMonitoring(!1),this._pointerMoveCallback=s,this._onStopCallback=r;let n=e;try{e.setPointerCapture(t),this._hooks.add(Ko(()=>{try{e.releasePointerCapture(t)}catch{}}))}catch{n=fl(e)}this._hooks.add(gl(n,wl.POINTER_MOVE,e=>{e.buttons===i?(e.preventDefault(),this._pointerMoveCallback(e)):this.stopMonitoring(!0)})),this._hooks.add(gl(n,wl.POINTER_UP,e=>this.stopMonitoring(!0)))}};(Nl=El||(El={})).Tap="-xterm-gesturetap",Nl.Change="-xterm-gesturechange",Nl.Start="-xterm-gesturestart",Nl.End="-xterm-gesturesend",Nl.Contextmenu="-xterm-gesturecontextmenu";var jl=class e extends qo{constructor(){super(),this.dispatched=!1,this.targets=new Qo,this.ignoreTargets=new Qo,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(Zo.runAndSubscribe(ml,({window:e,disposables:t})=>{t.add(gl(e.document,"touchstart",e=>this.onTouchStart(e),{passive:!1})),t.add(gl(e.document,"touchend",t=>this.onTouchEnd(e,t))),t.add(gl(e.document,"touchmove",e=>this.onTouchMove(e),{passive:!1}))},{window:Xo,disposables:this._store}))}static addTarget(t){if(!e.isTouchDevice())return qo.None;return e.INSTANCE||(e.INSTANCE=new e),Ko(e.INSTANCE.targets.push(t))}static ignoreTarget(t){if(!e.isTouchDevice())return qo.None;return e.INSTANCE||(e.INSTANCE=new e),Ko(e.INSTANCE.ignoreTargets.push(t))}static isTouchDevice(){return"ontouchstart"in Xo||navigator.maxTouchPoints>0}dispose(){this.handle&&(this.handle.dispose(),this.handle=null),super.dispose()}onTouchStart(e){let t=Date.now();this.handle&&(this.handle.dispose(),this.handle=null);for(let i=0,s=e.targetTouches.length;i<s;i++){let s=e.targetTouches.item(i);this.activeTouches[s.identifier]={id:s.identifier,initialTarget:s.target,initialTimeStamp:t,initialPageX:s.pageX,initialPageY:s.pageY,rollingTimestamps:[t],rollingPageX:[s.pageX],rollingPageY:[s.pageY]};let r=this.newGestureEvent(El.Start,s.target);r.pageX=s.pageX,r.pageY=s.pageY,this.dispatchEvent(r)}this.dispatched&&(e.preventDefault(),e.stopPropagation(),this.dispatched=!1)}onTouchEnd(t,i){let s=Date.now(),r=Object.keys(this.activeTouches).length;for(let n=0,o=i.changedTouches.length;n<o;n++){let o=i.changedTouches.item(n);if(!this.activeTouches.hasOwnProperty(String(o.identifier))){console.warn("move of an UNKNOWN touch",o);continue}let a=this.activeTouches[o.identifier],l=Date.now()-a.initialTimeStamp;if(l<e.HOLD_DELAY&&Math.abs(a.initialPageX-Ho(a.rollingPageX))<30&&Math.abs(a.initialPageY-Ho(a.rollingPageY))<30){let e=this.newGestureEvent(El.Tap,a.initialTarget);e.pageX=Ho(a.rollingPageX),e.pageY=Ho(a.rollingPageY),this.dispatchEvent(e)}else if(l>=e.HOLD_DELAY&&Math.abs(a.initialPageX-Ho(a.rollingPageX))<30&&Math.abs(a.initialPageY-Ho(a.rollingPageY))<30){let e=this.newGestureEvent(El.Contextmenu,a.initialTarget);e.pageX=Ho(a.rollingPageX),e.pageY=Ho(a.rollingPageY),this.dispatchEvent(e)}else if(1===r){let e=Ho(a.rollingPageX),i=Ho(a.rollingPageY),r=Ho(a.rollingTimestamps)-a.rollingTimestamps[0],n=e-a.rollingPageX[0],o=i-a.rollingPageY[0],l=[...this.targets].filter(e=>a.initialTarget instanceof Node&&e.contains(a.initialTarget));this.inertia(t,l,s,Math.abs(n)/r,n>0?1:-1,e,Math.abs(o)/r,o>0?1:-1,i)}this.dispatchEvent(this.newGestureEvent(El.End,a.initialTarget)),delete this.activeTouches[o.identifier]}this.dispatched&&(i.preventDefault(),i.stopPropagation(),this.dispatched=!1)}newGestureEvent(e,t){let i=document.createEvent("CustomEvent");return i.initEvent(e,!1,!0),i.initialTarget=t,i.tapCount=0,i}dispatchEvent(t){if(t.type===El.Tap){let i=(new Date).getTime(),s=0;s=i-this._lastSetTapCountTime>e.CLEAR_TAP_COUNT_TIME?1:2,this._lastSetTapCountTime=i,t.tapCount=s}else(t.type===El.Change||t.type===El.Contextmenu)&&(this._lastSetTapCountTime=0);if(t.initialTarget instanceof Node){for(let i of this.ignoreTargets)if(i.contains(t.initialTarget))return;let e=[];for(let i of this.targets)if(i.contains(t.initialTarget)){let s=0,r=t.initialTarget;for(;r&&r!==i;)s++,r=r.parentElement;e.push([s,i])}e.sort((e,t)=>e[0]-t[0]);for(let[i,s]of e)s.dispatchEvent(t),this.dispatched=!0}}inertia(t,i,s,r,n,o,a,l,c){this.handle=vl(t,()=>{let h=Date.now(),d=h-s,u=0,f=0,p=!0;r+=e.SCROLL_FRICTION*d,a+=e.SCROLL_FRICTION*d,r>0&&(p=!1,u=n*r*d),a>0&&(p=!1,f=l*a*d);let m=this.newGestureEvent(El.Change);m.translationX=u,m.translationY=f,i.forEach(e=>e.dispatchEvent(m)),p||this.inertia(t,i,h,r,n,o+u,a,l,c+f)})}onTouchMove(e){let t=Date.now();for(let i=0,s=e.changedTouches.length;i<s;i++){let s=e.changedTouches.item(i);if(!this.activeTouches.hasOwnProperty(String(s.identifier))){console.warn("end of an UNKNOWN touch",s);continue}let r=this.activeTouches[s.identifier],n=this.newGestureEvent(El.Change,r.initialTarget);n.translationX=s.pageX-Ho(r.rollingPageX),n.translationY=s.pageY-Ho(r.rollingPageY),n.pageX=s.pageX,n.pageY=s.pageY,this.dispatchEvent(n),r.rollingPageX.length>3&&(r.rollingPageX.shift(),r.rollingPageY.shift(),r.rollingTimestamps.shift()),r.rollingPageX.push(s.pageX),r.rollingPageY.push(s.pageY),r.rollingTimestamps.push(t)}this.dispatched&&(e.preventDefault(),e.stopPropagation(),this.dispatched=!1)}};jl.SCROLL_FRICTION=-.005,jl.HOLD_DELAY=700,jl.CLEAR_TAP_COUNT_TIME=400,Wn([function(e,t,i){let s=null,r=null;if("function"==typeof i.value?(s="value",r=i.value,0!==r.length&&console.warn("Memoize should only be used in functions with zero parameters")):"function"==typeof i.get&&(s="get",r=i.get),!r)throw new Error("not supported");let n=`$memoize$${t}`;i[s]=function(...e){return this.hasOwnProperty(n)||Object.defineProperty(this,n,{configurable:!1,enumerable:!1,writable:!1,value:r.apply(this,e)}),this[n]}}],jl,"isTouchDevice",1);var Dl=jl,Rl=class extends qo{onclick(e,t){this._register(gl(e,wl.CLICK,i=>t(new rl(fl(e),i))))}onmousedown(e,t){this._register(gl(e,wl.MOUSE_DOWN,i=>t(new rl(fl(e),i))))}onmouseover(e,t){this._register(gl(e,wl.MOUSE_OVER,i=>t(new rl(fl(e),i))))}onmouseleave(e,t){this._register(gl(e,wl.MOUSE_LEAVE,i=>t(new rl(fl(e),i))))}onkeydown(e,t){this._register(gl(e,wl.KEY_DOWN,e=>t(new Qa(e))))}onkeyup(e,t){this._register(gl(e,wl.KEY_UP,e=>t(new Qa(e))))}oninput(e,t){this._register(gl(e,wl.INPUT,t))}onblur(e,t){this._register(gl(e,wl.BLUR,t))}onfocus(e,t){this._register(gl(e,wl.FOCUS,t))}onchange(e,t){this._register(gl(e,wl.CHANGE,t))}ignoreGesture(e){return Dl.ignoreTarget(e)}},Pl=class extends Rl{constructor(e){super(),this._onActivate=e.onActivate,this.bgDomNode=document.createElement("div"),this.bgDomNode.className="arrow-background",this.bgDomNode.style.position="absolute",this.bgDomNode.style.width=e.bgWidth+"px",this.bgDomNode.style.height=e.bgHeight+"px",typeof e.top<"u"&&(this.bgDomNode.style.top="0px"),typeof e.left<"u"&&(this.bgDomNode.style.left="0px"),typeof e.bottom<"u"&&(this.bgDomNode.style.bottom="0px"),typeof e.right<"u"&&(this.bgDomNode.style.right="0px"),this.domNode=document.createElement("div"),this.domNode.className=e.className,this.domNode.style.position="absolute",this.domNode.style.width="11px",this.domNode.style.height="11px",typeof e.top<"u"&&(this.domNode.style.top=e.top+"px"),typeof e.left<"u"&&(this.domNode.style.left=e.left+"px"),typeof e.bottom<"u"&&(this.domNode.style.bottom=e.bottom+"px"),typeof e.right<"u"&&(this.domNode.style.right=e.right+"px"),this._pointerMoveMonitor=this._register(new Ml),this._register(yl(this.bgDomNode,wl.POINTER_DOWN,e=>this._arrowPointerDown(e))),this._register(yl(this.domNode,wl.POINTER_DOWN,e=>this._arrowPointerDown(e))),this._pointerdownRepeatTimer=this._register(new xl),this._pointerdownScheduleRepeatTimer=this._register(new hl)}_arrowPointerDown(e){if(!(e.target&&e.target instanceof Element))return;this._onActivate(),this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancelAndSet(()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,fl(e))},200),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,e=>{},()=>{this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancel()}),e.preventDefault()}},Ll=class e{constructor(e,t,i,s,r,n,o){this._forceIntegerValues=e,this._scrollStateBrand=void 0,this._forceIntegerValues&&(t|=0,i|=0,s|=0,r|=0,n|=0,o|=0),this.rawScrollLeft=s,this.rawScrollTop=o,t<0&&(t=0),s+t>i&&(s=i-t),s<0&&(s=0),r<0&&(r=0),o+r>n&&(o=n-r),o<0&&(o=0),this.width=t,this.scrollWidth=i,this.scrollLeft=s,this.height=r,this.scrollHeight=n,this.scrollTop=o}equals(e){return this.rawScrollLeft===e.rawScrollLeft&&this.rawScrollTop===e.rawScrollTop&&this.width===e.width&&this.scrollWidth===e.scrollWidth&&this.scrollLeft===e.scrollLeft&&this.height===e.height&&this.scrollHeight===e.scrollHeight&&this.scrollTop===e.scrollTop}withScrollDimensions(t,i){return new e(this._forceIntegerValues,typeof t.width<"u"?t.width:this.width,typeof t.scrollWidth<"u"?t.scrollWidth:this.scrollWidth,i?this.rawScrollLeft:this.scrollLeft,typeof t.height<"u"?t.height:this.height,typeof t.scrollHeight<"u"?t.scrollHeight:this.scrollHeight,i?this.rawScrollTop:this.scrollTop)}withScrollPosition(t){return new e(this._forceIntegerValues,this.width,this.scrollWidth,typeof t.scrollLeft<"u"?t.scrollLeft:this.rawScrollLeft,this.height,this.scrollHeight,typeof t.scrollTop<"u"?t.scrollTop:this.rawScrollTop)}createScrollEvent(e,t){let i=this.width!==e.width,s=this.scrollWidth!==e.scrollWidth,r=this.scrollLeft!==e.scrollLeft,n=this.height!==e.height,o=this.scrollHeight!==e.scrollHeight,a=this.scrollTop!==e.scrollTop;return{inSmoothScrolling:t,oldWidth:e.width,oldScrollWidth:e.scrollWidth,oldScrollLeft:e.scrollLeft,width:this.width,scrollWidth:this.scrollWidth,scrollLeft:this.scrollLeft,oldHeight:e.height,oldScrollHeight:e.scrollHeight,oldScrollTop:e.scrollTop,height:this.height,scrollHeight:this.scrollHeight,scrollTop:this.scrollTop,widthChanged:i,scrollWidthChanged:s,scrollLeftChanged:r,heightChanged:n,scrollHeightChanged:o,scrollTopChanged:a}}},Tl=class extends qo{constructor(e){super(),this._scrollableBrand=void 0,this._onScroll=this._register(new da),this.onScroll=this._onScroll.event,this._smoothScrollDuration=e.smoothScrollDuration,this._scheduleAtNextAnimationFrame=e.scheduleAtNextAnimationFrame,this._state=new Ll(e.forceIntegerValues,0,0,0,0,0,0),this._smoothScrolling=null}dispose(){this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),super.dispose()}setSmoothScrollDuration(e){this._smoothScrollDuration=e}validateScrollPosition(e){return this._state.withScrollPosition(e)}getScrollDimensions(){return this._state}setScrollDimensions(e,t){var i;let s=this._state.withScrollDimensions(e,t);this._setState(s,!!this._smoothScrolling),null==(i=this._smoothScrolling)||i.acceptScrollDimensions(this._state)}getFutureScrollPosition(){return this._smoothScrolling?this._smoothScrolling.to:this._state}getCurrentScrollPosition(){return this._state}setScrollPositionNow(e){let t=this._state.withScrollPosition(e);this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),this._setState(t,!1)}setScrollPositionSmooth(e,t){if(0===this._smoothScrollDuration)return this.setScrollPositionNow(e);if(this._smoothScrolling){e={scrollLeft:typeof e.scrollLeft>"u"?this._smoothScrolling.to.scrollLeft:e.scrollLeft,scrollTop:typeof e.scrollTop>"u"?this._smoothScrolling.to.scrollTop:e.scrollTop};let i,s=this._state.withScrollPosition(e);if(this._smoothScrolling.to.scrollLeft===s.scrollLeft&&this._smoothScrolling.to.scrollTop===s.scrollTop)return;i=t?new Ol(this._smoothScrolling.from,s,this._smoothScrolling.startTime,this._smoothScrolling.duration):this._smoothScrolling.combine(this._state,s,this._smoothScrollDuration),this._smoothScrolling.dispose(),this._smoothScrolling=i}else{let t=this._state.withScrollPosition(e);this._smoothScrolling=Ol.start(this._state,t,this._smoothScrollDuration)}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}hasPendingScrollAnimation(){return!!this._smoothScrolling}_performSmoothScrolling(){if(!this._smoothScrolling)return;let e=this._smoothScrolling.tick(),t=this._state.withScrollPosition(e);if(this._setState(t,!0),this._smoothScrolling){if(e.isDone)return this._smoothScrolling.dispose(),void(this._smoothScrolling=null);this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}}_setState(e,t){let i=this._state;i.equals(e)||(this._state=e,this._onScroll.fire(this._state.createScrollEvent(i,t)))}},Il=class{constructor(e,t,i){this.scrollLeft=e,this.scrollTop=t,this.isDone=i}};function Bl(e,t){let i=t-e;return function(t){return e+i*function(e){return 1-function(e){return Math.pow(e,3)}(1-e)}(t)}}var Ol=class e{constructor(e,t,i,s){this.from=e,this.to=t,this.duration=s,this.startTime=i,this.animationFrameDisposable=null,this._initAnimations()}_initAnimations(){this.scrollLeft=this._initAnimation(this.from.scrollLeft,this.to.scrollLeft,this.to.width),this.scrollTop=this._initAnimation(this.from.scrollTop,this.to.scrollTop,this.to.height)}_initAnimation(e,t,i){if(Math.abs(e-t)>2.5*i){let s,r;return e<t?(s=e+.75*i,r=t-.75*i):(s=e-.75*i,r=t+.75*i),function(e,t,i){return function(s){return s<i?e(s/i):t((s-i)/(1-i))}}(Bl(e,s),Bl(r,t),.33)}return Bl(e,t)}dispose(){null!==this.animationFrameDisposable&&(this.animationFrameDisposable.dispose(),this.animationFrameDisposable=null)}acceptScrollDimensions(e){this.to=e.withScrollPosition(this.to),this._initAnimations()}tick(){return this._tick(Date.now())}_tick(e){let t=(e-this.startTime)/this.duration;if(t<1){let e=this.scrollLeft(t),i=this.scrollTop(t);return new Il(e,i,!1)}return new Il(this.to.scrollLeft,this.to.scrollTop,!0)}combine(t,i,s){return e.start(t,i,s)}static start(t,i,s){s+=10;let r=Date.now()-10;return new e(t,i,r,s)}};var Al=class extends qo{constructor(e,t,i){super(),this._visibility=e,this._visibleClassName=t,this._invisibleClassName=i,this._domNode=null,this._isVisible=!1,this._isNeeded=!1,this._rawShouldBeVisible=!1,this._shouldBeVisible=!1,this._revealTimer=this._register(new hl)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this._updateShouldBeVisible())}setShouldBeVisible(e){this._rawShouldBeVisible=e,this._updateShouldBeVisible()}_applyVisibilitySetting(){return 2!==this._visibility&&(3===this._visibility||this._rawShouldBeVisible)}_updateShouldBeVisible(){let e=this._applyVisibilitySetting();this._shouldBeVisible!==e&&(this._shouldBeVisible=e,this.ensureVisibility())}setIsNeeded(e){this._isNeeded!==e&&(this._isNeeded=e,this.ensureVisibility())}setDomNode(e){this._domNode=e,this._domNode.setClassName(this._invisibleClassName),this.setShouldBeVisible(!1)}ensureVisibility(){this._isNeeded?this._shouldBeVisible?this._reveal():this._hide(!0):this._hide(!1)}_reveal(){this._isVisible||(this._isVisible=!0,this._revealTimer.setIfNotSet(()=>{var e;null==(e=this._domNode)||e.setClassName(this._visibleClassName)},0))}_hide(e){var t;this._revealTimer.cancel(),this._isVisible&&(this._isVisible=!1,null==(t=this._domNode)||t.setClassName(this._invisibleClassName+(e?" fade":"")))}},zl=class extends Rl{constructor(e){super(),this._lazyRender=e.lazyRender,this._host=e.host,this._scrollable=e.scrollable,this._scrollByPage=e.scrollByPage,this._scrollbarState=e.scrollbarState,this._visibilityController=this._register(new Al(e.visibility,"visible scrollbar "+e.extraScrollbarClassName,"invisible scrollbar "+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new Ml),this._shouldRender=!0,this.domNode=kl(document.createElement("div")),this.domNode.setAttribute("role","presentation"),this.domNode.setAttribute("aria-hidden","true"),this._visibilityController.setDomNode(this.domNode),this.domNode.setPosition("absolute"),this._register(gl(this.domNode.domNode,wl.POINTER_DOWN,e=>this._domNodePointerDown(e)))}_createArrow(e){let t=this._register(new Pl(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,i,s){this.slider=kl(document.createElement("div")),this.slider.setClassName("slider"),this.slider.setPosition("absolute"),this.slider.setTop(e),this.slider.setLeft(t),"number"==typeof i&&this.slider.setWidth(i),"number"==typeof s&&this.slider.setHeight(s),this.slider.setLayerHinting(!0),this.slider.setContain("strict"),this.domNode.domNode.appendChild(this.slider.domNode),this._register(gl(this.slider.domNode,wl.POINTER_DOWN,e=>{0===e.button&&(e.preventDefault(),this._sliderPointerDown(e))})),this.onclick(this.slider.domNode,e=>{e.leftButton&&e.stopPropagation()})}_onElementSize(e){return this._scrollbarState.setVisibleSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollSize(e){return this._scrollbarState.setScrollSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollPosition(e){return this._scrollbarState.setScrollPosition(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}beginReveal(){this._visibilityController.setShouldBeVisible(!0)}beginHide(){this._visibilityController.setShouldBeVisible(!1)}render(){this._shouldRender&&(this._shouldRender=!1,this._renderDomNode(this._scrollbarState.getRectangleLargeSize(),this._scrollbarState.getRectangleSmallSize()),this._updateSlider(this._scrollbarState.getSliderSize(),this._scrollbarState.getArrowSize()+this._scrollbarState.getSliderPosition()))}_domNodePointerDown(e){e.target===this.domNode.domNode&&this._onPointerDown(e)}delegatePointerDown(e){let t=this.domNode.domNode.getClientRects()[0].top,i=t+this._scrollbarState.getSliderPosition(),s=t+this._scrollbarState.getSliderPosition()+this._scrollbarState.getSliderSize(),r=this._sliderPointerPosition(e);i<=r&&r<=s?0===e.button&&(e.preventDefault(),this._sliderPointerDown(e)):this._onPointerDown(e)}_onPointerDown(e){let t,i;if(e.target===this.domNode.domNode&&"number"==typeof e.offsetX&&"number"==typeof e.offsetY)t=e.offsetX,i=e.offsetY;else{let s=function(e){let t=e.getBoundingClientRect(),i=fl(e);return{left:t.left+i.scrollX,top:t.top+i.scrollY,width:t.width,height:t.height}}(this.domNode.domNode);t=e.pageX-s.left,i=e.pageY-s.top}let s=this._pointerDownRelativePosition(t,i);this._setDesiredScrollPositionNow(this._scrollByPage?this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(s):this._scrollbarState.getDesiredScrollPositionFromOffset(s)),0===e.button&&(e.preventDefault(),this._sliderPointerDown(e))}_sliderPointerDown(e){if(!(e.target&&e.target instanceof Element))return;let t=this._sliderPointerPosition(e),i=this._sliderOrthogonalPointerPosition(e),s=this._scrollbarState.clone();this.slider.toggleClassName("active",!0),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,e=>{let r=this._sliderOrthogonalPointerPosition(e),n=Math.abs(r-i);if(La&&n>140)return void this._setDesiredScrollPositionNow(s.getScrollPosition());let o=this._sliderPointerPosition(e)-t;this._setDesiredScrollPositionNow(s.getDesiredScrollPositionFromDelta(o))},()=>{this.slider.toggleClassName("active",!1),this._host.onDragEnd()}),this._host.onDragStart()}_setDesiredScrollPositionNow(e){let t={};this.writeScrollPosition(t,e),this._scrollable.setScrollPositionNow(t)}updateScrollbarSize(e){this._updateScrollbarSize(e),this._scrollbarState.setScrollbarSize(e),this._shouldRender=!0,this._lazyRender||this.render()}isNeeded(){return this._scrollbarState.isNeeded()}},$l=class e{constructor(e,t,i,s,r,n){this._scrollbarSize=Math.round(t),this._oppositeScrollbarSize=Math.round(i),this._arrowSize=Math.round(e),this._visibleSize=s,this._scrollSize=r,this._scrollPosition=n,this._computedAvailableSize=0,this._computedIsNeeded=!1,this._computedSliderSize=0,this._computedSliderRatio=0,this._computedSliderPosition=0,this._refreshComputedValues()}clone(){return new e(this._arrowSize,this._scrollbarSize,this._oppositeScrollbarSize,this._visibleSize,this._scrollSize,this._scrollPosition)}setVisibleSize(e){let t=Math.round(e);return this._visibleSize!==t&&(this._visibleSize=t,this._refreshComputedValues(),!0)}setScrollSize(e){let t=Math.round(e);return this._scrollSize!==t&&(this._scrollSize=t,this._refreshComputedValues(),!0)}setScrollPosition(e){let t=Math.round(e);return this._scrollPosition!==t&&(this._scrollPosition=t,this._refreshComputedValues(),!0)}setScrollbarSize(e){this._scrollbarSize=Math.round(e)}setOppositeScrollbarSize(e){this._oppositeScrollbarSize=Math.round(e)}static _computeValues(e,t,i,s,r){let n=Math.max(0,i-e),o=Math.max(0,n-2*t),a=s>0&&s>i;if(!a)return{computedAvailableSize:Math.round(n),computedIsNeeded:a,computedSliderSize:Math.round(o),computedSliderRatio:0,computedSliderPosition:0};let l=Math.round(Math.max(20,Math.floor(i*o/s))),c=(o-l)/(s-i),h=r*c;return{computedAvailableSize:Math.round(n),computedIsNeeded:a,computedSliderSize:Math.round(l),computedSliderRatio:c,computedSliderPosition:Math.round(h)}}_refreshComputedValues(){let t=e._computeValues(this._oppositeScrollbarSize,this._arrowSize,this._visibleSize,this._scrollSize,this._scrollPosition);this._computedAvailableSize=t.computedAvailableSize,this._computedIsNeeded=t.computedIsNeeded,this._computedSliderSize=t.computedSliderSize,this._computedSliderRatio=t.computedSliderRatio,this._computedSliderPosition=t.computedSliderPosition}getArrowSize(){return this._arrowSize}getScrollPosition(){return this._scrollPosition}getRectangleLargeSize(){return this._computedAvailableSize}getRectangleSmallSize(){return this._scrollbarSize}isNeeded(){return this._computedIsNeeded}getSliderSize(){return this._computedSliderSize}getSliderPosition(){return this._computedSliderPosition}getDesiredScrollPositionFromOffset(e){if(!this._computedIsNeeded)return 0;let t=e-this._arrowSize-this._computedSliderSize/2;return Math.round(t/this._computedSliderRatio)}getDesiredScrollPositionFromOffsetPaged(e){if(!this._computedIsNeeded)return 0;let t=e-this._arrowSize,i=this._scrollPosition;return t<this._computedSliderPosition?i-=this._visibleSize:i+=this._visibleSize,i}getDesiredScrollPositionFromDelta(e){if(!this._computedIsNeeded)return 0;let t=this._computedSliderPosition+e;return Math.round(t/this._computedSliderRatio)}},Hl=class extends zl{constructor(e,t,i){let s=e.getScrollDimensions(),r=e.getCurrentScrollPosition();if(super({lazyRender:t.lazyRender,host:i,scrollbarState:new $l(t.horizontalHasArrows?t.arrowSize:0,2===t.horizontal?0:t.horizontalScrollbarSize,2===t.vertical?0:t.verticalScrollbarSize,s.width,s.scrollWidth,r.scrollLeft),visibility:t.horizontal,extraScrollbarClassName:"horizontal",scrollable:e,scrollByPage:t.scrollByPage}),t.horizontalHasArrows)throw new Error("horizontalHasArrows is not supported in xterm.js");this._createSlider(Math.floor((t.horizontalScrollbarSize-t.horizontalSliderSize)/2),0,void 0,t.horizontalSliderSize)}_updateSlider(e,t){this.slider.setWidth(e),this.slider.setLeft(t)}_renderDomNode(e,t){this.domNode.setWidth(e),this.domNode.setHeight(t),this.domNode.setLeft(0),this.domNode.setBottom(0)}onDidScroll(e){return this._shouldRender=this._onElementScrollSize(e.scrollWidth)||this._shouldRender,this._shouldRender=this._onElementScrollPosition(e.scrollLeft)||this._shouldRender,this._shouldRender=this._onElementSize(e.width)||this._shouldRender,this._shouldRender}_pointerDownRelativePosition(e,t){return e}_sliderPointerPosition(e){return e.pageX}_sliderOrthogonalPointerPosition(e){return e.pageY}_updateScrollbarSize(e){this.slider.setHeight(e)}writeScrollPosition(e,t){e.scrollLeft=t}updateOptions(e){this.updateScrollbarSize(2===e.horizontal?0:e.horizontalScrollbarSize),this._scrollbarState.setOppositeScrollbarSize(2===e.vertical?0:e.verticalScrollbarSize),this._visibilityController.setVisibility(e.horizontal),this._scrollByPage=e.scrollByPage}},Wl=class extends zl{constructor(e,t,i){let s=e.getScrollDimensions(),r=e.getCurrentScrollPosition();if(super({lazyRender:t.lazyRender,host:i,scrollbarState:new $l(t.verticalHasArrows?t.arrowSize:0,2===t.vertical?0:t.verticalScrollbarSize,0,s.height,s.scrollHeight,r.scrollTop),visibility:t.vertical,extraScrollbarClassName:"vertical",scrollable:e,scrollByPage:t.scrollByPage}),t.verticalHasArrows)throw new Error("horizontalHasArrows is not supported in xterm.js");this._createSlider(0,Math.floor((t.verticalScrollbarSize-t.verticalSliderSize)/2),t.verticalSliderSize,void 0)}_updateSlider(e,t){this.slider.setHeight(e),this.slider.setTop(t)}_renderDomNode(e,t){this.domNode.setWidth(t),this.domNode.setHeight(e),this.domNode.setRight(0),this.domNode.setTop(0)}onDidScroll(e){return this._shouldRender=this._onElementScrollSize(e.scrollHeight)||this._shouldRender,this._shouldRender=this._onElementScrollPosition(e.scrollTop)||this._shouldRender,this._shouldRender=this._onElementSize(e.height)||this._shouldRender,this._shouldRender}_pointerDownRelativePosition(e,t){return t}_sliderPointerPosition(e){return e.pageY}_sliderOrthogonalPointerPosition(e){return e.pageX}_updateScrollbarSize(e){this.slider.setWidth(e)}writeScrollPosition(e,t){e.scrollTop=t}updateOptions(e){this.updateScrollbarSize(2===e.vertical?0:e.verticalScrollbarSize),this._scrollbarState.setOppositeScrollbarSize(0),this._visibilityController.setVisibility(e.vertical),this._scrollByPage=e.scrollByPage}},Fl=class{constructor(e,t,i){this.timestamp=e,this.deltaX=t,this.deltaY=i,this.score=0}},Kl=class{constructor(){this._capacity=5,this._memory=[],this._front=-1,this._rear=-1}isPhysicalMouseWheel(){if(-1===this._front&&-1===this._rear)return!1;let e=1,t=0,i=1,s=this._rear;for(;;){let r=s===this._front?e:Math.pow(2,-i);if(e-=r,t+=this._memory[s].score*r,s===this._front)break;s=(this._capacity+s-1)%this._capacity,i++}return t<=.5}acceptStandardWheelEvent(e){if(va){let i=fl(e.browserEvent),s=(t=i,pa.INSTANCE.getZoomFactor(t));this.accept(Date.now(),e.deltaX*s,e.deltaY*s)}else this.accept(Date.now(),e.deltaX,e.deltaY);var t}accept(e,t,i){let s=null,r=new Fl(e,t,i);-1===this._front&&-1===this._rear?(this._memory[0]=r,this._front=0,this._rear=0):(s=this._memory[this._rear],this._rear=(this._rear+1)%this._capacity,this._rear===this._front&&(this._front=(this._front+1)%this._capacity),this._memory[this._rear]=r),r.score=this._computeScore(r,s)}_computeScore(e,t){if(Math.abs(e.deltaX)>0&&Math.abs(e.deltaY)>0)return 1;let i=.5;if((!this._isAlmostInt(e.deltaX)||!this._isAlmostInt(e.deltaY))&&(i+=.25),t){let s=Math.abs(e.deltaX),r=Math.abs(e.deltaY),n=Math.abs(t.deltaX),o=Math.abs(t.deltaY),a=Math.max(Math.min(s,n),1),l=Math.max(Math.min(r,o),1),c=Math.max(s,n),h=Math.max(r,o);c%a===0&&h%l===0&&(i-=.5)}return Math.min(Math.max(i,0),1)}_isAlmostInt(e){return Math.abs(Math.round(e)-e)<.01}};Kl.INSTANCE=new Kl;var Ul=Kl,Vl=class extends Rl{constructor(e,t,i){super(),this._onScroll=this._register(new da),this.onScroll=this._onScroll.event,this._onWillScroll=this._register(new da),this.onWillScroll=this._onWillScroll.event,this._options=function(e){let t={lazyRender:typeof e.lazyRender<"u"&&e.lazyRender,className:typeof e.className<"u"?e.className:"",useShadows:!(typeof e.useShadows<"u")||e.useShadows,handleMouseWheel:!(typeof e.handleMouseWheel<"u")||e.handleMouseWheel,flipAxes:typeof e.flipAxes<"u"&&e.flipAxes,consumeMouseWheelIfScrollbarIsNeeded:typeof e.consumeMouseWheelIfScrollbarIsNeeded<"u"&&e.consumeMouseWheelIfScrollbarIsNeeded,alwaysConsumeMouseWheel:typeof e.alwaysConsumeMouseWheel<"u"&&e.alwaysConsumeMouseWheel,scrollYToX:typeof e.scrollYToX<"u"&&e.scrollYToX,mouseWheelScrollSensitivity:typeof e.mouseWheelScrollSensitivity<"u"?e.mouseWheelScrollSensitivity:1,fastScrollSensitivity:typeof e.fastScrollSensitivity<"u"?e.fastScrollSensitivity:5,scrollPredominantAxis:!(typeof e.scrollPredominantAxis<"u")||e.scrollPredominantAxis,mouseWheelSmoothScroll:!(typeof e.mouseWheelSmoothScroll<"u")||e.mouseWheelSmoothScroll,arrowSize:typeof e.arrowSize<"u"?e.arrowSize:11,listenOnDomNode:typeof e.listenOnDomNode<"u"?e.listenOnDomNode:null,horizontal:typeof e.horizontal<"u"?e.horizontal:1,horizontalScrollbarSize:typeof e.horizontalScrollbarSize<"u"?e.horizontalScrollbarSize:10,horizontalSliderSize:typeof e.horizontalSliderSize<"u"?e.horizontalSliderSize:0,horizontalHasArrows:typeof e.horizontalHasArrows<"u"&&e.horizontalHasArrows,vertical:typeof e.vertical<"u"?e.vertical:1,verticalScrollbarSize:typeof e.verticalScrollbarSize<"u"?e.verticalScrollbarSize:10,verticalHasArrows:typeof e.verticalHasArrows<"u"&&e.verticalHasArrows,verticalSliderSize:typeof e.verticalSliderSize<"u"?e.verticalSliderSize:0,scrollByPage:typeof e.scrollByPage<"u"&&e.scrollByPage};return t.horizontalSliderSize=typeof e.horizontalSliderSize<"u"?e.horizontalSliderSize:t.horizontalScrollbarSize,t.verticalSliderSize=typeof e.verticalSliderSize<"u"?e.verticalSliderSize:t.verticalScrollbarSize,Ta&&(t.className+=" mac"),t}(t),this._scrollable=i,this._register(this._scrollable.onScroll(e=>{this._onWillScroll.fire(e),this._onDidScroll(e),this._onScroll.fire(e)}));let s={onMouseWheel:e=>this._onMouseWheel(e),onDragStart:()=>this._onDragStart(),onDragEnd:()=>this._onDragEnd()};this._verticalScrollbar=this._register(new Wl(this._scrollable,this._options,s)),this._horizontalScrollbar=this._register(new Hl(this._scrollable,this._options,s)),this._domNode=document.createElement("div"),this._domNode.className="xterm-scrollable-element "+this._options.className,this._domNode.setAttribute("role","presentation"),this._domNode.style.position="relative",this._domNode.appendChild(e),this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode),this._domNode.appendChild(this._verticalScrollbar.domNode.domNode),this._options.useShadows?(this._leftShadowDomNode=kl(document.createElement("div")),this._leftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=kl(document.createElement("div")),this._topShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=kl(document.createElement("div")),this._topLeftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topLeftShadowDomNode.domNode)):(this._leftShadowDomNode=null,this._topShadowDomNode=null,this._topLeftShadowDomNode=null),this._listenOnDomNode=this._options.listenOnDomNode||this._domNode,this._mouseWheelToDispose=[],this._setListeningToMouseWheel(this._options.handleMouseWheel),this.onmouseover(this._listenOnDomNode,e=>this._onMouseOver(e)),this.onmouseleave(this._listenOnDomNode,e=>this._onMouseLeave(e)),this._hideTimeout=this._register(new hl),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=Fo(this._mouseWheelToDispose),super.dispose()}getDomNode(){return this._domNode}getOverviewRulerLayoutInfo(){return{parent:this._domNode,insertBefore:this._verticalScrollbar.domNode.domNode}}delegateVerticalScrollbarPointerDown(e){this._verticalScrollbar.delegatePointerDown(e)}getScrollDimensions(){return this._scrollable.getScrollDimensions()}setScrollDimensions(e){this._scrollable.setScrollDimensions(e,!1)}updateClassName(e){this._options.className=e,Ta&&(this._options.className+=" mac"),this._domNode.className="xterm-scrollable-element "+this._options.className}updateOptions(e){typeof e.handleMouseWheel<"u"&&(this._options.handleMouseWheel=e.handleMouseWheel,this._setListeningToMouseWheel(this._options.handleMouseWheel)),typeof e.mouseWheelScrollSensitivity<"u"&&(this._options.mouseWheelScrollSensitivity=e.mouseWheelScrollSensitivity),typeof e.fastScrollSensitivity<"u"&&(this._options.fastScrollSensitivity=e.fastScrollSensitivity),typeof e.scrollPredominantAxis<"u"&&(this._options.scrollPredominantAxis=e.scrollPredominantAxis),typeof e.horizontal<"u"&&(this._options.horizontal=e.horizontal),typeof e.vertical<"u"&&(this._options.vertical=e.vertical),typeof e.horizontalScrollbarSize<"u"&&(this._options.horizontalScrollbarSize=e.horizontalScrollbarSize),typeof e.verticalScrollbarSize<"u"&&(this._options.verticalScrollbarSize=e.verticalScrollbarSize),typeof e.scrollByPage<"u"&&(this._options.scrollByPage=e.scrollByPage),this._horizontalScrollbar.updateOptions(this._options),this._verticalScrollbar.updateOptions(this._options),this._options.lazyRender||this._render()}setRevealOnScroll(e){this._revealOnScroll=e}delegateScrollFromMouseWheelEvent(e){this._onMouseWheel(new nl(e))}_setListeningToMouseWheel(e){if(this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=Fo(this._mouseWheelToDispose),e)){let e=e=>{this._onMouseWheel(new nl(e))};this._mouseWheelToDispose.push(gl(this._listenOnDomNode,wl.MOUSE_WHEEL,e,{passive:!1}))}}_onMouseWheel(e){var t;if(null==(t=e.browserEvent)?void 0:t.defaultPrevented)return;let i=Ul.INSTANCE;i.acceptStandardWheelEvent(e);let s=!1;if(e.deltaY||e.deltaX){let t=e.deltaY*this._options.mouseWheelScrollSensitivity,r=e.deltaX*this._options.mouseWheelScrollSensitivity;this._options.scrollPredominantAxis&&(this._options.scrollYToX&&r+t===0?r=t=0:Math.abs(t)>=Math.abs(r)?r=0:t=0),this._options.flipAxes&&([t,r]=[r,t]);let n=!Ta&&e.browserEvent&&e.browserEvent.shiftKey;(this._options.scrollYToX||n)&&!r&&(r=t,t=0),e.browserEvent&&e.browserEvent.altKey&&(r*=this._options.fastScrollSensitivity,t*=this._options.fastScrollSensitivity);let o=this._scrollable.getFutureScrollPosition(),a={};if(t){let e=50*t,i=o.scrollTop-(e<0?Math.floor(e):Math.ceil(e));this._verticalScrollbar.writeScrollPosition(a,i)}if(r){let e=50*r,t=o.scrollLeft-(e<0?Math.floor(e):Math.ceil(e));this._horizontalScrollbar.writeScrollPosition(a,t)}a=this._scrollable.validateScrollPosition(a),(o.scrollLeft!==a.scrollLeft||o.scrollTop!==a.scrollTop)&&(this._options.mouseWheelSmoothScroll&&i.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(a):this._scrollable.setScrollPositionNow(a),s=!0)}let r=s;!r&&this._options.alwaysConsumeMouseWheel&&(r=!0),!r&&this._options.consumeMouseWheelIfScrollbarIsNeeded&&(this._verticalScrollbar.isNeeded()||this._horizontalScrollbar.isNeeded())&&(r=!0),r&&(e.preventDefault(),e.stopPropagation())}_onDidScroll(e){this._shouldRender=this._horizontalScrollbar.onDidScroll(e)||this._shouldRender,this._shouldRender=this._verticalScrollbar.onDidScroll(e)||this._shouldRender,this._options.useShadows&&(this._shouldRender=!0),this._revealOnScroll&&this._reveal(),this._options.lazyRender||this._render()}renderNow(){if(!this._options.lazyRender)throw new Error("Please use `lazyRender` together with `renderNow`!");this._render()}_render(){if(this._shouldRender&&(this._shouldRender=!1,this._horizontalScrollbar.render(),this._verticalScrollbar.render(),this._options.useShadows)){let e=this._scrollable.getCurrentScrollPosition(),t=e.scrollTop>0,i=e.scrollLeft>0,s=i?" left":"",r=t?" top":"",n=i||t?" top-left-corner":"";this._leftShadowDomNode.setClassName(`shadow${s}`),this._topShadowDomNode.setClassName(`shadow${r}`),this._topLeftShadowDomNode.setClassName(`shadow${n}${r}${s}`)}}_onDragStart(){this._isDragging=!0,this._reveal()}_onDragEnd(){this._isDragging=!1,this._hide()}_onMouseLeave(e){this._mouseIsOver=!1,this._hide()}_onMouseOver(e){this._mouseIsOver=!0,this._reveal()}_reveal(){this._verticalScrollbar.beginReveal(),this._horizontalScrollbar.beginReveal(),this._scheduleHide()}_hide(){!this._mouseIsOver&&!this._isDragging&&(this._verticalScrollbar.beginHide(),this._horizontalScrollbar.beginHide())}_scheduleHide(){!this._mouseIsOver&&!this._isDragging&&this._hideTimeout.cancelAndSet(()=>this._hide(),500)}},ql=class extends Vl{constructor(e,t,i){super(e,t,i)}setScrollPosition(e){e.reuseAnimation?this._scrollable.setScrollPositionSmooth(e,e.reuseAnimation):this._scrollable.setScrollPositionNow(e)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}};var Yl=class extends qo{constructor(e,t,i,s,r,n,o,a){super(),this._bufferService=i,this._optionsService=o,this._renderService=a,this._onRequestScrollLines=this._register(new da),this.onRequestScrollLines=this._onRequestScrollLines.event,this._isSyncing=!1,this._isHandlingScroll=!1,this._suppressOnScrollHandler=!1;let l=this._register(new Tl({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:e=>vl(s.window,e)}));this._register(this._optionsService.onSpecificOptionChange("smoothScrollDuration",()=>{l.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new ql(t,{vertical:1,horizontal:2,useShadows:!1,mouseWheelSmoothScroll:!0,...this._getChangeOptions()},l)),this._register(this._optionsService.onMultipleOptionChange(["scrollSensitivity","fastScrollSensitivity","overviewRuler"],()=>this._scrollableElement.updateOptions(this._getChangeOptions()))),this._register(r.onProtocolChange(e=>{this._scrollableElement.updateOptions({handleMouseWheel:!(16&e)})})),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(Zo.runAndSubscribe(n.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=n.colors.background.css})),e.appendChild(this._scrollableElement.getDomNode()),this._register(Ko(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=s.mainDocument.createElement("style"),t.appendChild(this._styleElement),this._register(Ko(()=>this._styleElement.remove())),this._register(Zo.runAndSubscribe(n.onChangeColors,()=>{this._styleElement.textContent=[".xterm .xterm-scrollable-element > .scrollbar > .slider {",` background: ${n.colors.scrollbarSliderBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider:hover {",` background: ${n.colors.scrollbarSliderHoverBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider.active {",` background: ${n.colors.scrollbarSliderActiveBackground.css};`,"}"].join("\n")})),this._register(this._bufferService.onResize(()=>this.queueSync())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._latestYDisp=void 0,this.queueSync()})),this._register(this._bufferService.onScroll(()=>this._sync())),this._register(this._scrollableElement.onScroll(e=>this._handleScroll(e)))}scrollLines(e){let t=this._scrollableElement.getScrollPosition();this._scrollableElement.setScrollPosition({reuseAnimation:!0,scrollTop:t.scrollTop+e*this._renderService.dimensions.css.cell.height})}scrollToLine(e,t){t&&(this._latestYDisp=e),this._scrollableElement.setScrollPosition({reuseAnimation:!t,scrollTop:e*this._renderService.dimensions.css.cell.height})}_getChangeOptions(){var e;return{mouseWheelScrollSensitivity:this._optionsService.rawOptions.scrollSensitivity,fastScrollSensitivity:this._optionsService.rawOptions.fastScrollSensitivity,verticalScrollbarSize:(null==(e=this._optionsService.rawOptions.overviewRuler)?void 0:e.width)||14}}queueSync(e){void 0!==e&&(this._latestYDisp=e),void 0===this._queuedAnimationFrame&&(this._queuedAnimationFrame=this._renderService.addRefreshCallback(()=>{this._queuedAnimationFrame=void 0,this._sync(this._latestYDisp)}))}_sync(e=this._bufferService.buffer.ydisp){!this._renderService||this._isSyncing||(this._isSyncing=!0,this._suppressOnScrollHandler=!0,this._scrollableElement.setScrollDimensions({height:this._renderService.dimensions.css.canvas.height,scrollHeight:this._renderService.dimensions.css.cell.height*this._bufferService.buffer.lines.length}),this._suppressOnScrollHandler=!1,e!==this._latestYDisp&&this._scrollableElement.setScrollPosition({scrollTop:e*this._renderService.dimensions.css.cell.height}),this._isSyncing=!1)}_handleScroll(e){if(!this._renderService||this._isHandlingScroll||this._suppressOnScrollHandler)return;this._isHandlingScroll=!0;let t=Math.round(e.scrollTop/this._renderService.dimensions.css.cell.height),i=t-this._bufferService.buffer.ydisp;0!==i&&(this._latestYDisp=t,this._onRequestScrollLines.fire(i)),this._isHandlingScroll=!1}};Yl=Wn([Fn(2,uo),Fn(3,ko),Fn(4,fo),Fn(5,Do),Fn(6,vo),Fn(7,No)],Yl);var Xl=class extends qo{constructor(e,t,i,s,r){super(),this._screenElement=e,this._bufferService=t,this._coreBrowserService=i,this._decorationService=s,this._renderService=r,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement("div"),this._container.classList.add("xterm-decoration-container"),this._screenElement.appendChild(this._container),this._register(this._renderService.onRenderedViewportChange(()=>this._doRefreshDecorations())),this._register(this._renderService.onDimensionsChange(()=>{this._dimensionsChanged=!0,this._queueRefresh()})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt})),this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh())),this._register(this._decorationService.onDecorationRemoved(e=>this._removeDecoration(e))),this._register(Ko(()=>{this._container.remove(),this._decorationElements.clear()}))}_queueRefresh(){void 0===this._animationFrame&&(this._animationFrame=this._renderService.addRefreshCallback(()=>{this._doRefreshDecorations(),this._animationFrame=void 0}))}_doRefreshDecorations(){for(let e of this._decorationService.decorations)this._renderDecoration(e);this._dimensionsChanged=!1}_renderDecoration(e){this._refreshStyle(e),this._dimensionsChanged&&this._refreshXPosition(e)}_createElement(e){var t;let i=this._coreBrowserService.mainDocument.createElement("div");i.classList.add("xterm-decoration"),i.classList.toggle("xterm-decoration-top-layer","top"===(null==(t=null==e?void 0:e.options)?void 0:t.layer)),i.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,i.style.height=(e.options.height||1)*this._renderService.dimensions.css.cell.height+"px",i.style.top=(e.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height+"px",i.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;let s=e.options.x??0;return s&&s>this._bufferService.cols&&(i.style.display="none"),this._refreshXPosition(e,i),i}_refreshStyle(e){let t=e.marker.line-this._bufferService.buffers.active.ydisp;if(t<0||t>=this._bufferService.rows)e.element&&(e.element.style.display="none",e.onRenderEmitter.fire(e.element));else{let i=this._decorationElements.get(e);i||(i=this._createElement(e),e.element=i,this._decorationElements.set(e,i),this._container.appendChild(i),e.onDispose(()=>{this._decorationElements.delete(e),i.remove()})),i.style.display=this._altBufferIsActive?"none":"block",this._altBufferIsActive||(i.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,i.style.height=(e.options.height||1)*this._renderService.dimensions.css.cell.height+"px",i.style.top=t*this._renderService.dimensions.css.cell.height+"px",i.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`),e.onRenderEmitter.fire(i)}}_refreshXPosition(e,t=e.element){if(!t)return;let i=e.options.x??0;"right"===(e.options.anchor||"left")?t.style.right=i?i*this._renderService.dimensions.css.cell.width+"px":"":t.style.left=i?i*this._renderService.dimensions.css.cell.width+"px":""}_removeDecoration(e){var t;null==(t=this._decorationElements.get(e))||t.remove(),this._decorationElements.delete(e),e.dispose()}};Xl=Wn([Fn(1,uo),Fn(2,ko),Fn(3,bo),Fn(4,No)],Xl);var Gl,Zl,Jl,Ql,ec,tc=class{constructor(){this._zones=[],this._zonePool=[],this._zonePoolIndex=0,this._linePadding={full:0,left:0,center:0,right:0}}get zones(){return this._zonePool.length=Math.min(this._zonePool.length,this._zones.length),this._zones}clear(){this._zones.length=0,this._zonePoolIndex=0}addDecoration(e){if(e.options.overviewRulerOptions){for(let t of this._zones)if(t.color===e.options.overviewRulerOptions.color&&t.position===e.options.overviewRulerOptions.position){if(this._lineIntersectsZone(t,e.marker.line))return;if(this._lineAdjacentToZone(t,e.marker.line,e.options.overviewRulerOptions.position))return void this._addLineToZone(t,e.marker.line)}if(this._zonePoolIndex<this._zonePool.length)return this._zonePool[this._zonePoolIndex].color=e.options.overviewRulerOptions.color,this._zonePool[this._zonePoolIndex].position=e.options.overviewRulerOptions.position,this._zonePool[this._zonePoolIndex].startBufferLine=e.marker.line,this._zonePool[this._zonePoolIndex].endBufferLine=e.marker.line,void this._zones.push(this._zonePool[this._zonePoolIndex++]);this._zones.push({color:e.options.overviewRulerOptions.color,position:e.options.overviewRulerOptions.position,startBufferLine:e.marker.line,endBufferLine:e.marker.line}),this._zonePool.push(this._zones[this._zones.length-1]),this._zonePoolIndex++}}setPadding(e){this._linePadding=e}_lineIntersectsZone(e,t){return t>=e.startBufferLine&&t<=e.endBufferLine}_lineAdjacentToZone(e,t,i){return t>=e.startBufferLine-this._linePadding[i||"full"]&&t<=e.endBufferLine+this._linePadding[i||"full"]}_addLineToZone(e,t){e.startBufferLine=Math.min(e.startBufferLine,t),e.endBufferLine=Math.max(e.endBufferLine,t)}},ic={full:0,left:0,center:0,right:0},sc={full:0,left:0,center:0,right:0},rc={full:0,left:0,center:0,right:0},nc=class extends qo{constructor(e,t,i,s,r,n,o,a){var l;super(),this._viewportElement=e,this._screenElement=t,this._bufferService=i,this._decorationService=s,this._renderService=r,this._optionsService=n,this._themeService=o,this._coreBrowserService=a,this._colorZoneStore=new tc,this._shouldUpdateDimensions=!0,this._shouldUpdateAnchor=!0,this._lastKnownBufferLength=0,this._canvas=this._coreBrowserService.mainDocument.createElement("canvas"),this._canvas.classList.add("xterm-decoration-overview-ruler"),this._refreshCanvasDimensions(),null==(l=this._viewportElement.parentElement)||l.insertBefore(this._canvas,this._viewportElement),this._register(Ko(()=>{var e;return null==(e=this._canvas)?void 0:e.remove()}));let c=this._canvas.getContext("2d");if(!c)throw new Error("Ctx cannot be null");this._ctx=c,this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh(void 0,!0))),this._register(this._decorationService.onDecorationRemoved(()=>this._queueRefresh(void 0,!0))),this._register(this._renderService.onRenderedViewportChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?"none":"block"})),this._register(this._bufferService.onScroll(()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())})),this._register(this._renderService.onRender(()=>{(!this._containerHeight||this._containerHeight!==this._screenElement.clientHeight)&&(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh(!0))),this._register(this._optionsService.onSpecificOptionChange("overviewRuler",()=>this._queueRefresh(!0))),this._register(this._themeService.onChangeColors(()=>this._queueRefresh())),this._queueRefresh(!0)}get _width(){var e;return(null==(e=this._optionsService.options.overviewRuler)?void 0:e.width)||0}_refreshDrawConstants(){let e=Math.floor((this._canvas.width-1)/3),t=Math.ceil((this._canvas.width-1)/3);sc.full=this._canvas.width,sc.left=e,sc.center=t,sc.right=e,this._refreshDrawHeightConstants(),rc.full=1,rc.left=1,rc.center=1+sc.left,rc.right=1+sc.left+sc.center}_refreshDrawHeightConstants(){ic.full=Math.round(2*this._coreBrowserService.dpr);let e=this._canvas.height/this._bufferService.buffer.lines.length,t=Math.round(Math.max(Math.min(e,12),6)*this._coreBrowserService.dpr);ic.left=t,ic.center=t,ic.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*ic.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*ic.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*ic.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*ic.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowserService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowserService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(let t of this._decorationService.decorations)this._colorZoneStore.addDecoration(t);this._ctx.lineWidth=1,this._renderRulerOutline();let e=this._colorZoneStore.zones;for(let t of e)"full"!==t.position&&this._renderColorZone(t);for(let t of e)"full"===t.position&&this._renderColorZone(t);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderRulerOutline(){this._ctx.fillStyle=this._themeService.colors.overviewRulerBorder.css,this._ctx.fillRect(0,0,1,this._canvas.height),this._optionsService.rawOptions.overviewRuler.showTopBorder&&this._ctx.fillRect(1,0,this._canvas.width-1,1),this._optionsService.rawOptions.overviewRuler.showBottomBorder&&this._ctx.fillRect(1,this._canvas.height-1,this._canvas.width-1,this._canvas.height)}_renderColorZone(e){this._ctx.fillStyle=e.color,this._ctx.fillRect(rc[e.position||"full"],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-ic[e.position||"full"]/2),sc[e.position||"full"],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+ic[e.position||"full"]))}_queueRefresh(e,t){this._shouldUpdateDimensions=e||this._shouldUpdateDimensions,this._shouldUpdateAnchor=t||this._shouldUpdateAnchor,void 0===this._animationFrame&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._refreshDecorations(),this._animationFrame=void 0}))}};nc=Wn([Fn(2,uo),Fn(3,bo),Fn(4,No),Fn(5,vo),Fn(6,Do),Fn(7,ko)],nc),(Zl=Gl||(Gl={})).NUL="\0",Zl.SOH="",Zl.STX="",Zl.ETX="",Zl.EOT="",Zl.ENQ="",Zl.ACK="",Zl.BEL="",Zl.BS="\b",Zl.HT="\t",Zl.LF="\n",Zl.VT="\v",Zl.FF="\f",Zl.CR="\r",Zl.SO="",Zl.SI="",Zl.DLE="",Zl.DC1="",Zl.DC2="",Zl.DC3="",Zl.DC4="",Zl.NAK="",Zl.SYN="",Zl.ETB="",Zl.CAN="",Zl.EM="",Zl.SUB="",Zl.ESC="",Zl.FS="",Zl.GS="",Zl.RS="",Zl.US="",Zl.SP=" ",Zl.DEL="",(Ql=Jl||(Jl={})).PAD="€",Ql.HOP="",Ql.BPH="‚",Ql.NBH="ƒ",Ql.IND="„",Ql.NEL="…",Ql.SSA="†",Ql.ESA="‡",Ql.HTS="ˆ",Ql.HTJ="‰",Ql.VTS="Š",Ql.PLD="‹",Ql.PLU="Œ",Ql.RI="",Ql.SS2="Ž",Ql.SS3="",Ql.DCS="",Ql.PU1="‘",Ql.PU2="’",Ql.STS="“",Ql.CCH="”",Ql.MW="•",Ql.SPA="–",Ql.EPA="—",Ql.SOS="˜",Ql.SGCI="™",Ql.SCI="š",Ql.CSI="›",Ql.ST="œ",Ql.OSC="",Ql.PM="ž",Ql.APC="Ÿ",(ec||(ec={})).ST=`${Gl.ESC}\\`;var oc=class{constructor(e,t,i,s,r,n){this._textarea=e,this._compositionView=t,this._bufferService=i,this._optionsService=s,this._coreService=r,this._renderService=n,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=""}get isComposing(){return this._isComposing}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent="",this._dataAlreadySent="",this._compositionView.classList.add("active")}compositionupdate(e){this._compositionView.textContent=e.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(e){if(this._isComposing||this._isSendingComposition){if(20===e.keyCode||229===e.keyCode||16===e.keyCode||17===e.keyCode||18===e.keyCode)return!1;this._finalizeComposition(!1)}return 229!==e.keyCode||(this._handleAnyTextareaChanges(),!1)}_finalizeComposition(e){if(this._compositionView.classList.remove("active"),this._isComposing=!1,e){let e={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){let t;this._isSendingComposition=!1,e.start+=this._dataAlreadySent.length,t=this._isComposing?this._textarea.value.substring(e.start,this._compositionPosition.start):this._textarea.value.substring(e.start),t.length>0&&this._coreService.triggerDataEvent(t,!0)}},0)}else{this._isSendingComposition=!1;let e=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(e,!0)}}_handleAnyTextareaChanges(){let e=this._textarea.value;setTimeout(()=>{if(!this._isComposing){let t=this._textarea.value,i=t.replace(e,"");this._dataAlreadySent=i,t.length>e.length?this._coreService.triggerDataEvent(i,!0):t.length<e.length?this._coreService.triggerDataEvent(`${Gl.DEL}`,!0):t.length===e.length&&t!==e&&this._coreService.triggerDataEvent(t,!0)}},0)}updateCompositionElements(e){if(this._isComposing){if(this._bufferService.buffer.isCursorInViewport){let e=Math.min(this._bufferService.buffer.x,this._bufferService.cols-1),t=this._renderService.dimensions.css.cell.height,i=this._bufferService.buffer.y*this._renderService.dimensions.css.cell.height,s=e*this._renderService.dimensions.css.cell.width;this._compositionView.style.left=s+"px",this._compositionView.style.top=i+"px",this._compositionView.style.height=t+"px",this._compositionView.style.lineHeight=t+"px",this._compositionView.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._compositionView.style.fontSize=this._optionsService.rawOptions.fontSize+"px";let r=this._compositionView.getBoundingClientRect();this._textarea.style.left=s+"px",this._textarea.style.top=i+"px",this._textarea.style.width=Math.max(r.width,1)+"px",this._textarea.style.height=Math.max(r.height,1)+"px",this._textarea.style.lineHeight=r.height+"px"}e||setTimeout(()=>this.updateCompositionElements(!0),0)}}};oc=Wn([Fn(2,uo),Fn(3,vo),Fn(4,po),Fn(5,No)],oc);var ac,lc,cc,hc,dc,uc=0,fc=0,pc=0,mc=0,_c={css:"#00000000",rgba:0};function gc(e){let t=e.toString(16);return t.length<2?"0"+t:t}function vc(e,t){return e<t?(t+.05)/(e+.05):(e+.05)/(t+.05)}(e=>{e.toCss=function(e,t,i,s){return void 0!==s?`#${gc(e)}${gc(t)}${gc(i)}${gc(s)}`:`#${gc(e)}${gc(t)}${gc(i)}`},e.toRgba=function(e,t,i,s=255){return(e<<24|t<<16|i<<8|s)>>>0},e.toColor=function(t,i,s,r){return{css:e.toCss(t,i,s,r),rgba:e.toRgba(t,i,s,r)}}})(ac||(ac={})),(e=>{function t(e,t){return mc=Math.round(255*t),[uc,fc,pc]=dc.toChannels(e.rgba),{css:ac.toCss(uc,fc,pc,mc),rgba:ac.toRgba(uc,fc,pc,mc)}}e.blend=function(e,t){if(1===(mc=(255&t.rgba)/255))return{css:t.css,rgba:t.rgba};let i=t.rgba>>24&255,s=t.rgba>>16&255,r=t.rgba>>8&255,n=e.rgba>>24&255,o=e.rgba>>16&255,a=e.rgba>>8&255;return uc=n+Math.round((i-n)*mc),fc=o+Math.round((s-o)*mc),pc=a+Math.round((r-a)*mc),{css:ac.toCss(uc,fc,pc),rgba:ac.toRgba(uc,fc,pc)}},e.isOpaque=function(e){return!(255&~e.rgba)},e.ensureContrastRatio=function(e,t,i){let s=dc.ensureContrastRatio(e.rgba,t.rgba,i);if(s)return ac.toColor(s>>24&255,s>>16&255,s>>8&255)},e.opaque=function(e){let t=(255|e.rgba)>>>0;return[uc,fc,pc]=dc.toChannels(t),{css:ac.toCss(uc,fc,pc),rgba:t}},e.opacity=t,e.multiplyOpacity=function(e,i){return t(e,(mc=255&e.rgba)*i/255)},e.toColorRGB=function(e){return[e.rgba>>24&255,e.rgba>>16&255,e.rgba>>8&255]}})(lc||(lc={})),(e=>{let t,i;try{let e=document.createElement("canvas");e.width=1,e.height=1;let s=e.getContext("2d",{willReadFrequently:!0});s&&(t=s,t.globalCompositeOperation="copy",i=t.createLinearGradient(0,0,1,1))}catch{}e.toColor=function(e){if(e.match(/#[\da-f]{3,8}/i))switch(e.length){case 4:return uc=parseInt(e.slice(1,2).repeat(2),16),fc=parseInt(e.slice(2,3).repeat(2),16),pc=parseInt(e.slice(3,4).repeat(2),16),ac.toColor(uc,fc,pc);case 5:return uc=parseInt(e.slice(1,2).repeat(2),16),fc=parseInt(e.slice(2,3).repeat(2),16),pc=parseInt(e.slice(3,4).repeat(2),16),mc=parseInt(e.slice(4,5).repeat(2),16),ac.toColor(uc,fc,pc,mc);case 7:return{css:e,rgba:(parseInt(e.slice(1),16)<<8|255)>>>0};case 9:return{css:e,rgba:parseInt(e.slice(1),16)>>>0}}let s=e.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(s)return uc=parseInt(s[1]),fc=parseInt(s[2]),pc=parseInt(s[3]),mc=Math.round(255*(void 0===s[5]?1:parseFloat(s[5]))),ac.toColor(uc,fc,pc,mc);if(!t||!i)throw new Error("css.toColor: Unsupported css format");if(t.fillStyle=i,t.fillStyle=e,"string"!=typeof t.fillStyle)throw new Error("css.toColor: Unsupported css format");if(t.fillRect(0,0,1,1),[uc,fc,pc,mc]=t.getImageData(0,0,1,1).data,255!==mc)throw new Error("css.toColor: Unsupported css format");return{rgba:ac.toRgba(uc,fc,pc,mc),css:e}}})(cc||(cc={})),(e=>{function t(e,t,i){let s=e/255,r=t/255,n=i/255;return.2126*(s<=.03928?s/12.92:Math.pow((s+.055)/1.055,2.4))+.7152*(r<=.03928?r/12.92:Math.pow((r+.055)/1.055,2.4))+.0722*(n<=.03928?n/12.92:Math.pow((n+.055)/1.055,2.4))}e.relativeLuminance=function(e){return t(e>>16&255,e>>8&255,255&e)},e.relativeLuminance2=t})(hc||(hc={})),(e=>{function t(e,t,i){let s=e>>24&255,r=e>>16&255,n=e>>8&255,o=t>>24&255,a=t>>16&255,l=t>>8&255,c=vc(hc.relativeLuminance2(o,a,l),hc.relativeLuminance2(s,r,n));for(;c<i&&(o>0||a>0||l>0);)o-=Math.max(0,Math.ceil(.1*o)),a-=Math.max(0,Math.ceil(.1*a)),l-=Math.max(0,Math.ceil(.1*l)),c=vc(hc.relativeLuminance2(o,a,l),hc.relativeLuminance2(s,r,n));return(o<<24|a<<16|l<<8|255)>>>0}function i(e,t,i){let s=e>>24&255,r=e>>16&255,n=e>>8&255,o=t>>24&255,a=t>>16&255,l=t>>8&255,c=vc(hc.relativeLuminance2(o,a,l),hc.relativeLuminance2(s,r,n));for(;c<i&&(o<255||a<255||l<255);)o=Math.min(255,o+Math.ceil(.1*(255-o))),a=Math.min(255,a+Math.ceil(.1*(255-a))),l=Math.min(255,l+Math.ceil(.1*(255-l))),c=vc(hc.relativeLuminance2(o,a,l),hc.relativeLuminance2(s,r,n));return(o<<24|a<<16|l<<8|255)>>>0}e.blend=function(e,t){if(1===(mc=(255&t)/255))return t;let i=t>>24&255,s=t>>16&255,r=t>>8&255,n=e>>24&255,o=e>>16&255,a=e>>8&255;return uc=n+Math.round((i-n)*mc),fc=o+Math.round((s-o)*mc),pc=a+Math.round((r-a)*mc),ac.toRgba(uc,fc,pc)},e.ensureContrastRatio=function(e,s,r){let n=hc.relativeLuminance(e>>8),o=hc.relativeLuminance(s>>8);if(vc(n,o)<r){if(o<n){let o=t(e,s,r),a=vc(n,hc.relativeLuminance(o>>8));if(a<r){let t=i(e,s,r);return a>vc(n,hc.relativeLuminance(t>>8))?o:t}return o}let a=i(e,s,r),l=vc(n,hc.relativeLuminance(a>>8));if(l<r){let i=t(e,s,r);return l>vc(n,hc.relativeLuminance(i>>8))?a:i}return a}},e.reduceLuminance=t,e.increaseLuminance=i,e.toChannels=function(e){return[e>>24&255,e>>16&255,e>>8&255,255&e]}})(dc||(dc={}));var yc=class extends ro{constructor(e,t,i){super(),this.content=0,this.combinedData="",this.fg=e.fg,this.bg=e.bg,this.combinedData=t,this._width=i}isCombined(){return 2097152}getWidth(){return this._width}getChars(){return this.combinedData}getCode(){return 2097151}setFromCharData(e){throw new Error("not implemented")}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},xc=class{constructor(e){this._bufferService=e,this._characterJoiners=[],this._nextCharacterJoinerId=0,this._workCell=new oo}register(e){let t={id:this._nextCharacterJoinerId++,handler:e};return this._characterJoiners.push(t),t.id}deregister(e){for(let t=0;t<this._characterJoiners.length;t++)if(this._characterJoiners[t].id===e)return this._characterJoiners.splice(t,1),!0;return!1}getJoinedCharacters(e){if(0===this._characterJoiners.length)return[];let t=this._bufferService.buffer.lines.get(e);if(!t||0===t.length)return[];let i=[],s=t.translateToString(!0),r=0,n=0,o=0,a=t.getFg(0),l=t.getBg(0);for(let c=0;c<t.getTrimmedLength();c++)if(t.loadCell(c,this._workCell),0!==this._workCell.getWidth()){if(this._workCell.fg!==a||this._workCell.bg!==l){if(c-r>1){let e=this._getJoinedRanges(s,o,n,t,r);for(let t=0;t<e.length;t++)i.push(e[t])}r=c,o=n,a=this._workCell.fg,l=this._workCell.bg}n+=this._workCell.getChars().length||1}if(this._bufferService.cols-r>1){let e=this._getJoinedRanges(s,o,n,t,r);for(let t=0;t<e.length;t++)i.push(e[t])}return i}_getJoinedRanges(e,t,i,s,r){let n=e.substring(t,i),o=[];try{o=this._characterJoiners[0].handler(n)}catch(a){console.error(a)}for(let c=1;c<this._characterJoiners.length;c++)try{let e=this._characterJoiners[c].handler(n);for(let t=0;t<e.length;t++)xc._mergeRanges(o,e[t])}catch(l){console.error(l)}return this._stringRangesToCellRanges(o,s,r),o}_stringRangesToCellRanges(e,t,i){let s=0,r=!1,n=0,o=e[s];if(o){for(let a=i;a<this._bufferService.cols;a++){let i=t.getWidth(a),l=t.getString(a).length||1;if(0!==i){if(!r&&o[0]<=n&&(o[0]=a,r=!0),o[1]<=n){if(o[1]=a,o=e[++s],!o)break;o[0]<=n?(o[0]=a,r=!0):r=!1}n+=l}}o&&(o[1]=this._bufferService.cols)}}static _mergeRanges(e,t){let i=!1;for(let s=0;s<e.length;s++){let r=e[s];if(i){if(t[1]<=r[0])return e[s-1][1]=t[1],e;if(t[1]<=r[1])return e[s-1][1]=Math.max(t[1],r[1]),e.splice(s,1),e;e.splice(s,1),s--}else{if(t[1]<=r[0])return e.splice(s,0,t),e;if(t[1]<=r[1])return r[0]=Math.min(t[0],r[0]),e;t[0]<r[1]&&(r[0]=Math.min(t[0],r[0]),i=!0)}}return i?e[e.length-1][1]=t[1]:e.push(t),e}};xc=Wn([Fn(0,uo)],xc);var bc=class{constructor(e,t,i,s,r,n,o){this._document=e,this._characterJoinerService=t,this._optionsService=i,this._coreBrowserService=s,this._coreService=r,this._decorationService=n,this._themeService=o,this._workCell=new oo,this._columnSelectMode=!1,this.defaultSpacing=0}handleSelectionChanged(e,t,i){this._selectionStart=e,this._selectionEnd=t,this._columnSelectMode=i}createRow(e,t,i,s,r,n,o,a,l,c,h){let d=[],u=this._characterJoinerService.getJoinedCharacters(t),f=this._themeService.colors,p=e.getNoBgTrimmedLength();i&&p<n+1&&(p=n+1);let m,_=0,g="",v=0,y=0,x=0,b=0,w=!1,S=0,C=!1,k=0,E=0,N=[],M=-1!==c&&-1!==h;for(let j=0;j<p;j++){e.loadCell(j,this._workCell);let p=this._workCell.getWidth();if(0===p)continue;let D=!1,R=j>=E,P=j,L=this._workCell;if(u.length>0&&j===u[0][0]&&R){let s=u.shift(),r=this._isCellInSelection(s[0],t);for(v=s[0]+1;v<s[1];v++)R&&(R=r===this._isCellInSelection(v,t));R&&(R=!i||n<s[0]||n>=s[1]),R?(D=!0,L=new yc(this._workCell,e.translateToString(!0,s[0],s[1]),s[1]-s[0]),P=s[1]-1,p=L.getWidth()):E=s[1]}let T=this._isCellInSelection(j,t),I=i&&j===n,B=M&&j>=c&&j<=h,O=!1;this._decorationService.forEachDecorationAtCell(j,t,void 0,e=>{O=!0});let A=L.getChars()||so;if(" "===A&&(L.isUnderline()||L.isOverline())&&(A=" "),k=p*a-l.get(A,L.isBold(),L.isItalic()),m){if(_&&(T&&C||!T&&!C&&L.bg===y)&&(T&&C&&f.selectionForeground||L.fg===x)&&L.extended.ext===b&&B===w&&k===S&&!I&&!D&&!O&&R){L.isInvisible()?g+=so:g+=A,_++;continue}_&&(m.textContent=g),m=this._document.createElement("span"),_=0,g=""}else m=this._document.createElement("span");if(y=L.bg,x=L.fg,b=L.extended.ext,w=B,S=k,C=T,D&&n>=j&&n<=P&&(n=j),!this._coreService.isCursorHidden&&I&&this._coreService.isCursorInitialized)if(N.push("xterm-cursor"),this._coreBrowserService.isFocused)o&&N.push("xterm-cursor-blink"),N.push("bar"===s?"xterm-cursor-bar":"underline"===s?"xterm-cursor-underline":"xterm-cursor-block");else if(r)switch(r){case"outline":N.push("xterm-cursor-outline");break;case"block":N.push("xterm-cursor-block");break;case"bar":N.push("xterm-cursor-bar");break;case"underline":N.push("xterm-cursor-underline")}if(L.isBold()&&N.push("xterm-bold"),L.isItalic()&&N.push("xterm-italic"),L.isDim()&&N.push("xterm-dim"),g=L.isInvisible()?so:L.getChars()||so,L.isUnderline()&&(N.push(`xterm-underline-${L.extended.underlineStyle}`)," "===g&&(g=" "),!L.isUnderlineColorDefault()))if(L.isUnderlineColorRGB())m.style.textDecorationColor=`rgb(${ro.toColorRGB(L.getUnderlineColor()).join(",")})`;else{let e=L.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&L.isBold()&&e<8&&(e+=8),m.style.textDecorationColor=f.ansi[e].css}L.isOverline()&&(N.push("xterm-overline")," "===g&&(g=" ")),L.isStrikethrough()&&N.push("xterm-strikethrough"),B&&(m.style.textDecoration="underline");let z=L.getFgColor(),$=L.getFgColorMode(),H=L.getBgColor(),W=L.getBgColorMode(),F=!!L.isInverse();if(F){let e=z;z=H,H=e;let t=$;$=W,W=t}let K,U,V,q=!1;switch(this._decorationService.forEachDecorationAtCell(j,t,void 0,e=>{"top"!==e.options.layer&&q||(e.backgroundColorRGB&&(W=50331648,H=e.backgroundColorRGB.rgba>>8&16777215,K=e.backgroundColorRGB),e.foregroundColorRGB&&($=50331648,z=e.foregroundColorRGB.rgba>>8&16777215,U=e.foregroundColorRGB),q="top"===e.options.layer)}),!q&&T&&(K=this._coreBrowserService.isFocused?f.selectionBackgroundOpaque:f.selectionInactiveBackgroundOpaque,H=K.rgba>>8&16777215,W=50331648,q=!0,f.selectionForeground&&($=50331648,z=f.selectionForeground.rgba>>8&16777215,U=f.selectionForeground)),q&&N.push("xterm-decoration-top"),W){case 16777216:case 33554432:V=f.ansi[H],N.push(`xterm-bg-${H}`);break;case 50331648:V=ac.toColor(H>>16,H>>8&255,255&H),this._addStyle(m,`background-color:#${wc((H>>>0).toString(16),"0",6)}`);break;default:F?(V=f.foreground,N.push("xterm-bg-257")):V=f.background}switch(K||L.isDim()&&(K=lc.multiplyOpacity(V,.5)),$){case 16777216:case 33554432:L.isBold()&&z<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(z+=8),this._applyMinimumContrast(m,V,f.ansi[z],L,K,void 0)||N.push(`xterm-fg-${z}`);break;case 50331648:let e=ac.toColor(z>>16&255,z>>8&255,255&z);this._applyMinimumContrast(m,V,e,L,K,U)||this._addStyle(m,`color:#${wc(z.toString(16),"0",6)}`);break;default:this._applyMinimumContrast(m,V,f.foreground,L,K,U)||F&&N.push("xterm-fg-257")}N.length&&(m.className=N.join(" "),N.length=0),I||D||O||!R?m.textContent=g:_++,k!==this.defaultSpacing&&(m.style.letterSpacing=`${k}px`),d.push(m),j=P}return m&&_&&(m.textContent=g),d}_applyMinimumContrast(e,t,i,s,r,n){if(1===this._optionsService.rawOptions.minimumContrastRatio||(function(e){return 57508<=e&&e<=57558}(o=s.getCode())||function(e){return 9472<=e&&e<=9631}(o)))return!1;var o;let a,l=this._getContrastCache(s);if(!r&&!n&&(a=l.getColor(t.rgba,i.rgba)),void 0===a){let e=this._optionsService.rawOptions.minimumContrastRatio/(s.isDim()?2:1);a=lc.ensureContrastRatio(r||t,n||i,e),l.setColor((r||t).rgba,(n||i).rgba,a??null)}return!!a&&(this._addStyle(e,`color:${a.css}`),!0)}_getContrastCache(e){return e.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(e,t){e.setAttribute("style",`${e.getAttribute("style")||""}${t};`)}_isCellInSelection(e,t){let i=this._selectionStart,s=this._selectionEnd;return!(!i||!s)&&(this._columnSelectMode?i[0]<=s[0]?e>=i[0]&&t>=i[1]&&e<s[0]&&t<=s[1]:e<i[0]&&t>=i[1]&&e>=s[0]&&t<=s[1]:t>i[1]&&t<s[1]||i[1]===s[1]&&t===i[1]&&e>=i[0]&&e<s[0]||i[1]<s[1]&&t===s[1]&&e<s[0]||i[1]<s[1]&&t===i[1]&&e>=i[0])}};function wc(e,t,i){for(;e.length<i;)e=t+e;return e}bc=Wn([Fn(1,jo),Fn(2,vo),Fn(3,ko),Fn(4,po),Fn(5,bo),Fn(6,Do)],bc);var Sc=class{constructor(e,t){this._flat=new Float32Array(256),this._font="",this._fontSize=0,this._weight="normal",this._weightBold="bold",this._measureElements=[],this._container=e.createElement("div"),this._container.classList.add("xterm-width-cache-measure-container"),this._container.setAttribute("aria-hidden","true"),this._container.style.whiteSpace="pre",this._container.style.fontKerning="none";let i=e.createElement("span");i.classList.add("xterm-char-measure-element");let s=e.createElement("span");s.classList.add("xterm-char-measure-element"),s.style.fontWeight="bold";let r=e.createElement("span");r.classList.add("xterm-char-measure-element"),r.style.fontStyle="italic";let n=e.createElement("span");n.classList.add("xterm-char-measure-element"),n.style.fontWeight="bold",n.style.fontStyle="italic",this._measureElements=[i,s,r,n],this._container.appendChild(i),this._container.appendChild(s),this._container.appendChild(r),this._container.appendChild(n),t.appendChild(this._container),this.clear()}dispose(){this._container.remove(),this._measureElements.length=0,this._holey=void 0}clear(){this._flat.fill(-9999),this._holey=new Map}setFont(e,t,i,s){e===this._font&&t===this._fontSize&&i===this._weight&&s===this._weightBold||(this._font=e,this._fontSize=t,this._weight=i,this._weightBold=s,this._container.style.fontFamily=this._font,this._container.style.fontSize=`${this._fontSize}px`,this._measureElements[0].style.fontWeight=`${i}`,this._measureElements[1].style.fontWeight=`${s}`,this._measureElements[2].style.fontWeight=`${i}`,this._measureElements[3].style.fontWeight=`${s}`,this.clear())}get(e,t,i){let s=0;if(!t&&!i&&1===e.length&&(s=e.charCodeAt(0))<256){if(-9999!==this._flat[s])return this._flat[s];let t=this._measure(e,0);return t>0&&(this._flat[s]=t),t}let r=e;t&&(r+="B"),i&&(r+="I");let n=this._holey.get(r);if(void 0===n){let s=0;t&&(s|=1),i&&(s|=2),n=this._measure(e,s),n>0&&this._holey.set(r,n)}return n}_measure(e,t){let i=this._measureElements[t];return i.textContent=e.repeat(32),i.offsetWidth/32}},Cc=class{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(e,t,i,s=!1){if(this.selectionStart=t,this.selectionEnd=i,!t||!i||t[0]===i[0]&&t[1]===i[1])return void this.clear();let r=e.buffers.active.ydisp,n=t[1]-r,o=i[1]-r,a=Math.max(n,0),l=Math.min(o,e.rows-1);a>=e.rows||l<0?this.clear():(this.hasSelection=!0,this.columnSelectMode=s,this.viewportStartRow=n,this.viewportEndRow=o,this.viewportCappedStartRow=a,this.viewportCappedEndRow=l,this.startCol=t[0],this.endCol=i[0])}isCellSelected(e,t,i){return!!this.hasSelection&&(i-=e.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?t>=this.startCol&&i>=this.viewportCappedStartRow&&t<this.endCol&&i<=this.viewportCappedEndRow:t<this.startCol&&i>=this.viewportCappedStartRow&&t>=this.endCol&&i<=this.viewportCappedEndRow:i>this.viewportStartRow&&i<this.viewportEndRow||this.viewportStartRow===this.viewportEndRow&&i===this.viewportStartRow&&t>=this.startCol&&t<this.endCol||this.viewportStartRow<this.viewportEndRow&&i===this.viewportEndRow&&t<this.endCol||this.viewportStartRow<this.viewportEndRow&&i===this.viewportStartRow&&t>=this.startCol)}};var kc="xterm-dom-renderer-owner-",Ec="xterm-rows",Nc="xterm-fg-",Mc="xterm-bg-",jc="xterm-focus",Dc="xterm-selection",Rc=1,Pc=class extends qo{constructor(e,t,i,s,r,n,o,a,l,c,h,d,u,f){super(),this._terminal=e,this._document=t,this._element=i,this._screenElement=s,this._viewportElement=r,this._helperContainer=n,this._linkifier2=o,this._charSizeService=l,this._optionsService=c,this._bufferService=h,this._coreService=d,this._coreBrowserService=u,this._themeService=f,this._terminalClass=Rc++,this._rowElements=[],this._selectionRenderModel=new Cc,this.onRequestRedraw=this._register(new da).event,this._rowContainer=this._document.createElement("div"),this._rowContainer.classList.add(Ec),this._rowContainer.style.lineHeight="normal",this._rowContainer.setAttribute("aria-hidden","true"),this._refreshRowElements(this._bufferService.cols,this._bufferService.rows),this._selectionContainer=this._document.createElement("div"),this._selectionContainer.classList.add(Dc),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions={css:{canvas:{width:0,height:0},cell:{width:0,height:0}},device:{canvas:{width:0,height:0},cell:{width:0,height:0},char:{width:0,height:0,left:0,top:0}}},this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(e=>this._injectCss(e))),this._injectCss(this._themeService.colors),this._rowFactory=a.createInstance(bc,document),this._element.classList.add(kc+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(e=>this._handleLinkHover(e))),this._register(this._linkifier2.onHideLinkUnderline(e=>this._handleLinkLeave(e))),this._register(Ko(()=>{this._element.classList.remove(kc+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new Sc(this._document,this._helperContainer),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}_updateDimensions(){let e=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*e,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*e),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.left=0,this.dimensions.device.char.top=0,this.dimensions.device.canvas.width=this.dimensions.device.cell.width*this._bufferService.cols,this.dimensions.device.canvas.height=this.dimensions.device.cell.height*this._bufferService.rows,this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/e),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/e),this.dimensions.css.cell.width=this.dimensions.css.canvas.width/this._bufferService.cols,this.dimensions.css.cell.height=this.dimensions.css.canvas.height/this._bufferService.rows;for(let i of this._rowElements)i.style.width=`${this.dimensions.css.canvas.width}px`,i.style.height=`${this.dimensions.css.cell.height}px`,i.style.lineHeight=`${this.dimensions.css.cell.height}px`,i.style.overflow="hidden";this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._dimensionsStyleElement));let t=`${this._terminalSelector} .${Ec} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=t,this._selectionContainer.style.height=this._viewportElement.style.height,this._screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._screenElement.style.height=`${this.dimensions.css.canvas.height}px`}_injectCss(e){this._themeStyleElement||(this._themeStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._themeStyleElement));let t=`${this._terminalSelector} .${Ec} { pointer-events: none; color: ${e.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;t+=`${this._terminalSelector} .${Ec} .xterm-dim { color: ${lc.multiplyOpacity(e.foreground,.5).css};}`,t+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`;let i=`blink_underline_${this._terminalClass}`,s=`blink_bar_${this._terminalClass}`,r=`blink_block_${this._terminalClass}`;t+=`@keyframes ${i} { 50% { border-bottom-style: hidden; }}`,t+=`@keyframes ${s} { 50% { box-shadow: none; }}`,t+=`@keyframes ${r} { 0% { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css}; } 50% { background-color: inherit; color: ${e.cursor.css}; }}`,t+=`${this._terminalSelector} .${Ec}.${jc} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${Ec}.${jc} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${s} 1s step-end infinite;}${this._terminalSelector} .${Ec}.${jc} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${r} 1s step-end infinite;}${this._terminalSelector} .${Ec} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${Ec} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${Ec} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${Ec} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${Ec} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${Dc} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${Dc} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${Dc} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[n,o]of e.ansi.entries())t+=`${this._terminalSelector} .${Nc}${n} { color: ${o.css}; }${this._terminalSelector} .${Nc}${n}.xterm-dim { color: ${lc.multiplyOpacity(o,.5).css}; }${this._terminalSelector} .${Mc}${n} { background-color: ${o.css}; }`;t+=`${this._terminalSelector} .${Nc}257 { color: ${lc.opaque(e.background).css}; }${this._terminalSelector} .${Nc}257.xterm-dim { color: ${lc.multiplyOpacity(lc.opaque(e.background),.5).css}; }${this._terminalSelector} .${Mc}257 { background-color: ${e.foreground.css}; }`,this._themeStyleElement.textContent=t}_setDefaultSpacing(){let e=this.dimensions.css.cell.width-this._widthCache.get("W",!1,!1);this._rowContainer.style.letterSpacing=`${e}px`,this._rowFactory.defaultSpacing=e}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(e,t){for(let i=this._rowElements.length;i<=t;i++){let e=this._document.createElement("div");this._rowContainer.appendChild(e),this._rowElements.push(e)}for(;this._rowElements.length>t;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(e,t){this._refreshRowElements(e,t),this._updateDimensions(),this.handleSelectionChanged(this._selectionRenderModel.selectionStart,this._selectionRenderModel.selectionEnd,this._selectionRenderModel.columnSelectMode)}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(jc),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(jc),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(e,t,i){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(e,t,i),this.renderRows(0,this._bufferService.rows-1),!e||!t||(this._selectionRenderModel.update(this._terminal,e,t,i),!this._selectionRenderModel.hasSelection))return;let s=this._selectionRenderModel.viewportStartRow,r=this._selectionRenderModel.viewportEndRow,n=this._selectionRenderModel.viewportCappedStartRow,o=this._selectionRenderModel.viewportCappedEndRow,a=this._document.createDocumentFragment();if(i){let i=e[0]>t[0];a.appendChild(this._createSelectionElement(n,i?t[0]:e[0],i?e[0]:t[0],o-n+1))}else{let i=s===n?e[0]:0,l=n===r?t[0]:this._bufferService.cols;a.appendChild(this._createSelectionElement(n,i,l));let c=o-n-1;if(a.appendChild(this._createSelectionElement(n+1,0,this._bufferService.cols,c)),n!==o){let e=r===o?t[0]:this._bufferService.cols;a.appendChild(this._createSelectionElement(o,0,e))}}this._selectionContainer.appendChild(a)}_createSelectionElement(e,t,i,s=1){let r=this._document.createElement("div"),n=t*this.dimensions.css.cell.width,o=this.dimensions.css.cell.width*(i-t);return n+o>this.dimensions.css.canvas.width&&(o=this.dimensions.css.canvas.width-n),r.style.height=s*this.dimensions.css.cell.height+"px",r.style.top=e*this.dimensions.css.cell.height+"px",r.style.left=`${n}px`,r.style.width=`${o}px`,r}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(let e of this._rowElements)e.replaceChildren()}renderRows(e,t){let i=this._bufferService.buffer,s=i.ybase+i.y,r=Math.min(i.x,this._bufferService.cols-1),n=this._coreService.decPrivateModes.cursorBlink??this._optionsService.rawOptions.cursorBlink,o=this._coreService.decPrivateModes.cursorStyle??this._optionsService.rawOptions.cursorStyle,a=this._optionsService.rawOptions.cursorInactiveStyle;for(let l=e;l<=t;l++){let e=l+i.ydisp,t=this._rowElements[l],c=i.lines.get(e);if(!t||!c)break;t.replaceChildren(...this._rowFactory.createRow(c,e,e===s,o,a,r,n,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${kc}${this._terminalClass}`}_handleLinkHover(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!0)}_handleLinkLeave(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!1)}_setCellUnderline(e,t,i,s,r,n){i<0&&(e=0),s<0&&(t=0);let o=this._bufferService.rows-1;i=Math.max(Math.min(i,o),0),s=Math.max(Math.min(s,o),0),r=Math.min(r,this._bufferService.cols);let a=this._bufferService.buffer,l=a.ybase+a.y,c=Math.min(a.x,r-1),h=this._optionsService.rawOptions.cursorBlink,d=this._optionsService.rawOptions.cursorStyle,u=this._optionsService.rawOptions.cursorInactiveStyle;for(let f=i;f<=s;++f){let o=f+a.ydisp,p=this._rowElements[f],m=a.lines.get(o);if(!p||!m)break;p.replaceChildren(...this._rowFactory.createRow(m,o,o===l,d,u,c,h,this.dimensions.css.cell.width,this._widthCache,n?f===i?e:0:-1,n?(f===s?t:r)-1:-1))}}};Pc=Wn([Fn(7,_o),Fn(8,Co),Fn(9,vo),Fn(10,uo),Fn(11,po),Fn(12,ko),Fn(13,Do)],Pc);var Lc=class extends qo{constructor(e,t,i){super(),this._optionsService=i,this.width=0,this.height=0,this._onCharSizeChange=this._register(new da),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new Bc(this._optionsService))}catch{this._measureStrategy=this._register(new Ic(e,t,this._optionsService))}this._register(this._optionsService.onMultipleOptionChange(["fontFamily","fontSize"],()=>this.measure()))}get hasValidSize(){return this.width>0&&this.height>0}measure(){let e=this._measureStrategy.measure();(e.width!==this.width||e.height!==this.height)&&(this.width=e.width,this.height=e.height,this._onCharSizeChange.fire())}};Lc=Wn([Fn(2,vo)],Lc);var Tc=class extends qo{constructor(){super(...arguments),this._result={width:0,height:0}}_validateAndSet(e,t){void 0!==e&&e>0&&void 0!==t&&t>0&&(this._result.width=e,this._result.height=t)}},Ic=class extends Tc{constructor(e,t,i){super(),this._document=e,this._parentElement=t,this._optionsService=i,this._measureElement=this._document.createElement("span"),this._measureElement.classList.add("xterm-char-measure-element"),this._measureElement.textContent="W".repeat(32),this._measureElement.setAttribute("aria-hidden","true"),this._measureElement.style.whiteSpace="pre",this._measureElement.style.fontKerning="none",this._parentElement.appendChild(this._measureElement)}measure(){return this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}px`,this._validateAndSet(Number(this._measureElement.offsetWidth)/32,Number(this._measureElement.offsetHeight)),this._result}},Bc=class extends Tc{constructor(e){super(),this._optionsService=e,this._canvas=new OffscreenCanvas(100,100),this._ctx=this._canvas.getContext("2d");let t=this._ctx.measureText("W");if(!("width"in t&&"fontBoundingBoxAscent"in t&&"fontBoundingBoxDescent"in t))throw new Error("Required font metrics not supported")}measure(){this._ctx.font=`${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;let e=this._ctx.measureText("W");return this._validateAndSet(e.width,e.fontBoundingBoxAscent+e.fontBoundingBoxDescent),this._result}},Oc=class extends qo{constructor(e,t,i){super(),this._textarea=e,this._window=t,this.mainDocument=i,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=this._register(new Ac(this._window)),this._onDprChange=this._register(new da),this.onDprChange=this._onDprChange.event,this._onWindowChange=this._register(new da),this.onWindowChange=this._onWindowChange.event,this._register(this.onWindowChange(e=>this._screenDprMonitor.setWindow(e))),this._register(Zo.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(gl(this._textarea,"focus",()=>this._isFocused=!0)),this._register(gl(this._textarea,"blur",()=>this._isFocused=!1))}get window(){return this._window}set window(e){this._window!==e&&(this._window=e,this._onWindowChange.fire(this._window))}get dpr(){return this.window.devicePixelRatio}get isFocused(){return void 0===this._cachedIsFocused&&(this._cachedIsFocused=this._isFocused&&this._textarea.ownerDocument.hasFocus(),queueMicrotask(()=>this._cachedIsFocused=void 0)),this._cachedIsFocused}},Ac=class extends qo{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new Yo),this._onDprChange=this._register(new da),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register(Ko(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=gl(this._parentWindow,"resize",()=>this._setDprAndFireIfDiffers())}_setDprAndFireIfDiffers(){this._parentWindow.devicePixelRatio!==this._currentDevicePixelRatio&&this._onDprChange.fire(this._parentWindow.devicePixelRatio),this._updateDpr()}_updateDpr(){var e;this._outerListener&&(null==(e=this._resolutionMediaMatchList)||e.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){!this._resolutionMediaMatchList||!this._outerListener||(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._outerListener=void 0)}},zc=class extends qo{constructor(){super(),this.linkProviders=[],this._register(Ko(()=>this.linkProviders.length=0))}registerLinkProvider(e){return this.linkProviders.push(e),{dispose:()=>{let t=this.linkProviders.indexOf(e);-1!==t&&this.linkProviders.splice(t,1)}}}};function $c(e,t,i){let s=i.getBoundingClientRect(),r=e.getComputedStyle(i),n=parseInt(r.getPropertyValue("padding-left")),o=parseInt(r.getPropertyValue("padding-top"));return[t.clientX-s.left-n,t.clientY-s.top-o]}var Hc=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,i,s,r){return function(e,t,i,s,r,n,o,a,l){if(!n)return;let c=$c(e,t,i);return c?(c[0]=Math.ceil((c[0]+(l?o/2:0))/o),c[1]=Math.ceil(c[1]/a),c[0]=Math.min(Math.max(c[0],1),s+(l?1:0)),c[1]=Math.min(Math.max(c[1],1),r),c):void 0}(window,e,t,i,s,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,r)}getMouseReportCoords(e,t){let i=$c(window,e,t);if(this._charSizeService.hasValidSize)return i[0]=Math.min(Math.max(i[0],0),this._renderService.dimensions.css.canvas.width-1),i[1]=Math.min(Math.max(i[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(i[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(i[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(i[0]),y:Math.floor(i[1])}}};Hc=Wn([Fn(0,No),Fn(1,Co)],Hc);var Wc=class{constructor(e,t){this._renderCallback=e,this._coreBrowserService=t,this._refreshCallbacks=[]}dispose(){this._animationFrame&&(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0)}addRefreshCallback(e){return this._refreshCallbacks.push(e),this._animationFrame||(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh())),this._animationFrame}refresh(e,t,i){this._rowCount=i,e=void 0!==e?e:0,t=void 0!==t?t:this._rowCount-1,this._rowStart=void 0!==this._rowStart?Math.min(this._rowStart,e):e,this._rowEnd=void 0!==this._rowEnd?Math.max(this._rowEnd,t):t,!this._animationFrame&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()))}_innerRefresh(){if(this._animationFrame=void 0,void 0===this._rowStart||void 0===this._rowEnd||void 0===this._rowCount)return void this._runRefreshCallbacks();let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(let e of this._refreshCallbacks)e(0);this._refreshCallbacks=[]}},Fc={};((e,t)=>{for(var i in t)$n(e,i,{get:t[i],enumerable:!0})})(Fc,{getSafariVersion:()=>Gc,isChromeOS:()=>ih,isFirefox:()=>qc,isIpad:()=>Jc,isIphone:()=>Qc,isLegacyEdge:()=>Yc,isLinux:()=>th,isMac:()=>Zc,isNode:()=>Kc,isSafari:()=>Xc,isWindows:()=>eh});var Kc=typeof process<"u"&&"title"in process,Uc=Kc?"node":navigator.userAgent,Vc=Kc?"node":navigator.platform,qc=Uc.includes("Firefox"),Yc=Uc.includes("Edge"),Xc=/^((?!chrome|android).)*safari/i.test(Uc);function Gc(){if(!Xc)return 0;let e=Uc.match(/Version\/(\d+)/);return null===e||e.length<2?0:parseInt(e[1])}var Zc=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(Vc),Jc="iPad"===Vc,Qc="iPhone"===Vc,eh=["Windows","Win16","Win32","WinCE"].includes(Vc),th=Vc.indexOf("Linux")>=0,ih=/\bCrOS\b/.test(Uc),sh=class{constructor(){this._tasks=[],this._i=0}enqueue(e){this._tasks.push(e),this._start()}flush(){for(;this._i<this._tasks.length;)this._tasks[this._i]()||this._i++;this.clear()}clear(){this._idleCallback&&(this._cancelCallback(this._idleCallback),this._idleCallback=void 0),this._i=0,this._tasks.length=0}_start(){this._idleCallback||(this._idleCallback=this._requestCallback(this._process.bind(this)))}_process(e){this._idleCallback=void 0;let t=0,i=0,s=e.timeRemaining(),r=0;for(;this._i<this._tasks.length;){if(t=performance.now(),this._tasks[this._i]()||this._i++,t=Math.max(1,performance.now()-t),i=Math.max(t,i),r=e.timeRemaining(),1.5*i>r)return s-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(s-t))}ms`),void this._start();s=r}this.clear()}},rh=!Kc&&"requestIdleCallback"in window?class extends sh{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}}:class extends sh{_requestCallback(e){return setTimeout(()=>e(this._createDeadline(16)))}_cancelCallback(e){clearTimeout(e)}_createDeadline(e){let t=performance.now()+e;return{timeRemaining:()=>Math.max(0,t-performance.now())}}},nh=class{constructor(){this._queue=new rh}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},oh=class extends qo{constructor(e,t,i,s,r,n,o,a,l){super(),this._rowCount=e,this._optionsService=i,this._charSizeService=s,this._coreService=r,this._coreBrowserService=a,this._renderer=this._register(new Yo),this._pausedResizeTask=new nh,this._observerDisposable=this._register(new Yo),this._isPaused=!1,this._needsFullRefresh=!1,this._isNextRenderRedrawOnly=!0,this._needsSelectionRefresh=!1,this._canvasWidth=0,this._canvasHeight=0,this._selectionState={start:void 0,end:void 0,columnSelectMode:!1},this._onDimensionsChange=this._register(new da),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this._register(new da),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this._register(new da),this.onRender=this._onRender.event,this._onRefreshRequest=this._register(new da),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new Wc((e,t)=>this._renderRows(e,t),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new ah(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register(Ko(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(o.onResize(()=>this._fullRefresh())),this._register(o.buffers.onBufferActivate(()=>{var e;return null==(e=this._renderer.value)?void 0:e.clear()})),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._charSizeService.onCharSizeChange(()=>this.handleCharSizeChanged())),this._register(n.onDecorationRegistered(()=>this._fullRefresh())),this._register(n.onDecorationRemoved(()=>this._fullRefresh())),this._register(this._optionsService.onMultipleOptionChange(["customGlyphs","drawBoldTextInBrightColors","letterSpacing","lineHeight","fontFamily","fontSize","fontWeight","fontWeightBold","minimumContrastRatio","rescaleOverlappingGlyphs"],()=>{this.clear(),this.handleResize(o.cols,o.rows),this._fullRefresh()})),this._register(this._optionsService.onMultipleOptionChange(["cursorBlink","cursorStyle"],()=>this.refreshRows(o.buffer.y,o.buffer.y,!0))),this._register(l.onChangeColors(()=>this._fullRefresh())),this._registerIntersectionObserver(this._coreBrowserService.window,t),this._register(this._coreBrowserService.onWindowChange(e=>this._registerIntersectionObserver(e,t)))}get dimensions(){return this._renderer.value.dimensions}_registerIntersectionObserver(e,t){if("IntersectionObserver"in e){let i=new e.IntersectionObserver(e=>this._handleIntersectionChange(e[e.length-1]),{threshold:0});i.observe(t),this._observerDisposable.value=Ko(()=>i.disconnect())}}_handleIntersectionChange(e){this._isPaused=void 0===e.isIntersecting?0===e.intersectionRatio:!e.isIntersecting,!this._isPaused&&!this._charSizeService.hasValidSize&&this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(e,t,i=!1){if(this._isPaused)return void(this._needsFullRefresh=!0);if(this._coreService.decPrivateModes.synchronizedOutput)return void this._syncOutputHandler.bufferRows(e,t);let s=this._syncOutputHandler.flush();s&&(e=Math.min(e,s.start),t=Math.max(t,s.end)),i||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(e,t,this._rowCount)}_renderRows(e,t){if(this._renderer.value){if(this._coreService.decPrivateModes.synchronizedOutput)return void this._syncOutputHandler.bufferRows(e,t);e=Math.min(e,this._rowCount-1),t=Math.min(t,this._rowCount-1),this._renderer.value.renderRows(e,t),this._needsSelectionRefresh&&(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),this._needsSelectionRefresh=!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:e,end:t}),this._onRender.fire({start:e,end:t}),this._isNextRenderRedrawOnly=!0}}resize(e,t){this._rowCount=t,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(e){this._renderer.value=e,this._renderer.value&&(this._renderer.value.onRequestRedraw(e=>this.refreshRows(e.start,e.end,!0)),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(e){return this._renderDebouncer.addRefreshCallback(e)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){var e,t;this._renderer.value&&(null==(t=(e=this._renderer.value).clearTextureAtlas)||t.call(e),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(e,t){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set(()=>{var i;return null==(i=this._renderer.value)?void 0:i.handleResize(e,t)}):this._renderer.value.handleResize(e,t),this._fullRefresh())}handleCharSizeChanged(){var e;null==(e=this._renderer.value)||e.handleCharSizeChanged()}handleBlur(){var e;null==(e=this._renderer.value)||e.handleBlur()}handleFocus(){var e;null==(e=this._renderer.value)||e.handleFocus()}handleSelectionChanged(e,t,i){var s;this._selectionState.start=e,this._selectionState.end=t,this._selectionState.columnSelectMode=i,null==(s=this._renderer.value)||s.handleSelectionChanged(e,t,i)}handleCursorMove(){var e;null==(e=this._renderer.value)||e.handleCursorMove()}clear(){var e;null==(e=this._renderer.value)||e.clear()}};oh=Wn([Fn(2,vo),Fn(3,Co),Fn(4,po),Fn(5,bo),Fn(6,uo),Fn(7,ko),Fn(8,Do)],oh);var ah=class{constructor(e,t,i){this._coreBrowserService=e,this._coreService=t,this._onTimeout=i,this._start=0,this._end=0,this._isBuffering=!1}bufferRows(e,t){this._isBuffering?(this._start=Math.min(this._start,e),this._end=Math.max(this._end,t)):(this._start=e,this._end=t,this._isBuffering=!0),void 0===this._timeout&&(this._timeout=this._coreBrowserService.window.setTimeout(()=>{this._timeout=void 0,this._coreService.decPrivateModes.synchronizedOutput=!1,this._onTimeout()},1e3))}flush(){if(void 0!==this._timeout&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0),!this._isBuffering)return;let e={start:this._start,end:this._end};return this._isBuffering=!1,e}dispose(){void 0!==this._timeout&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0)}};function lh(e,t,i,s){let r,n=i.buffer.x,o=i.buffer.y;if(!i.buffer.hasScrollback)return function(e,t,i,s,r,n){return 0===ch(t,s,r,n).length?"":ph(uh(e,t,e,t-hh(t,r),!1,r).length,fh("D",n))}(n,o,0,t,i,s)+ch(o,t,i,s)+function(e,t,i,s,r,n){let o;o=ch(t,s,r,n).length>0?s-hh(s,r):t;let a=s,l=function(e,t,i,s,r,n){let o;return o=ch(i,s,r,n).length>0?s-hh(s,r):t,e<i&&o<=s||e>=i&&o<s?"C":"D"}(e,t,i,s,r,n);return ph(uh(e,o,i,a,"C"===l,r).length,fh(l,n))}(n,o,e,t,i,s);if(o===t)return r=n>e?"D":"C",ph(Math.abs(n-e),fh(r,s));r=o>t?"D":"C";let a=Math.abs(o-t),l=function(e,t){return t.cols-e}(o>t?e:n,i)+(a-1)*i.cols+1+function(e){return e-1}(o>t?n:e);return ph(l,fh(r,s))}function ch(e,t,i,s){let r=e-hh(e,i),n=t-hh(t,i),o=Math.abs(r-n)-function(e,t,i){var s;let r=0,n=e-hh(e,i),o=t-hh(t,i);for(let a=0;a<Math.abs(n-o);a++){let o="A"===dh(e,t)?-1:1;(null==(s=i.buffer.lines.get(n+o*a))?void 0:s.isWrapped)&&r++}return r}(e,t,i);return ph(o,fh(dh(e,t),s))}function hh(e,t){let i=0,s=t.buffer.lines.get(e),r=null==s?void 0:s.isWrapped;for(;r&&e>=0&&e<t.rows;)i++,s=t.buffer.lines.get(--e),r=null==s?void 0:s.isWrapped;return i}function dh(e,t){return e>t?"A":"B"}function uh(e,t,i,s,r,n){let o=e,a=t,l="";for(;(o!==i||a!==s)&&a>=0&&a<n.buffer.lines.length;)o+=r?1:-1,r&&o>n.cols-1?(l+=n.buffer.translateBufferLineToString(a,!1,e,o),o=0,e=0,a++):!r&&o<0&&(l+=n.buffer.translateBufferLineToString(a,!1,0,e+1),o=n.cols-1,e=o,a--);return l+n.buffer.translateBufferLineToString(a,!1,e,o)}function fh(e,t){let i=t?"O":"[";return Gl.ESC+i+e}function ph(e,t){e=Math.floor(e);let i="";for(let s=0;s<e;s++)i+=t;return i}var mh=class{constructor(e){this._bufferService=e,this.isSelectAllActive=!1,this.selectionStartLength=0}clearSelection(){this.selectionStart=void 0,this.selectionEnd=void 0,this.isSelectAllActive=!1,this.selectionStartLength=0}get finalSelectionStart(){return this.isSelectAllActive?[0,0]:this.selectionEnd&&this.selectionStart&&this.areSelectionValuesReversed()?this.selectionEnd:this.selectionStart}get finalSelectionEnd(){if(this.isSelectAllActive)return[this._bufferService.cols,this._bufferService.buffer.ybase+this._bufferService.rows-1];if(this.selectionStart){if(!this.selectionEnd||this.areSelectionValuesReversed()){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?e%this._bufferService.cols===0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)-1]:[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[e,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[Math.max(e,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){let e=this.selectionStart,t=this.selectionEnd;return!(!e||!t)&&(e[1]>t[1]||e[1]===t[1]&&e[0]>t[0])}handleTrim(e){return this.selectionStart&&(this.selectionStart[1]-=e),this.selectionEnd&&(this.selectionEnd[1]-=e),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}};function _h(e,t){if(e.start.y>e.end.y)throw new Error(`Buffer range end (${e.end.x}, ${e.end.y}) cannot be before start (${e.start.x}, ${e.start.y})`);return t*(e.end.y-e.start.y)+(e.end.x-e.start.x+1)}var gh=new RegExp(" ","g"),vh=class extends qo{constructor(e,t,i,s,r,n,o,a,l){super(),this._element=e,this._screenElement=t,this._linkifier=i,this._bufferService=s,this._coreService=r,this._mouseService=n,this._optionsService=o,this._renderService=a,this._coreBrowserService=l,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new oo,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this._register(new da),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this._register(new da),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this._register(new da),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this._register(new da),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=e=>this._handleMouseMove(e),this._mouseUpListener=e=>this._handleMouseUp(e),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(e=>this._handleTrim(e)),this._register(this._bufferService.buffers.onBufferActivate(e=>this._handleBufferActivate(e))),this.enable(),this._model=new mh(this._bufferService),this._activeSelectionMode=0,this._register(Ko(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(e=>{e.rowsChanged&&this.clearSelection()}))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;return!(!e||!t)&&(e[0]!==t[0]||e[1]!==t[1])}get selectionText(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;if(!e||!t)return"";let i=this._bufferService.buffer,s=[];if(3===this._activeSelectionMode){if(e[0]===t[0])return"";let r=e[0]<t[0]?e[0]:t[0],n=e[0]<t[0]?t[0]:e[0];for(let o=e[1];o<=t[1];o++){let e=i.translateBufferLineToString(o,!0,r,n);s.push(e)}}else{let r=e[1]===t[1]?t[0]:void 0;s.push(i.translateBufferLineToString(e[1],!0,e[0],r));for(let n=e[1]+1;n<=t[1]-1;n++){let e=i.lines.get(n),t=i.translateBufferLineToString(n,!0);(null==e?void 0:e.isWrapped)?s[s.length-1]+=t:s.push(t)}if(e[1]!==t[1]){let e=i.lines.get(t[1]),r=i.translateBufferLineToString(t[1],!0,0,t[0]);e&&e.isWrapped?s[s.length-1]+=r:s.push(r)}}return s.map(e=>e.replace(gh," ")).join(eh?"\r\n":"\n")}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),th&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:3===this._activeSelectionMode})}_isClickInSelection(e){let t=this._getMouseBufferCoords(e),i=this._model.finalSelectionStart,s=this._model.finalSelectionEnd;return!!(i&&s&&t)&&this._areCoordsInSelection(t,i,s)}isCellInSelection(e,t){let i=this._model.finalSelectionStart,s=this._model.finalSelectionEnd;return!(!i||!s)&&this._areCoordsInSelection([e,t],i,s)}_areCoordsInSelection(e,t,i){return e[1]>t[1]&&e[1]<i[1]||t[1]===i[1]&&e[1]===t[1]&&e[0]>=t[0]&&e[0]<i[0]||t[1]<i[1]&&e[1]===i[1]&&e[0]<i[0]||t[1]<i[1]&&e[1]===t[1]&&e[0]>=t[0]}_selectWordAtCursor(e,t){var i,s;let r=null==(s=null==(i=this._linkifier.currentLink)?void 0:i.link)?void 0:s.range;if(r)return this._model.selectionStart=[r.start.x-1,r.start.y-1],this._model.selectionStartLength=_h(r,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let n=this._getMouseBufferCoords(e);return!!n&&(this._selectWordAt(n,t),this._model.selectionEnd=void 0,!0)}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=$c(this._coreBrowserService.window,e,this._screenElement)[1],i=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=i?0:(t>i&&(t-=i),t=Math.min(Math.max(t,-50),50),t/=50,t/Math.abs(t)+Math.round(14*t))}shouldForceSelection(e){return Zc?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,(2!==e.button||!this.hasSelection)&&0===e.button){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):1===e.detail?this._handleSingleClick(e):2===e.detail?this._handleDoubleClick(e):3===e.detail&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener("mouseup",this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),50)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener("mouseup",this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&0===t.hasWidth(this._model.selectionStart[0])&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(Zc&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd)return void this.refresh(!0);2===this._activeSelectionMode?this._model.selectionEnd[1]<this._model.selectionStart[1]?this._model.selectionEnd[0]=0:this._model.selectionEnd[0]=this._bufferService.cols:1===this._activeSelectionMode&&this._selectToWordAt(this._model.selectionEnd),this._dragScrollAmount=this._getMouseEventScrollAmount(e),3!==this._activeSelectionMode&&(this._dragScrollAmount>0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));let i=this._bufferService.buffer;if(this._model.selectionEnd[1]<i.lines.length){let e=i.lines.get(this._model.selectionEnd[1]);e&&0===e.hasWidth(this._model.selectionEnd[0])&&this._model.selectionEnd[0]<this._bufferService.cols&&this._model.selectionEnd[0]++}(!t||t[0]!==this._model.selectionEnd[0]||t[1]!==this._model.selectionEnd[1])&&this.refresh(!0)}_dragScroll(){if(this._model.selectionEnd&&this._model.selectionStart&&this._dragScrollAmount){this._onRequestScrollLines.fire({amount:this._dragScrollAmount,suppressScrollEvent:!1});let e=this._bufferService.buffer;this._dragScrollAmount>0?(3!==this._activeSelectionMode&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(3!==this._activeSelectionMode&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}}_handleMouseUp(e){let t=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&t<500&&e.altKey&&this._optionsService.rawOptions.altClickMovesCursor){if(this._bufferService.buffer.ybase===this._bufferService.buffer.ydisp){let t=this._mouseService.getCoords(e,this._element,this._bufferService.cols,this._bufferService.rows,!1);if(t&&void 0!==t[0]&&void 0!==t[1]){let e=lh(t[0]-1,t[1]-1,this._bufferService,this._coreService.decPrivateModes.applicationCursorKeys);this._coreService.triggerDataEvent(e,!0)}}}else this._fireEventIfSelectionChanged()}_fireEventIfSelectionChanged(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd,i=!(!e||!t||e[0]===t[0]&&e[1]===t[1]);i?!e||!t||(!this._oldSelectionStart||!this._oldSelectionEnd||e[0]!==this._oldSelectionStart[0]||e[1]!==this._oldSelectionStart[1]||t[0]!==this._oldSelectionEnd[0]||t[1]!==this._oldSelectionEnd[1])&&this._fireOnSelectionChange(e,t,i):this._oldHasSelection&&this._fireOnSelectionChange(e,t,i)}_fireOnSelectionChange(e,t,i){this._oldSelectionStart=e,this._oldSelectionEnd=t,this._oldHasSelection=i,this._onSelectionChange.fire()}_handleBufferActivate(e){this.clearSelection(),this._trimListener.dispose(),this._trimListener=e.activeBuffer.lines.onTrim(e=>this._handleTrim(e))}_convertViewportColToCharacterIndex(e,t){let i=t;for(let s=0;t>=s;s++){let r=e.loadCell(s,this._workCell).getChars().length;0===this._workCell.getWidth()?i--:r>1&&t!==s&&(i+=r-1)}return i}setSelection(e,t,i){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=i,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,t,i=!0,s=!0){if(e[0]>=this._bufferService.cols)return;let r=this._bufferService.buffer,n=r.lines.get(e[1]);if(!n)return;let o=r.translateBufferLineToString(e[1],!1),a=this._convertViewportColToCharacterIndex(n,e[0]),l=a,c=e[0]-a,h=0,d=0,u=0,f=0;if(" "===o.charAt(a)){for(;a>0&&" "===o.charAt(a-1);)a--;for(;l<o.length&&" "===o.charAt(l+1);)l++}else{let t=e[0],i=e[0];0===n.getWidth(t)&&(h++,t--),2===n.getWidth(i)&&(d++,i++);let s=n.getString(i).length;for(s>1&&(f+=s-1,l+=s-1);t>0&&a>0&&!this._isCharWordSeparator(n.loadCell(t-1,this._workCell));){n.loadCell(t-1,this._workCell);let e=this._workCell.getChars().length;0===this._workCell.getWidth()?(h++,t--):e>1&&(u+=e-1,a-=e-1),a--,t--}for(;i<n.length&&l+1<o.length&&!this._isCharWordSeparator(n.loadCell(i+1,this._workCell));){n.loadCell(i+1,this._workCell);let e=this._workCell.getChars().length;2===this._workCell.getWidth()?(d++,i++):e>1&&(f+=e-1,l+=e-1),l++,i++}}l++;let p=a+c-h+u,m=Math.min(this._bufferService.cols,l-a+h+d-u-f);if(t||""!==o.slice(a,l).trim()){if(i&&0===p&&32!==n.getCodePoint(0)){let t=r.lines.get(e[1]-1);if(t&&n.isWrapped&&32!==t.getCodePoint(this._bufferService.cols-1)){let t=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(t){let e=this._bufferService.cols-t.start;p-=e,m+=e}}}if(s&&p+m===this._bufferService.cols&&32!==n.getCodePoint(this._bufferService.cols-1)){let t=r.lines.get(e[1]+1);if((null==t?void 0:t.isWrapped)&&32!==t.getCodePoint(0)){let t=this._getWordAt([0,e[1]+1],!1,!1,!0);t&&(m+=t.length)}}return{start:p,length:m}}}_selectWordAt(e,t){let i=this._getWordAt(e,t);if(i){for(;i.start<0;)i.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[i.start,e[1]],this._model.selectionStartLength=i.length}}_selectToWordAt(e){let t=this._getWordAt(e,!0);if(t){let i=e[1];for(;t.start<0;)t.start+=this._bufferService.cols,i--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,i++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,i]}}_isCharWordSeparator(e){return 0!==e.getWidth()&&this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){let t=this._bufferService.buffer.getWrappedRangeForLine(e),i={start:{x:0,y:t.first},end:{x:this._bufferService.cols-1,y:t.last}};this._model.selectionStart=[0,t.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=_h(i,this._bufferService.cols)}};vh=Wn([Fn(3,uo),Fn(4,po),Fn(5,Eo),Fn(6,vo),Fn(7,No),Fn(8,ko)],vh);var yh=class{constructor(){this._data={}}set(e,t,i){this._data[e]||(this._data[e]={}),this._data[e][t]=i}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}},xh=class{constructor(){this._color=new yh,this._css=new yh}setCss(e,t,i){this._css.set(e,t,i)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,i){this._color.set(e,t,i)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}},bh=Object.freeze((()=>{let e=[cc.toColor("#2e3436"),cc.toColor("#cc0000"),cc.toColor("#4e9a06"),cc.toColor("#c4a000"),cc.toColor("#3465a4"),cc.toColor("#75507b"),cc.toColor("#06989a"),cc.toColor("#d3d7cf"),cc.toColor("#555753"),cc.toColor("#ef2929"),cc.toColor("#8ae234"),cc.toColor("#fce94f"),cc.toColor("#729fcf"),cc.toColor("#ad7fa8"),cc.toColor("#34e2e2"),cc.toColor("#eeeeec")],t=[0,95,135,175,215,255];for(let i=0;i<216;i++){let s=t[i/36%6|0],r=t[i/6%6|0],n=t[i%6];e.push({css:ac.toCss(s,r,n),rgba:ac.toRgba(s,r,n)})}for(let i=0;i<24;i++){let t=8+10*i;e.push({css:ac.toCss(t,t,t),rgba:ac.toRgba(t,t,t)})}return e})()),wh=cc.toColor("#ffffff"),Sh=cc.toColor("#000000"),Ch=cc.toColor("#ffffff"),kh=Sh,Eh={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117},Nh=wh,Mh=class extends qo{constructor(e){super(),this._optionsService=e,this._contrastCache=new xh,this._halfContrastCache=new xh,this._onChangeColors=this._register(new da),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:wh,background:Sh,cursor:Ch,cursorAccent:kh,selectionForeground:void 0,selectionBackgroundTransparent:Eh,selectionBackgroundOpaque:lc.blend(Sh,Eh),selectionInactiveBackgroundTransparent:Eh,selectionInactiveBackgroundOpaque:lc.blend(Sh,Eh),scrollbarSliderBackground:lc.opacity(wh,.2),scrollbarSliderHoverBackground:lc.opacity(wh,.4),scrollbarSliderActiveBackground:lc.opacity(wh,.5),overviewRulerBorder:wh,ansi:bh.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this._register(this._optionsService.onSpecificOptionChange("minimumContrastRatio",()=>this._contrastCache.clear())),this._register(this._optionsService.onSpecificOptionChange("theme",()=>this._setTheme(this._optionsService.rawOptions.theme)))}get colors(){return this._colors}_setTheme(e={}){let t=this._colors;if(t.foreground=jh(e.foreground,wh),t.background=jh(e.background,Sh),t.cursor=lc.blend(t.background,jh(e.cursor,Ch)),t.cursorAccent=lc.blend(t.background,jh(e.cursorAccent,kh)),t.selectionBackgroundTransparent=jh(e.selectionBackground,Eh),t.selectionBackgroundOpaque=lc.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=jh(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=lc.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?jh(e.selectionForeground,_c):void 0,t.selectionForeground===_c&&(t.selectionForeground=void 0),lc.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=lc.opacity(t.selectionBackgroundTransparent,.3)),lc.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=lc.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=jh(e.scrollbarSliderBackground,lc.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=jh(e.scrollbarSliderHoverBackground,lc.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=jh(e.scrollbarSliderActiveBackground,lc.opacity(t.foreground,.5)),t.overviewRulerBorder=jh(e.overviewRulerBorder,Nh),t.ansi=bh.slice(),t.ansi[0]=jh(e.black,bh[0]),t.ansi[1]=jh(e.red,bh[1]),t.ansi[2]=jh(e.green,bh[2]),t.ansi[3]=jh(e.yellow,bh[3]),t.ansi[4]=jh(e.blue,bh[4]),t.ansi[5]=jh(e.magenta,bh[5]),t.ansi[6]=jh(e.cyan,bh[6]),t.ansi[7]=jh(e.white,bh[7]),t.ansi[8]=jh(e.brightBlack,bh[8]),t.ansi[9]=jh(e.brightRed,bh[9]),t.ansi[10]=jh(e.brightGreen,bh[10]),t.ansi[11]=jh(e.brightYellow,bh[11]),t.ansi[12]=jh(e.brightBlue,bh[12]),t.ansi[13]=jh(e.brightMagenta,bh[13]),t.ansi[14]=jh(e.brightCyan,bh[14]),t.ansi[15]=jh(e.brightWhite,bh[15]),e.extendedAnsi){let i=Math.min(t.ansi.length-16,e.extendedAnsi.length);for(let s=0;s<i;s++)t.ansi[s+16]=jh(e.extendedAnsi[s],bh[s+16])}this._contrastCache.clear(),this._halfContrastCache.clear(),this._updateRestoreColors(),this._onChangeColors.fire(this.colors)}restoreColor(e){this._restoreColor(e),this._onChangeColors.fire(this.colors)}_restoreColor(e){if(void 0!==e)switch(e){case 256:this._colors.foreground=this._restoreColors.foreground;break;case 257:this._colors.background=this._restoreColors.background;break;case 258:this._colors.cursor=this._restoreColors.cursor;break;default:this._colors.ansi[e]=this._restoreColors.ansi[e]}else for(let t=0;t<this._restoreColors.ansi.length;++t)this._colors.ansi[t]=this._restoreColors.ansi[t]}modifyColors(e){e(this._colors),this._onChangeColors.fire(this.colors)}_updateRestoreColors(){this._restoreColors={foreground:this._colors.foreground,background:this._colors.background,cursor:this._colors.cursor,ansi:this._colors.ansi.slice()}}};function jh(e,t){if(void 0!==e)try{return cc.toColor(e)}catch{}return t}Mh=Wn([Fn(0,vo)],Mh);var Dh=class{constructor(...e){this._entries=new Map;for(let[t,i]of e)this.set(t,i)}set(e,t){let i=this._entries.get(e);return this._entries.set(e,t),i}forEach(e){for(let[t,i]of this._entries.entries())e(t,i)}has(e){return this._entries.has(e)}get(e){return this._entries.get(e)}},Rh=class{constructor(){this._services=new Dh,this._services.set(_o,this)}setService(e,t){this._services.set(e,t)}getService(e){return this._services.get(e)}createInstance(e,...t){let i=(r=e,r[lo]||[]).sort((e,t)=>e.index-t.index),s=[];var r;for(let o of i){let t=this._services.get(o.id);if(!t)throw new Error(`[createInstance] ${e.name} depends on UNKNOWN service ${o.id._id}.`);s.push(t)}let n=i.length>0?i[0].index:t.length;if(t.length!==n)throw new Error(`[createInstance] First service dependency of ${e.name} at position ${n+1} conflicts with ${t.length} static arguments`);return new e(...t,...s)}},Ph={trace:0,debug:1,info:2,warn:3,error:4,off:5},Lh=class extends qo{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange("logLevel",()=>this._updateLogLevel()))}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=Ph[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let t=0;t<e.length;t++)"function"==typeof e[t]&&(e[t]=e[t]())}_log(e,t,i){this._evalLazyOptionalParams(i),e.call(console,(this._optionsService.options.logger?"":"xterm.js: ")+t,...i)}trace(e,...t){var i;this._logLevel<=0&&this._log((null==(i=this._optionsService.options.logger)?void 0:i.trace.bind(this._optionsService.options.logger))??console.log,e,t)}debug(e,...t){var i;this._logLevel<=1&&this._log((null==(i=this._optionsService.options.logger)?void 0:i.debug.bind(this._optionsService.options.logger))??console.log,e,t)}info(e,...t){var i;this._logLevel<=2&&this._log((null==(i=this._optionsService.options.logger)?void 0:i.info.bind(this._optionsService.options.logger))??console.info,e,t)}warn(e,...t){var i;this._logLevel<=3&&this._log((null==(i=this._optionsService.options.logger)?void 0:i.warn.bind(this._optionsService.options.logger))??console.warn,e,t)}error(e,...t){var i;this._logLevel<=4&&this._log((null==(i=this._optionsService.options.logger)?void 0:i.error.bind(this._optionsService.options.logger))??console.error,e,t)}};Lh=Wn([Fn(0,vo)],Lh);var Th=class extends qo{constructor(e){super(),this._maxLength=e,this.onDeleteEmitter=this._register(new da),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this._register(new da),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this._register(new da),this.onTrim=this.onTrimEmitter.event,this._array=new Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(e){if(this._maxLength===e)return;let t=new Array(e);for(let i=0;i<Math.min(e,this.length);i++)t[i]=this._array[this._getCyclicIndex(i)];this._array=t,this._maxLength=e,this._startIndex=0}get length(){return this._length}set length(e){if(e>this._length)for(let t=this._length;t<e;t++)this._array[t]=void 0;this._length=e}get(e){return this._array[this._getCyclicIndex(e)]}set(e,t){this._array[this._getCyclicIndex(e)]=t}push(e){this._array[this._getCyclicIndex(this._length)]=e,this._length===this._maxLength?(this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1)):this._length++}recycle(){if(this._length!==this._maxLength)throw new Error("Can only recycle when the buffer is full");return this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1),this._array[this._getCyclicIndex(this._length-1)]}get isFull(){return this._length===this._maxLength}pop(){return this._array[this._getCyclicIndex(this._length---1)]}splice(e,t,...i){if(t){for(let i=e;i<this._length-t;i++)this._array[this._getCyclicIndex(i)]=this._array[this._getCyclicIndex(i+t)];this._length-=t,this.onDeleteEmitter.fire({index:e,amount:t})}for(let s=this._length-1;s>=e;s--)this._array[this._getCyclicIndex(s+i.length)]=this._array[this._getCyclicIndex(s)];for(let s=0;s<i.length;s++)this._array[this._getCyclicIndex(e+s)]=i[s];if(i.length&&this.onInsertEmitter.fire({index:e,amount:i.length}),this._length+i.length>this._maxLength){let e=this._length+i.length-this._maxLength;this._startIndex+=e,this._length=this._maxLength,this.onTrimEmitter.fire(e)}else this._length+=i.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,i){if(!(t<=0)){if(e<0||e>=this._length)throw new Error("start argument out of range");if(e+i<0)throw new Error("Cannot shift elements in list beyond index 0");if(i>0){for(let r=t-1;r>=0;r--)this.set(e+r+i,this.get(e+r));let s=e+t+i-this._length;if(s>0)for(this._length+=s;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let s=0;s<t;s++)this.set(e+s+i,this.get(e+s))}}_getCyclicIndex(e){return(this._startIndex+e)%this._maxLength}},Ih=Object.freeze(new ro),Bh=0,Oh=class e{constructor(e,t,i=!1){this.isWrapped=i,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(3*e);let s=t||oo.fromCharData([0,"",1,0]);for(let r=0;r<e;++r)this.setCell(r,s);this.length=e}get(e){let t=this._data[3*e+0],i=2097151&t;return[this._data[3*e+1],2097152&t?this._combined[e]:i?Qn(i):"",t>>22,2097152&t?this._combined[e].charCodeAt(this._combined[e].length-1):i]}set(e,t){this._data[3*e+1]=t[0],t[1].length>1?(this._combined[e]=t[1],this._data[3*e+0]=2097152|e|t[2]<<22):this._data[3*e+0]=t[1].charCodeAt(0)|t[2]<<22}getWidth(e){return this._data[3*e+0]>>22}hasWidth(e){return 12582912&this._data[3*e+0]}getFg(e){return this._data[3*e+1]}getBg(e){return this._data[3*e+2]}hasContent(e){return 4194303&this._data[3*e+0]}getCodePoint(e){let t=this._data[3*e+0];return 2097152&t?this._combined[e].charCodeAt(this._combined[e].length-1):2097151&t}isCombined(e){return 2097152&this._data[3*e+0]}getString(e){let t=this._data[3*e+0];return 2097152&t?this._combined[e]:2097151&t?Qn(2097151&t):""}isProtected(e){return 536870912&this._data[3*e+2]}loadCell(e,t){return Bh=3*e,t.content=this._data[Bh+0],t.fg=this._data[Bh+1],t.bg=this._data[Bh+2],2097152&t.content&&(t.combinedData=this._combined[e]),268435456&t.bg&&(t.extended=this._extendedAttrs[e]),t}setCell(e,t){2097152&t.content&&(this._combined[e]=t.combinedData),268435456&t.bg&&(this._extendedAttrs[e]=t.extended),this._data[3*e+0]=t.content,this._data[3*e+1]=t.fg,this._data[3*e+2]=t.bg}setCellFromCodepoint(e,t,i,s){268435456&s.bg&&(this._extendedAttrs[e]=s.extended),this._data[3*e+0]=t|i<<22,this._data[3*e+1]=s.fg,this._data[3*e+2]=s.bg}addCodepointToCell(e,t,i){let s=this._data[3*e+0];2097152&s?this._combined[e]+=Qn(t):2097151&s?(this._combined[e]=Qn(2097151&s)+Qn(t),s&=-2097152,s|=2097152):s=t|1<<22,i&&(s&=-12582913,s|=i<<22),this._data[3*e+0]=s}insertCells(e,t,i){if((e%=this.length)&&2===this.getWidth(e-1)&&this.setCellFromCodepoint(e-1,0,1,i),t<this.length-e){let s=new oo;for(let i=this.length-e-t-1;i>=0;--i)this.setCell(e+t+i,this.loadCell(e+i,s));for(let r=0;r<t;++r)this.setCell(e+r,i)}else for(let s=e;s<this.length;++s)this.setCell(s,i);2===this.getWidth(this.length-1)&&this.setCellFromCodepoint(this.length-1,0,1,i)}deleteCells(e,t,i){if(e%=this.length,t<this.length-e){let s=new oo;for(let i=0;i<this.length-e-t;++i)this.setCell(e+i,this.loadCell(e+t+i,s));for(let e=this.length-t;e<this.length;++e)this.setCell(e,i)}else for(let s=e;s<this.length;++s)this.setCell(s,i);e&&2===this.getWidth(e-1)&&this.setCellFromCodepoint(e-1,0,1,i),0===this.getWidth(e)&&!this.hasContent(e)&&this.setCellFromCodepoint(e,0,1,i)}replaceCells(e,t,i,s=!1){if(s)for(e&&2===this.getWidth(e-1)&&!this.isProtected(e-1)&&this.setCellFromCodepoint(e-1,0,1,i),t<this.length&&2===this.getWidth(t-1)&&!this.isProtected(t)&&this.setCellFromCodepoint(t,0,1,i);e<t&&e<this.length;)this.isProtected(e)||this.setCell(e,i),e++;else for(e&&2===this.getWidth(e-1)&&this.setCellFromCodepoint(e-1,0,1,i),t<this.length&&2===this.getWidth(t-1)&&this.setCellFromCodepoint(t,0,1,i);e<t&&e<this.length;)this.setCell(e++,i)}resize(e,t){if(e===this.length)return 4*this._data.length*2<this._data.buffer.byteLength;let i=3*e;if(e>this.length){if(this._data.buffer.byteLength>=4*i)this._data=new Uint32Array(this._data.buffer,0,i);else{let e=new Uint32Array(i);e.set(this._data),this._data=e}for(let i=this.length;i<e;++i)this.setCell(i,t)}else{this._data=this._data.subarray(0,i);let t=Object.keys(this._combined);for(let i=0;i<t.length;i++){let s=parseInt(t[i],10);s>=e&&delete this._combined[s]}let s=Object.keys(this._extendedAttrs);for(let i=0;i<s.length;i++){let t=parseInt(s[i],10);t>=e&&delete this._extendedAttrs[t]}}return this.length=e,4*i*2<this._data.buffer.byteLength}cleanupMemory(){if(4*this._data.length*2<this._data.buffer.byteLength){let e=new Uint32Array(this._data.length);return e.set(this._data),this._data=e,1}return 0}fill(e,t=!1){if(t)for(let i=0;i<this.length;++i)this.isProtected(i)||this.setCell(i,e);else{this._combined={},this._extendedAttrs={};for(let t=0;t<this.length;++t)this.setCell(t,e)}}copyFrom(e){this.length!==e.length?this._data=new Uint32Array(e._data):this._data.set(e._data),this.length=e.length,this._combined={};for(let t in e._combined)this._combined[t]=e._combined[t];this._extendedAttrs={};for(let t in e._extendedAttrs)this._extendedAttrs[t]=e._extendedAttrs[t];this.isWrapped=e.isWrapped}clone(){let t=new e(0);t._data=new Uint32Array(this._data),t.length=this.length;for(let e in this._combined)t._combined[e]=this._combined[e];for(let e in this._extendedAttrs)t._extendedAttrs[e]=this._extendedAttrs[e];return t.isWrapped=this.isWrapped,t}getTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(4194303&this._data[3*e+0])return e+(this._data[3*e+0]>>22);return 0}getNoBgTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(4194303&this._data[3*e+0]||50331648&this._data[3*e+2])return e+(this._data[3*e+0]>>22);return 0}copyCellsFrom(e,t,i,s,r){let n=e._data;if(r)for(let a=s-1;a>=0;a--){for(let e=0;e<3;e++)this._data[3*(i+a)+e]=n[3*(t+a)+e];268435456&n[3*(t+a)+2]&&(this._extendedAttrs[i+a]=e._extendedAttrs[t+a])}else for(let a=0;a<s;a++){for(let e=0;e<3;e++)this._data[3*(i+a)+e]=n[3*(t+a)+e];268435456&n[3*(t+a)+2]&&(this._extendedAttrs[i+a]=e._extendedAttrs[t+a])}let o=Object.keys(e._combined);for(let a=0;a<o.length;a++){let s=parseInt(o[a],10);s>=t&&(this._combined[s-t+i]=e._combined[s])}}translateToString(e,t,i,s){t=t??0,i=i??this.length,e&&(i=Math.min(i,this.getTrimmedLength())),s&&(s.length=0);let r="";for(;t<i;){let e=this._data[3*t+0],i=2097151&e,n=2097152&e?this._combined[t]:i?Qn(i):so;if(r+=n,s)for(let r=0;r<n.length;++r)s.push(t);t+=e>>22||1}return s&&s.push(t),r}};function Ah(e,t,i){let s=[],r=e.map((i,s)=>zh(e,s,t)).reduce((e,t)=>e+t),n=0,o=0,a=0;for(;a<r;){if(r-a<i){s.push(r-a);break}n+=i;let l=zh(e,o,t);n>l&&(n-=l,o++);let c=2===e[o].getWidth(n-1);c&&n--;let h=c?i-1:i;s.push(h),a+=h}return s}function zh(e,t,i){if(t===e.length-1)return e[t].getTrimmedLength();let s=!e[t].hasContent(i-1)&&1===e[t].getWidth(i-1),r=2===e[t+1].getWidth(0);return s&&r?i-1:i}var $h=class e{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=e._nextId++,this._onDispose=this.register(new da),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),Fo(this._disposables),this._disposables.length=0)}register(e){return this._disposables.push(e),e}};$h._nextId=1;var Hh=$h,Wh={},Fh=Wh.B;Wh[0]={"`":"◆",a:"▒",b:"␉",c:"␌",d:"␍",e:"␊",f:"°",g:"±",h:"␤",i:"␋",j:"┘",k:"┐",l:"┌",m:"└",n:"┼",o:"⎺",p:"⎻",q:"─",r:"⎼",s:"⎽",t:"├",u:"┤",v:"┴",w:"┬",x:"│",y:"≤",z:"≥","{":"π","|":"≠","}":"£","~":"·"},Wh.A={"#":"£"},Wh.B=void 0,Wh[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"},Wh.C=Wh[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"},Wh.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"},Wh.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"},Wh.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"},Wh.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"},Wh.E=Wh[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"},Wh.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"},Wh.H=Wh[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"},Wh["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"};var Kh=4294967295,Uh=class{constructor(e,t,i){this._hasScrollback=e,this._optionsService=t,this._bufferService=i,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=Ih.clone(),this.savedCharset=Fh,this.markers=[],this._nullCell=oo.fromCharData([0,"",1,0]),this._whitespaceCell=oo.fromCharData([0,so,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new rh,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new Th(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg,this._nullCell.extended=e.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new no),this._nullCell}getWhitespaceCell(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg,this._whitespaceCell.extended=e.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new no),this._whitespaceCell}getBlankLine(e,t){return new Oh(this._bufferService.cols,this.getNullCell(e),t)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let e=this.ybase+this.y-this.ydisp;return e>=0&&e<this._rows}_getCorrectBufferLength(e){if(!this._hasScrollback)return e;let t=e+this._optionsService.rawOptions.scrollback;return t>Kh?Kh:t}fillViewportRows(e){if(0===this.lines.length){void 0===e&&(e=Ih);let t=this._rows;for(;t--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new Th(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let i=this.getNullCell(Ih),s=0,r=this._getCorrectBufferLength(t);if(r>this.lines.maxLength&&(this.lines.maxLength=r),this.lines.length>0){if(this._cols<e)for(let t=0;t<this.lines.length;t++)s+=+this.lines.get(t).resize(e,i);let n=0;if(this._rows<t)for(let s=this._rows;s<t;s++)this.lines.length<t+this.ybase&&(this._optionsService.rawOptions.windowsMode||void 0!==this._optionsService.rawOptions.windowsPty.backend||void 0!==this._optionsService.rawOptions.windowsPty.buildNumber?this.lines.push(new Oh(e,i)):this.ybase>0&&this.lines.length<=this.ybase+this.y+n+1?(this.ybase--,n++,this.ydisp>0&&this.ydisp--):this.lines.push(new Oh(e,i)));else for(let e=this._rows;e>t;e--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(r<this.lines.maxLength){let e=this.lines.length-r;e>0&&(this.lines.trimStart(e),this.ybase=Math.max(this.ybase-e,0),this.ydisp=Math.max(this.ydisp-e,0),this.savedY=Math.max(this.savedY-e,0)),this.lines.maxLength=r}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),n&&(this.y+=n),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(let n=0;n<this.lines.length;n++)s+=+this.lines.get(n).resize(e,i);this._cols=e,this._rows=t,this._memoryCleanupQueue.clear(),s>.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let e=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e=!1);let t=0;for(;this._memoryCleanupPosition<this.lines.length;)if(t+=this.lines.get(this._memoryCleanupPosition++).cleanupMemory(),t>100)return!0;return e}get _isReflowEnabled(){let e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&"conpty"===e.backend&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))}_reflowLarger(e,t){let i=this._optionsService.rawOptions.reflowCursorLine,s=function(e,t,i,s,r,n){let o=[];for(let a=0;a<e.length-1;a++){let l=a,c=e.get(++l);if(!c.isWrapped)continue;let h=[e.get(a)];for(;l<e.length&&c.isWrapped;)h.push(c),c=e.get(++l);if(!n&&s>=a&&s<l){a+=h.length-1;continue}let d=0,u=zh(h,d,t),f=1,p=0;for(;f<h.length;){let e=zh(h,f,t),s=e-p,n=i-u,o=Math.min(s,n);h[d].copyCellsFrom(h[f],p,u,o,!1),u+=o,u===i&&(d++,u=0),p+=o,p===e&&(f++,p=0),0===u&&0!==d&&2===h[d-1].getWidth(i-1)&&(h[d].copyCellsFrom(h[d-1],i-1,u++,1,!1),h[d-1].setCell(i-1,r))}h[d].replaceCells(u,i,r);let m=0;for(let e=h.length-1;e>0&&(e>d||0===h[e].getTrimmedLength());e--)m++;m>0&&(o.push(a+h.length-m),o.push(m)),a+=h.length-1}return o}(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(Ih),i);if(s.length>0){let i=function(e,t){let i=[],s=0,r=t[s],n=0;for(let o=0;o<e.length;o++)if(r===o){let i=t[++s];e.onDeleteEmitter.fire({index:o-n,amount:i}),o+=i-1,n+=i,r=t[++s]}else i.push(o);return{layout:i,countRemoved:n}}(this.lines,s);(function(e,t){let i=[];for(let s=0;s<t.length;s++)i.push(e.get(t[s]));for(let s=0;s<i.length;s++)e.set(s,i[s]);e.length=t.length})(this.lines,i.layout),this._reflowLargerAdjustViewport(e,t,i.countRemoved)}}_reflowLargerAdjustViewport(e,t,i){let s=this.getNullCell(Ih),r=i;for(;r-- >0;)0===this.ybase?(this.y>0&&this.y--,this.lines.length<t&&this.lines.push(new Oh(e,s))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-i,0)}_reflowSmaller(e,t){let i=this._optionsService.rawOptions.reflowCursorLine,s=this.getNullCell(Ih),r=[],n=0;for(let o=this.lines.length-1;o>=0;o--){let a=this.lines.get(o);if(!a||!a.isWrapped&&a.getTrimmedLength()<=e)continue;let l=[a];for(;a.isWrapped&&o>0;)a=this.lines.get(--o),l.unshift(a);if(!i){let e=this.ybase+this.y;if(e>=o&&e<o+l.length)continue}let c,h=l[l.length-1].getTrimmedLength(),d=Ah(l,this._cols,e),u=d.length-l.length;c=0===this.ybase&&this.y!==this.lines.length-1?Math.max(0,this.y-this.lines.maxLength+u):Math.max(0,this.lines.length-this.lines.maxLength+u);let f=[];for(let e=0;e<u;e++){let e=this.getBlankLine(Ih,!0);f.push(e)}f.length>0&&(r.push({start:o+l.length+n,newLines:f}),n+=f.length),l.push(...f);let p=d.length-1,m=d[p];0===m&&(p--,m=d[p]);let _=l.length-u-1,g=h;for(;_>=0;){let e=Math.min(g,m);if(void 0===l[p])break;if(l[p].copyCellsFrom(l[_],g-e,m-e,e,!0),m-=e,0===m&&(p--,m=d[p]),g-=e,0===g){_--,g=zh(l,Math.max(_,0),this._cols)}}for(let t=0;t<l.length;t++)d[t]<e&&l[t].setCell(d[t],s);let v=u-c;for(;v-- >0;)0===this.ybase?this.y<t-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+n)-t&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+u,this.ybase+t-1)}if(r.length>0){let e=[],t=[];for(let r=0;r<this.lines.length;r++)t.push(this.lines.get(r));let i=this.lines.length,s=i-1,o=0,a=r[o];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+n);let l=0;for(let d=Math.min(this.lines.maxLength-1,i+n-1);d>=0;d--)if(a&&a.start>s+l){for(let e=a.newLines.length-1;e>=0;e--)this.lines.set(d--,a.newLines[e]);d++,e.push({index:s+1,amount:a.newLines.length}),l+=a.newLines.length,a=r[++o]}else this.lines.set(d,t[s--]);let c=0;for(let r=e.length-1;r>=0;r--)e[r].index+=c,this.lines.onInsertEmitter.fire(e[r]),c+=e[r].amount;let h=Math.max(0,i+n-this.lines.maxLength);h>0&&this.lines.onTrimEmitter.fire(h)}}translateBufferLineToString(e,t,i=0,s){let r=this.lines.get(e);return r?r.translateToString(t,i,s):""}getWrappedRangeForLine(e){let t=e,i=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;i+1<this.lines.length&&this.lines.get(i+1).isWrapped;)i++;return{first:t,last:i}}setupTabStops(e){for(null!=e?this.tabs[e]||(e=this.prevStop(e)):(this.tabs={},e=0);e<this._cols;e+=this._optionsService.rawOptions.tabStopWidth)this.tabs[e]=!0}prevStop(e){for(null==e&&(e=this.x);!this.tabs[--e]&&e>0;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(null==e&&(e=this.x);!this.tabs[++e]&&e<this._cols;);return e>=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t<this.markers.length;t++)this.markers[t].line===e&&(this.markers[t].dispose(),this.markers.splice(t--,1));this._isClearing=!1}clearAllMarkers(){this._isClearing=!0;for(let e=0;e<this.markers.length;e++)this.markers[e].dispose();this.markers.length=0,this._isClearing=!1}addMarker(e){let t=new Hh(e);return this.markers.push(t),t.register(this.lines.onTrim(e=>{t.line-=e,t.line<0&&t.dispose()})),t.register(this.lines.onInsert(e=>{t.line>=e.index&&(t.line+=e.amount)})),t.register(this.lines.onDelete(e=>{t.line>=e.index&&t.line<e.index+e.amount&&t.dispose(),t.line>e.index&&(t.line-=e.amount)})),t.register(t.onDispose(()=>this._removeMarker(t))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}},Vh=class extends qo{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new da),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this._register(this._optionsService.onSpecificOptionChange("scrollback",()=>this.resize(this._bufferService.cols,this._bufferService.rows))),this._register(this._optionsService.onSpecificOptionChange("tabStopWidth",()=>this.setupTabStops()))}reset(){this._normal=new Uh(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new Uh(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e,t){this._normal.resize(e,t),this._alt.resize(e,t),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}},qh=class extends qo{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new da),this.onResize=this._onResize.event,this._onScroll=this._register(new da),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,2),this.rows=Math.max(e.rawOptions.rows||0,1),this.buffers=this._register(new Vh(e,this)),this._register(this.buffers.onBufferActivate(e=>{this._onScroll.fire(e.activeBuffer.ydisp)}))}get buffer(){return this.buffers.active}resize(e,t){let i=this.cols!==e,s=this.rows!==t;this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t,colsChanged:i,rowsChanged:s})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){let i,s=this.buffer;i=this._cachedBlankLine,(!i||i.length!==this.cols||i.getFg(0)!==e.fg||i.getBg(0)!==e.bg)&&(i=s.getBlankLine(e,t),this._cachedBlankLine=i),i.isWrapped=t;let r=s.ybase+s.scrollTop,n=s.ybase+s.scrollBottom;if(0===s.scrollTop){let e=s.lines.isFull;n===s.lines.length-1?e?s.lines.recycle().copyFrom(i):s.lines.push(i.clone()):s.lines.splice(n+1,0,i.clone()),e?this.isUserScrolling&&(s.ydisp=Math.max(s.ydisp-1,0)):(s.ybase++,this.isUserScrolling||s.ydisp++)}else{let e=n-r+1;s.lines.shiftElements(r+1,e-1,-1),s.lines.set(n,i.clone())}this.isUserScrolling||(s.ydisp=s.ybase),this._onScroll.fire(s.ydisp)}scrollLines(e,t){let i=this.buffer;if(e<0){if(0===i.ydisp)return;this.isUserScrolling=!0}else e+i.ydisp>=i.ybase&&(this.isUserScrolling=!1);let s=i.ydisp;i.ydisp=Math.max(Math.min(i.ydisp+e,i.ybase),0),s!==i.ydisp&&(t||this._onScroll.fire(i.ydisp))}};qh=Wn([Fn(0,vo)],qh);var Yh={cols:80,rows:24,cursorBlink:!1,cursorStyle:"block",cursorWidth:1,cursorInactiveStyle:"outline",customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:"alt",fastScrollSensitivity:5,fontFamily:"monospace",fontSize:15,fontWeight:"normal",fontWeightBold:"bold",ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:"info",logger:null,scrollback:1e3,scrollOnEraseInDisplay:!1,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},reflowCursorLine:!1,rescaleOverlappingGlyphs:!1,rightClickSelectsWord:Zc,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRuler:{}},Xh=["normal","bold","100","200","300","400","500","600","700","800","900"],Gh=class extends qo{constructor(e){super(),this._onOptionChange=this._register(new da),this.onOptionChange=this._onOptionChange.event;let t={...Yh};for(let i in e)if(i in t)try{let s=e[i];t[i]=this._sanitizeAndValidateOption(i,s)}catch(Nl){console.error(Nl)}this.rawOptions=t,this.options={...t},this._setupOptions(),this._register(Ko(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(e,t){return this.onOptionChange(i=>{i===e&&t(this.rawOptions[e])})}onMultipleOptionChange(e,t){return this.onOptionChange(i=>{-1!==e.indexOf(i)&&t()})}_setupOptions(){let e=e=>{if(!(e in Yh))throw new Error(`No option with key "${e}"`);return this.rawOptions[e]},t=(e,t)=>{if(!(e in Yh))throw new Error(`No option with key "${e}"`);t=this._sanitizeAndValidateOption(e,t),this.rawOptions[e]!==t&&(this.rawOptions[e]=t,this._onOptionChange.fire(e))};for(let i in this.rawOptions){let s={get:e.bind(this,i),set:t.bind(this,i)};Object.defineProperty(this.options,i,s)}}_sanitizeAndValidateOption(e,t){switch(e){case"cursorStyle":if(t||(t=Yh[e]),"block"!==(i=t)&&"underline"!==i&&"bar"!==i)throw new Error(`"${t}" is not a valid value for ${e}`);break;case"wordSeparator":t||(t=Yh[e]);break;case"fontWeight":case"fontWeightBold":if("number"==typeof t&&1<=t&&t<=1e3)break;t=Xh.includes(t)?t:Yh[e];break;case"cursorWidth":t=Math.floor(t);case"lineHeight":case"tabStopWidth":if(t<1)throw new Error(`${e} cannot be less than 1, value: ${t}`);break;case"minimumContrastRatio":t=Math.max(1,Math.min(21,Math.round(10*t)/10));break;case"scrollback":if((t=Math.min(t,4294967295))<0)throw new Error(`${e} cannot be less than 0, value: ${t}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(t<=0)throw new Error(`${e} cannot be less than or equal to 0, value: ${t}`);break;case"rows":case"cols":if(!t&&0!==t)throw new Error(`${e} must be numeric, value: ${t}`);break;case"windowsPty":t=t??{}}var i;return t}};function Zh(e,t=5){if("object"!=typeof e)return e;let i=Array.isArray(e)?[]:{};for(let s in e)i[s]=t<=1?e[s]:e[s]&&Zh(e[s],t-1);return i}var Jh=Object.freeze({insertMode:!1}),Qh=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),ed=class extends qo{constructor(e,t,i){super(),this._bufferService=e,this._logService=t,this._optionsService=i,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new da),this.onData=this._onData.event,this._onUserInput=this._register(new da),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new da),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new da),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=Zh(Jh),this.decPrivateModes=Zh(Qh)}reset(){this.modes=Zh(Jh),this.decPrivateModes=Zh(Qh)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;let i=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&i.ybase!==i.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`),this._logService.trace("sending data (codes)",()=>e.split("").map(e=>e.charCodeAt(0))),this._onData.fire(e)}triggerBinaryEvent(e){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${e}"`),this._logService.trace("sending binary (codes)",()=>e.split("").map(e=>e.charCodeAt(0))),this._onBinary.fire(e))}};ed=Wn([Fn(0,uo),Fn(1,go),Fn(2,vo)],ed);var td={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:e=>4!==e.button&&1===e.action&&(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)},VT200:{events:19,restrict:e=>32!==e.action},DRAG:{events:23,restrict:e=>!(32===e.action&&3===e.button)},ANY:{events:31,restrict:e=>!0}};function id(e,t){let i=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return 4===e.button?(i|=64,i|=e.action):(i|=3&e.button,4&e.button&&(i|=64),8&e.button&&(i|=128),32===e.action?i|=32:0===e.action&&!t&&(i|=3)),i}var sd=String.fromCharCode,rd={DEFAULT:e=>{let t=[id(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?"":`${sd(t[0])}${sd(t[1])}${sd(t[2])}`},SGR:e=>{let t=0===e.action&&4!==e.button?"m":"M";return`[<${id(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=0===e.action&&4!==e.button?"m":"M";return`[<${id(e,!0)};${e.x};${e.y}${t}`}},nd=class extends qo{constructor(e,t,i){super(),this._bufferService=e,this._coreService=t,this._optionsService=i,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new da),this.onProtocolChange=this._onProtocolChange.event;for(let s of Object.keys(td))this.addProtocol(s,td[s]);for(let s of Object.keys(rd))this.addEncoding(s,rd[s]);this.reset()}addProtocol(e,t){this._protocols[e]=t}addEncoding(e,t){this._encodings[e]=t}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return 0!==this._protocols[this._activeProtocol].events}set activeProtocol(e){if(!this._protocols[e])throw new Error(`unknown protocol "${e}"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw new Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(e,t,i){if(0===e.deltaY||e.shiftKey||void 0===t||void 0===i)return 0;let s=t/i,r=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(r/=s+0,Math.abs(e.deltaY)<50&&(r*=.3),this._wheelPartialScroll+=r,r=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(r*=this._bufferService.rows),r}_applyScrollModifier(e,t){return t.altKey||t.ctrlKey||t.shiftKey?e*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:e*this._optionsService.rawOptions.scrollSensitivity}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows||4===e.button&&32===e.action||3===e.button&&32!==e.action||4!==e.button&&(2===e.action||3===e.action)||(e.col++,e.row++,32===e.action&&this._lastEvent&&this._equalEvents(this._lastEvent,e,"SGR_PIXELS"===this._activeEncoding))||!this._protocols[this._activeProtocol].restrict(e))return!1;let t=this._encodings[this._activeEncoding](e);return t&&("DEFAULT"===this._activeEncoding?this._coreService.triggerBinaryEvent(t):this._coreService.triggerDataEvent(t,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(1&e),up:!!(2&e),drag:!!(4&e),move:!!(8&e),wheel:!!(16&e)}}_equalEvents(e,t,i){if(i){if(e.x!==t.x||e.y!==t.y)return!1}else if(e.col!==t.col||e.row!==t.row)return!1;return!(e.button!==t.button||e.action!==t.action||e.ctrl!==t.ctrl||e.alt!==t.alt||e.shift!==t.shift)}};nd=Wn([Fn(0,uo),Fn(1,po),Fn(2,vo)],nd);var od,ad=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],ld=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]];var cd=class{constructor(){if(this.version="6",!od){(od=new Uint8Array(65536)).fill(1),od[0]=0,od.fill(0,1,32),od.fill(0,127,160),od.fill(2,4352,4448),od[9001]=2,od[9002]=2,od.fill(2,11904,42192),od[12351]=1,od.fill(2,44032,55204),od.fill(2,63744,64256),od.fill(2,65040,65050),od.fill(2,65072,65136),od.fill(2,65280,65377),od.fill(2,65504,65511);for(let e=0;e<ad.length;++e)od.fill(0,ad[e][0],ad[e][1]+1)}}wcwidth(e){return e<32?0:e<127?1:e<65536?od[e]:function(e,t){let i,s=0,r=t.length-1;if(e<t[0][0]||e>t[r][1])return!1;for(;r>=s;)if(i=s+r>>1,e>t[i][1])s=i+1;else{if(!(e<t[i][0]))return!0;r=i-1}return!1}(e,ld)?0:e>=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let i=this.wcwidth(e),s=0===i&&0!==t;if(s){let e=hd.extractWidth(t);0===e?s=!1:e>i&&(i=e)}return hd.createPropertyValue(0,i,s)}},hd=class e{constructor(){this._providers=Object.create(null),this._active="",this._onChange=new da,this.onChange=this._onChange.event;let e=new cd;this.register(e),this._active=e.version,this._activeProvider=e}static extractShouldJoin(e){return!!(1&e)}static extractWidth(e){return e>>1&3}static extractCharKind(e){return e>>3}static createPropertyValue(e,t,i=!1){return(16777215&e)<<3|(3&t)<<1|(i?1:0)}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(e){if(!this._providers[e])throw new Error(`unknown Unicode version "${e}"`);this._active=e,this._activeProvider=this._providers[e],this._onChange.fire(e)}register(e){this._providers[e.version]=e}wcwidth(e){return this._activeProvider.wcwidth(e)}getStringCellWidth(t){let i=0,s=0,r=t.length;for(let n=0;n<r;++n){let o=t.charCodeAt(n);if(55296<=o&&o<=56319){if(++n>=r)return i+this.wcwidth(o);let e=t.charCodeAt(n);56320<=e&&e<=57343?o=1024*(o-55296)+e-56320+65536:i+=this.wcwidth(e)}let a=this.charProperties(o,s),l=e.extractWidth(a);e.extractShouldJoin(a)&&(l-=e.extractWidth(s)),i+=l,s=a}return i}charProperties(e,t){return this._activeProvider.charProperties(e,t)}},dd=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(e){this.glevel=e,this.charset=this._charsets[e]}setgCharset(e,t){this._charsets[e]=t,this.glevel===e&&(this.charset=t)}};function ud(e){var t;let i=null==(t=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1))?void 0:t.get(e.cols-1),s=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);s&&i&&(s.isWrapped=0!==i[3]&&32!==i[3])}var fd=2147483647,pd=class e{constructor(e=32,t=32){if(this.maxLength=e,this.maxSubParamsLength=t,t>256)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(e),this.length=0,this._subParams=new Int32Array(t),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(e),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}static fromArray(t){let i=new e;if(!t.length)return i;for(let e=Array.isArray(t[0])?1:0;e<t.length;++e){let s=t[e];if(Array.isArray(s))for(let e=0;e<s.length;++e)i.addSubParam(s[e]);else i.addParam(s)}return i}clone(){let t=new e(this.maxLength,this.maxSubParamsLength);return t.params.set(this.params),t.length=this.length,t._subParams.set(this._subParams),t._subParamsLength=this._subParamsLength,t._subParamsIdx.set(this._subParamsIdx),t._rejectDigits=this._rejectDigits,t._rejectSubDigits=this._rejectSubDigits,t._digitIsSub=this._digitIsSub,t}toArray(){let e=[];for(let t=0;t<this.length;++t){e.push(this.params[t]);let i=this._subParamsIdx[t]>>8,s=255&this._subParamsIdx[t];s-i>0&&e.push(Array.prototype.slice.call(this._subParams,i,s))}return e}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(e){if(this._digitIsSub=!1,this.length>=this.maxLength)this._rejectDigits=!0;else{if(e<-1)throw new Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=e>fd?fd:e}}addSubParam(e){if(this._digitIsSub=!0,this.length){if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength)return void(this._rejectSubDigits=!0);if(e<-1)throw new Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=e>fd?fd:e,this._subParamsIdx[this.length-1]++}}hasSubParams(e){return(255&this._subParamsIdx[e])-(this._subParamsIdx[e]>>8)>0}getSubParams(e){let t=this._subParamsIdx[e]>>8,i=255&this._subParamsIdx[e];return i-t>0?this._subParams.subarray(t,i):null}getSubParamsAll(){let e={};for(let t=0;t<this.length;++t){let i=this._subParamsIdx[t]>>8,s=255&this._subParamsIdx[t];s-i>0&&(e[t]=this._subParams.slice(i,s))}return e}addDigit(e){let t;if(this._rejectDigits||!(t=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let i=this._digitIsSub?this._subParams:this.params,s=i[t-1];i[t-1]=~s?Math.min(10*s+e,fd):e}},md=[],_d=class{constructor(){this._state=0,this._active=md,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(e,t){void 0===this._handlers[e]&&(this._handlers[e]=[]);let i=this._handlers[e];return i.push(t),{dispose:()=>{let e=i.indexOf(t);-1!==e&&i.splice(e,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=md}reset(){if(2===this._state)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].end(!1);this._stack.paused=!1,this._active=md,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||md,this._active.length)for(let e=this._active.length-1;e>=0;e--)this._active[e].start();else this._handlerFb(this._id,"START")}_put(e,t,i){if(this._active.length)for(let s=this._active.length-1;s>=0;s--)this._active[s].put(e,t,i);else this._handlerFb(this._id,"PUT",eo(e,t,i))}start(){this.reset(),this._state=1}put(e,t,i){if(3!==this._state){if(1===this._state)for(;t<i;){let i=e[t++];if(59===i){this._state=2,this._start();break}if(i<48||57<i)return void(this._state=3);-1===this._id&&(this._id=0),this._id=10*this._id+i-48}2===this._state&&i-t>0&&this._put(e,t,i)}}end(e,t=!0){if(0!==this._state){if(3!==this._state)if(1===this._state&&this._start(),this._active.length){let i=!1,s=this._active.length-1,r=!1;if(this._stack.paused&&(s=this._stack.loopPosition-1,i=t,r=this._stack.fallThrough,this._stack.paused=!1),!r&&!1===i){for(;s>=0&&(i=this._active[s].end(e),!0!==i);s--)if(i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!1,i;s--}for(;s>=0;s--)if(i=this._active[s].end(!1),i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!0,i}else this._handlerFb(this._id,"END",e);this._active=md,this._id=-1,this._state=0}}},gd=class{constructor(e){this._handler=e,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=eo(e,t,i),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}end(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data),t instanceof Promise))return t.then(e=>(this._data="",this._hitLimit=!1,e));return this._data="",this._hitLimit=!1,t}},vd=[],yd=class{constructor(){this._handlers=Object.create(null),this._active=vd,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=vd}registerHandler(e,t){void 0===this._handlers[e]&&(this._handlers[e]=[]);let i=this._handlers[e];return i.push(t),{dispose:()=>{let e=i.indexOf(t);-1!==e&&i.splice(e,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}reset(){if(this._active.length)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].unhook(!1);this._stack.paused=!1,this._active=vd,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||vd,this._active.length)for(let i=this._active.length-1;i>=0;i--)this._active[i].hook(t);else this._handlerFb(this._ident,"HOOK",t)}put(e,t,i){if(this._active.length)for(let s=this._active.length-1;s>=0;s--)this._active[s].put(e,t,i);else this._handlerFb(this._ident,"PUT",eo(e,t,i))}unhook(e,t=!0){if(this._active.length){let i=!1,s=this._active.length-1,r=!1;if(this._stack.paused&&(s=this._stack.loopPosition-1,i=t,r=this._stack.fallThrough,this._stack.paused=!1),!r&&!1===i){for(;s>=0&&(i=this._active[s].unhook(e),!0!==i);s--)if(i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!1,i;s--}for(;s>=0;s--)if(i=this._active[s].unhook(!1),i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!0,i}else this._handlerFb(this._ident,"UNHOOK",e);this._active=vd,this._ident=0}},xd=new pd;xd.addParam(0);var bd=class{constructor(e){this._handler=e,this._data="",this._params=xd,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():xd,this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=eo(e,t,i),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}unhook(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data,this._params),t instanceof Promise))return t.then(e=>(this._params=xd,this._data="",this._hitLimit=!1,e));return this._params=xd,this._data="",this._hitLimit=!1,t}},wd=class{constructor(e){this.table=new Uint8Array(e)}setDefault(e,t){this.table.fill(e<<4|t)}add(e,t,i,s){this.table[t<<8|e]=i<<4|s}addMany(e,t,i,s){for(let r=0;r<e.length;r++)this.table[t<<8|e[r]]=i<<4|s}},Sd=160,Cd=function(){let e=new wd(4095),t=Array.apply(null,Array(256)).map((e,t)=>t),i=(e,i)=>t.slice(e,i),s=i(32,127),r=i(0,24);r.push(25),r.push.apply(r,i(28,32));let n,o=i(0,14);for(n in e.setDefault(1,0),e.addMany(s,0,2,0),o)e.addMany([24,26,153,154],n,3,0),e.addMany(i(128,144),n,3,0),e.addMany(i(144,152),n,3,0),e.add(156,n,0,0),e.add(27,n,11,1),e.add(157,n,4,8),e.addMany([152,158,159],n,0,7),e.add(155,n,11,3),e.add(144,n,11,9);return e.addMany(r,0,3,0),e.addMany(r,1,3,1),e.add(127,1,0,1),e.addMany(r,8,0,8),e.addMany(r,3,3,3),e.add(127,3,0,3),e.addMany(r,4,3,4),e.add(127,4,0,4),e.addMany(r,6,3,6),e.addMany(r,5,3,5),e.add(127,5,0,5),e.addMany(r,2,3,2),e.add(127,2,0,2),e.add(93,1,4,8),e.addMany(s,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(i(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(s,7,0,7),e.addMany(r,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(i(64,127),3,7,0),e.addMany(i(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(i(48,60),4,8,4),e.addMany(i(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(i(32,64),6,0,6),e.add(127,6,0,6),e.addMany(i(64,127),6,0,0),e.addMany(i(32,48),3,9,5),e.addMany(i(32,48),5,9,5),e.addMany(i(48,64),5,0,6),e.addMany(i(64,127),5,7,0),e.addMany(i(32,48),4,9,5),e.addMany(i(32,48),1,9,2),e.addMany(i(32,48),2,9,2),e.addMany(i(48,127),2,10,0),e.addMany(i(48,80),1,10,0),e.addMany(i(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(i(96,127),1,10,0),e.add(80,1,11,9),e.addMany(r,9,0,9),e.add(127,9,0,9),e.addMany(i(28,32),9,0,9),e.addMany(i(32,48),9,9,12),e.addMany(i(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(r,11,0,11),e.addMany(i(32,128),11,0,11),e.addMany(i(28,32),11,0,11),e.addMany(r,10,0,10),e.add(127,10,0,10),e.addMany(i(28,32),10,0,10),e.addMany(i(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(i(32,48),10,9,12),e.addMany(r,12,0,12),e.add(127,12,0,12),e.addMany(i(28,32),12,0,12),e.addMany(i(32,48),12,9,12),e.addMany(i(48,64),12,0,11),e.addMany(i(64,127),12,12,13),e.addMany(i(64,127),10,12,13),e.addMany(i(64,127),9,12,13),e.addMany(r,13,13,13),e.addMany(s,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(Sd,0,2,0),e.add(Sd,8,5,8),e.add(Sd,6,0,6),e.add(Sd,11,0,11),e.add(Sd,13,13,13),e}(),kd=class extends qo{constructor(e=Cd){super(),this._transitions=e,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new pd,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(e,t,i)=>{},this._executeHandlerFb=e=>{},this._csiHandlerFb=(e,t)=>{},this._escHandlerFb=e=>{},this._errorHandlerFb=e=>e,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register(Ko(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new _d),this._dcsParser=this._register(new yd),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},()=>!0)}_identifier(e,t=[64,126]){let i=0;if(e.prefix){if(e.prefix.length>1)throw new Error("only one byte as prefix supported");if(i=e.prefix.charCodeAt(0),i&&60>i||i>63)throw new Error("prefix must be in range 0x3c .. 0x3f")}if(e.intermediates){if(e.intermediates.length>2)throw new Error("only two bytes as intermediates are supported");for(let t=0;t<e.intermediates.length;++t){let s=e.intermediates.charCodeAt(t);if(32>s||s>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");i<<=8,i|=s}}if(1!==e.final.length)throw new Error("final must be a single byte");let s=e.final.charCodeAt(0);if(t[0]>s||s>t[1])throw new Error(`final must be in range ${t[0]} .. ${t[1]}`);return i<<=8,i|=s,i}identToString(e){let t=[];for(;e;)t.push(String.fromCharCode(255&e)),e>>=8;return t.reverse().join("")}setPrintHandler(e){this._printHandler=e}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e,t){let i=this._identifier(e,[48,126]);void 0===this._escHandlers[i]&&(this._escHandlers[i]=[]);let s=this._escHandlers[i];return s.push(t),{dispose:()=>{let e=s.indexOf(t);-1!==e&&s.splice(e,1)}}}clearEscHandler(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]}setEscHandlerFallback(e){this._escHandlerFb=e}setExecuteHandler(e,t){this._executeHandlers[e.charCodeAt(0)]=t}clearExecuteHandler(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]}setExecuteHandlerFallback(e){this._executeHandlerFb=e}registerCsiHandler(e,t){let i=this._identifier(e);void 0===this._csiHandlers[i]&&(this._csiHandlers[i]=[]);let s=this._csiHandlers[i];return s.push(t),{dispose:()=>{let e=s.indexOf(t);-1!==e&&s.splice(e,1)}}}clearCsiHandler(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]}setCsiHandlerFallback(e){this._csiHandlerFb=e}registerDcsHandler(e,t){return this._dcsParser.registerHandler(this._identifier(e),t)}clearDcsHandler(e){this._dcsParser.clearHandler(this._identifier(e))}setDcsHandlerFallback(e){this._dcsParser.setHandlerFallback(e)}registerOscHandler(e,t){return this._oscParser.registerHandler(e,t)}clearOscHandler(e){this._oscParser.clearHandler(e)}setOscHandlerFallback(e){this._oscParser.setHandlerFallback(e)}setErrorHandler(e){this._errorHandler=e}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,0!==this._parseStack.state&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(e,t,i,s,r){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=i,this._parseStack.transition=s,this._parseStack.chunkPos=r}parse(e,t,i){let s,r=0,n=0,o=0;if(this._parseStack.state)if(2===this._parseStack.state)this._parseStack.state=0,o=this._parseStack.chunkPos+1;else{if(void 0===i||1===this._parseStack.state)throw this._parseStack.state=1,new Error("improper continuation due to previous async handler, giving up parsing");let t=this._parseStack.handlers,n=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(!1===i&&n>-1)for(;n>=0&&(s=t[n](this._params),!0!==s);n--)if(s instanceof Promise)return this._parseStack.handlerPos=n,s;this._parseStack.handlers=[];break;case 4:if(!1===i&&n>-1)for(;n>=0&&(s=t[n](),!0!==s);n--)if(s instanceof Promise)return this._parseStack.handlerPos=n,s;this._parseStack.handlers=[];break;case 6:if(r=e[this._parseStack.chunkPos],s=this._dcsParser.unhook(24!==r&&26!==r,i),s)return s;27===r&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(r=e[this._parseStack.chunkPos],s=this._oscParser.end(24!==r&&26!==r,i),s)return s;27===r&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0}this._parseStack.state=0,o=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=15&this._parseStack.transition}for(let a=o;a<t;++a){switch(r=e[a],n=this._transitions.table[this.currentState<<8|(r<160?r:Sd)],n>>4){case 2:for(let s=a+1;;++s){if(s>=t||(r=e[s])<32||r>126&&r<Sd){this._printHandler(e,a,s),a=s-1;break}if(++s>=t||(r=e[s])<32||r>126&&r<Sd){this._printHandler(e,a,s),a=s-1;break}if(++s>=t||(r=e[s])<32||r>126&&r<Sd){this._printHandler(e,a,s),a=s-1;break}if(++s>=t||(r=e[s])<32||r>126&&r<Sd){this._printHandler(e,a,s),a=s-1;break}}break;case 3:this._executeHandlers[r]?this._executeHandlers[r]():this._executeHandlerFb(r),this.precedingJoinState=0;break;case 0:break;case 1:if(this._errorHandler({position:a,code:r,currentState:this.currentState,collect:this._collect,params:this._params,abort:!1}).abort)return;break;case 7:let i=this._csiHandlers[this._collect<<8|r],o=i?i.length-1:-1;for(;o>=0&&(s=i[o](this._params),!0!==s);o--)if(s instanceof Promise)return this._preserveStack(3,i,o,n,a),s;o<0&&this._csiHandlerFb(this._collect<<8|r,this._params),this.precedingJoinState=0;break;case 8:do{switch(r){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(r-48)}}while(++a<t&&(r=e[a])>47&&r<60);a--;break;case 9:this._collect<<=8,this._collect|=r;break;case 10:let l=this._escHandlers[this._collect<<8|r],c=l?l.length-1:-1;for(;c>=0&&(s=l[c](),!0!==s);c--)if(s instanceof Promise)return this._preserveStack(4,l,c,n,a),s;c<0&&this._escHandlerFb(this._collect<<8|r),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|r,this._params);break;case 13:for(let s=a+1;;++s)if(s>=t||24===(r=e[s])||26===r||27===r||r>127&&r<Sd){this._dcsParser.put(e,a,s),a=s-1;break}break;case 14:if(s=this._dcsParser.unhook(24!==r&&26!==r),s)return this._preserveStack(6,[],0,n,a),s;27===r&&(n|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break;case 4:this._oscParser.start();break;case 5:for(let s=a+1;;s++)if(s>=t||(r=e[s])<32||r>127&&r<Sd){this._oscParser.put(e,a,s),a=s-1;break}break;case 6:if(s=this._oscParser.end(24!==r&&26!==r),s)return this._preserveStack(5,[],0,n,a),s;27===r&&(n|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0}this.currentState=15&n}}},Ed=/^([\da-f])\/([\da-f])\/([\da-f])$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$/,Nd=/^[\da-f]+$/;function Md(e){if(!e)return;let t=e.toLowerCase();if(0===t.indexOf("rgb:")){t=t.slice(4);let e=Ed.exec(t);if(e){let t=e[1]?15:e[4]?255:e[7]?4095:65535;return[Math.round(parseInt(e[1]||e[4]||e[7]||e[10],16)/t*255),Math.round(parseInt(e[2]||e[5]||e[8]||e[11],16)/t*255),Math.round(parseInt(e[3]||e[6]||e[9]||e[12],16)/t*255)]}}else if(0===t.indexOf("#")&&(t=t.slice(1),Nd.exec(t)&&[3,6,9,12].includes(t.length))){let e=t.length/3,i=[0,0,0];for(let s=0;s<3;++s){let r=parseInt(t.slice(e*s,e*s+e),16);i[s]=1===e?r<<4:2===e?r:3===e?r>>4:r>>8}return i}}function jd(e,t){let i=e.toString(16),s=i.length<2?"0"+i:i;switch(t){case 4:return i[0];case 8:return s;case 12:return(s+s).slice(0,3);default:return s+s}}function Dd(e,t=16){let[i,s,r]=e;return`rgb:${jd(i,t)}/${jd(s,t)}/${jd(r,t)}`}var Rd={"(":0,")":1,"*":2,"+":3,"-":1,".":2},Pd=131072;function Ld(e,t){if(e>24)return t.setWinLines||!1;switch(e){case 1:return!!t.restoreWin;case 2:return!!t.minimizeWin;case 3:return!!t.setWinPosition;case 4:return!!t.setWinSizePixels;case 5:return!!t.raiseWin;case 6:return!!t.lowerWin;case 7:return!!t.refreshWin;case 8:return!!t.setWinSizeChars;case 9:return!!t.maximizeWin;case 10:return!!t.fullscreenWin;case 11:return!!t.getWinState;case 13:return!!t.getWinPosition;case 14:return!!t.getWinSizePixels;case 15:return!!t.getScreenSizePixels;case 16:return!!t.getCellSizePixels;case 18:return!!t.getWinSizeChars;case 19:return!!t.getScreenSizeChars;case 20:return!!t.getIconTitle;case 21:return!!t.getWinTitle;case 22:return!!t.pushTitle;case 23:return!!t.popTitle;case 24:return!!t.setWinLines}return!1}var Td=0,Id=class extends qo{constructor(e,t,i,s,r,n,o,a,l=new kd){super(),this._bufferService=e,this._charsetService=t,this._coreService=i,this._logService=s,this._optionsService=r,this._oscLinkService=n,this._coreMouseService=o,this._unicodeService=a,this._parser=l,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new to,this._utf8Decoder=new io,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=Ih.clone(),this._eraseAttrDataInternal=Ih.clone(),this._onRequestBell=this._register(new da),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new da),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new da),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new da),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new da),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new da),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new da),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new da),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new da),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new da),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new da),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new da),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new da),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this._register(this._parser),this._dirtyRowTracker=new Bd(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(e=>this._activeBuffer=e.activeBuffer)),this._parser.setCsiHandlerFallback((e,t)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(e),params:t.toArray()})}),this._parser.setEscHandlerFallback(e=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(e)})}),this._parser.setExecuteHandlerFallback(e=>{this._logService.debug("Unknown EXECUTE code: ",{code:e})}),this._parser.setOscHandlerFallback((e,t,i)=>{this._logService.debug("Unknown OSC code: ",{identifier:e,action:t,data:i})}),this._parser.setDcsHandlerFallback((e,t,i)=>{"HOOK"===t&&(i=i.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(e),action:t,payload:i})}),this._parser.setPrintHandler((e,t,i)=>this.print(e,t,i)),this._parser.registerCsiHandler({final:"@"},e=>this.insertChars(e)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},e=>this.scrollLeft(e)),this._parser.registerCsiHandler({final:"A"},e=>this.cursorUp(e)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},e=>this.scrollRight(e)),this._parser.registerCsiHandler({final:"B"},e=>this.cursorDown(e)),this._parser.registerCsiHandler({final:"C"},e=>this.cursorForward(e)),this._parser.registerCsiHandler({final:"D"},e=>this.cursorBackward(e)),this._parser.registerCsiHandler({final:"E"},e=>this.cursorNextLine(e)),this._parser.registerCsiHandler({final:"F"},e=>this.cursorPrecedingLine(e)),this._parser.registerCsiHandler({final:"G"},e=>this.cursorCharAbsolute(e)),this._parser.registerCsiHandler({final:"H"},e=>this.cursorPosition(e)),this._parser.registerCsiHandler({final:"I"},e=>this.cursorForwardTab(e)),this._parser.registerCsiHandler({final:"J"},e=>this.eraseInDisplay(e,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},e=>this.eraseInDisplay(e,!0)),this._parser.registerCsiHandler({final:"K"},e=>this.eraseInLine(e,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},e=>this.eraseInLine(e,!0)),this._parser.registerCsiHandler({final:"L"},e=>this.insertLines(e)),this._parser.registerCsiHandler({final:"M"},e=>this.deleteLines(e)),this._parser.registerCsiHandler({final:"P"},e=>this.deleteChars(e)),this._parser.registerCsiHandler({final:"S"},e=>this.scrollUp(e)),this._parser.registerCsiHandler({final:"T"},e=>this.scrollDown(e)),this._parser.registerCsiHandler({final:"X"},e=>this.eraseChars(e)),this._parser.registerCsiHandler({final:"Z"},e=>this.cursorBackwardTab(e)),this._parser.registerCsiHandler({final:"`"},e=>this.charPosAbsolute(e)),this._parser.registerCsiHandler({final:"a"},e=>this.hPositionRelative(e)),this._parser.registerCsiHandler({final:"b"},e=>this.repeatPrecedingCharacter(e)),this._parser.registerCsiHandler({final:"c"},e=>this.sendDeviceAttributesPrimary(e)),this._parser.registerCsiHandler({prefix:">",final:"c"},e=>this.sendDeviceAttributesSecondary(e)),this._parser.registerCsiHandler({final:"d"},e=>this.linePosAbsolute(e)),this._parser.registerCsiHandler({final:"e"},e=>this.vPositionRelative(e)),this._parser.registerCsiHandler({final:"f"},e=>this.hVPosition(e)),this._parser.registerCsiHandler({final:"g"},e=>this.tabClear(e)),this._parser.registerCsiHandler({final:"h"},e=>this.setMode(e)),this._parser.registerCsiHandler({prefix:"?",final:"h"},e=>this.setModePrivate(e)),this._parser.registerCsiHandler({final:"l"},e=>this.resetMode(e)),this._parser.registerCsiHandler({prefix:"?",final:"l"},e=>this.resetModePrivate(e)),this._parser.registerCsiHandler({final:"m"},e=>this.charAttributes(e)),this._parser.registerCsiHandler({final:"n"},e=>this.deviceStatus(e)),this._parser.registerCsiHandler({prefix:"?",final:"n"},e=>this.deviceStatusPrivate(e)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},e=>this.softReset(e)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},e=>this.setCursorStyle(e)),this._parser.registerCsiHandler({final:"r"},e=>this.setScrollRegion(e)),this._parser.registerCsiHandler({final:"s"},e=>this.saveCursor(e)),this._parser.registerCsiHandler({final:"t"},e=>this.windowOptions(e)),this._parser.registerCsiHandler({final:"u"},e=>this.restoreCursor(e)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},e=>this.insertColumns(e)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},e=>this.deleteColumns(e)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},e=>this.selectProtected(e)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},e=>this.requestMode(e,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},e=>this.requestMode(e,!1)),this._parser.setExecuteHandler(Gl.BEL,()=>this.bell()),this._parser.setExecuteHandler(Gl.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(Gl.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(Gl.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(Gl.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(Gl.BS,()=>this.backspace()),this._parser.setExecuteHandler(Gl.HT,()=>this.tab()),this._parser.setExecuteHandler(Gl.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(Gl.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(Jl.IND,()=>this.index()),this._parser.setExecuteHandler(Jl.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(Jl.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new gd(e=>(this.setTitle(e),this.setIconName(e),!0))),this._parser.registerOscHandler(1,new gd(e=>this.setIconName(e))),this._parser.registerOscHandler(2,new gd(e=>this.setTitle(e))),this._parser.registerOscHandler(4,new gd(e=>this.setOrReportIndexedColor(e))),this._parser.registerOscHandler(8,new gd(e=>this.setHyperlink(e))),this._parser.registerOscHandler(10,new gd(e=>this.setOrReportFgColor(e))),this._parser.registerOscHandler(11,new gd(e=>this.setOrReportBgColor(e))),this._parser.registerOscHandler(12,new gd(e=>this.setOrReportCursorColor(e))),this._parser.registerOscHandler(104,new gd(e=>this.restoreIndexedColor(e))),this._parser.registerOscHandler(110,new gd(e=>this.restoreFgColor(e))),this._parser.registerOscHandler(111,new gd(e=>this.restoreBgColor(e))),this._parser.registerOscHandler(112,new gd(e=>this.restoreCursorColor(e))),this._parser.registerEscHandler({final:"7"},()=>this.saveCursor()),this._parser.registerEscHandler({final:"8"},()=>this.restoreCursor()),this._parser.registerEscHandler({final:"D"},()=>this.index()),this._parser.registerEscHandler({final:"E"},()=>this.nextLine()),this._parser.registerEscHandler({final:"H"},()=>this.tabSet()),this._parser.registerEscHandler({final:"M"},()=>this.reverseIndex()),this._parser.registerEscHandler({final:"="},()=>this.keypadApplicationMode()),this._parser.registerEscHandler({final:">"},()=>this.keypadNumericMode()),this._parser.registerEscHandler({final:"c"},()=>this.fullReset()),this._parser.registerEscHandler({final:"n"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"o"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"|"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"}"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"~"},()=>this.setgLevel(1)),this._parser.registerEscHandler({intermediates:"%",final:"@"},()=>this.selectDefaultCharset()),this._parser.registerEscHandler({intermediates:"%",final:"G"},()=>this.selectDefaultCharset());for(let c in Wh)this._parser.registerEscHandler({intermediates:"(",final:c},()=>this.selectCharset("("+c)),this._parser.registerEscHandler({intermediates:")",final:c},()=>this.selectCharset(")"+c)),this._parser.registerEscHandler({intermediates:"*",final:c},()=>this.selectCharset("*"+c)),this._parser.registerEscHandler({intermediates:"+",final:c},()=>this.selectCharset("+"+c)),this._parser.registerEscHandler({intermediates:"-",final:c},()=>this.selectCharset("-"+c)),this._parser.registerEscHandler({intermediates:".",final:c},()=>this.selectCharset("."+c)),this._parser.registerEscHandler({intermediates:"/",final:c},()=>this.selectCharset("/"+c));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(e=>(this._logService.error("Parsing error: ",e),e)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new bd((e,t)=>this.requestStatusString(e,t)))}getAttrData(){return this._curAttrData}_preserveStack(e,t,i,s){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=i,this._parseStack.position=s}_logSlowResolvingAsync(e){this._logService.logLevel<=3&&Promise.race([e,new Promise((e,t)=>setTimeout(()=>t("#SLOW_TIMEOUT"),5e3))]).catch(e=>{if("#SLOW_TIMEOUT"!==e)throw e;console.warn("async parser handler taking longer than 5000 ms")})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let i,s=this._activeBuffer.x,r=this._activeBuffer.y,n=0,o=this._parseStack.paused;if(o){if(i=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(i),i;s=this._parseStack.cursorStartX,r=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>Pd&&(n=this._parseStack.position+Pd)}if(this._logService.logLevel<=1&&this._logService.debug("parsing data "+("string"==typeof e?` "${e}"`:` "${Array.prototype.map.call(e,e=>String.fromCharCode(e)).join("")}"`)),0===this._logService.logLevel&&this._logService.trace("parsing data (codes)","string"==typeof e?e.split("").map(e=>e.charCodeAt(0)):e),this._parseBuffer.length<e.length&&this._parseBuffer.length<Pd&&(this._parseBuffer=new Uint32Array(Math.min(e.length,Pd))),o||this._dirtyRowTracker.clearRange(),e.length>Pd)for(let c=n;c<e.length;c+=Pd){let t=c+Pd<e.length?c+Pd:e.length,n="string"==typeof e?this._stringDecoder.decode(e.substring(c,t),this._parseBuffer):this._utf8Decoder.decode(e.subarray(c,t),this._parseBuffer);if(i=this._parser.parse(this._parseBuffer,n))return this._preserveStack(s,r,n,c),this._logSlowResolvingAsync(i),i}else if(!o){let t="string"==typeof e?this._stringDecoder.decode(e,this._parseBuffer):this._utf8Decoder.decode(e,this._parseBuffer);if(i=this._parser.parse(this._parseBuffer,t))return this._preserveStack(s,r,t,0),this._logSlowResolvingAsync(i),i}(this._activeBuffer.x!==s||this._activeBuffer.y!==r)&&this._onCursorMove.fire();let a=this._dirtyRowTracker.end+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp),l=this._dirtyRowTracker.start+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp);l<this._bufferService.rows&&this._onRequestRefreshRows.fire({start:Math.min(l,this._bufferService.rows-1),end:Math.min(a,this._bufferService.rows-1)})}print(e,t,i){let s,r,n=this._charsetService.charset,o=this._optionsService.rawOptions.screenReaderMode,a=this._bufferService.cols,l=this._coreService.decPrivateModes.wraparound,c=this._coreService.modes.insertMode,h=this._curAttrData,d=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&i-t>0&&2===d.getWidth(this._activeBuffer.x-1)&&d.setCellFromCodepoint(this._activeBuffer.x-1,0,1,h);let u=this._parser.precedingJoinState;for(let f=t;f<i;++f){if(s=e[f],s<127&&n){let e=n[String.fromCharCode(s)];e&&(s=e.charCodeAt(0))}let t=this._unicodeService.charProperties(s,u);r=hd.extractWidth(t);let i=hd.extractShouldJoin(t),p=i?hd.extractWidth(u):0;if(u=t,o&&this._onA11yChar.fire(Qn(s)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+r-p>a)if(l){let e=d,t=this._activeBuffer.x-p;for(this._activeBuffer.x=p,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),d=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),p>0&&d instanceof Oh&&d.copyCellsFrom(e,t,0,p,!1);t<a;)e.setCellFromCodepoint(t++,0,1,h)}else if(this._activeBuffer.x=a-1,2===r)continue;if(i&&this._activeBuffer.x){let e=d.getWidth(this._activeBuffer.x-1)?1:2;d.addCodepointToCell(this._activeBuffer.x-e,s,r);for(let t=r-p;--t>=0;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,h);continue}if(c&&(d.insertCells(this._activeBuffer.x,r-p,this._activeBuffer.getNullCell(h)),2===d.getWidth(a-1)&&d.setCellFromCodepoint(a-1,0,1,h)),d.setCellFromCodepoint(this._activeBuffer.x++,s,r,h),r>0)for(;--r;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,h)}this._parser.precedingJoinState=u,this._activeBuffer.x<a&&i-t>0&&0===d.getWidth(this._activeBuffer.x)&&!d.hasContent(this._activeBuffer.x)&&d.setCellFromCodepoint(this._activeBuffer.x,0,1,h),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return"t"!==e.final||e.prefix||e.intermediates?this._parser.registerCsiHandler(e,t):this._parser.registerCsiHandler(e,e=>!Ld(e.params[0],this._optionsService.rawOptions.windowOptions)||t(e))}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new bd(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new gd(t))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){var e;if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(0===this._activeBuffer.x&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&(null==(e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y))?void 0:e.isWrapped)){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);e.hasWidth(this._activeBuffer.x)&&!e.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e,t){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+t):(this._activeBuffer.x=e,this._activeBuffer.y=t),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,t){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+t)}cursorUp(e){let t=this._activeBuffer.y-this._activeBuffer.scrollTop;return t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){let t=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){let t=e.params[0];return 0===t?delete this._activeBuffer.tabs[this._activeBuffer.x]:3===t&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){let t=e.params[0];return 1===t&&(this._curAttrData.bg|=536870912),(2===t||0===t)&&(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,t,i,s=!1,r=!1){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.replaceCells(t,i,this._activeBuffer.getNullCell(this._eraseAttrData()),r),s&&(n.isWrapped=!1)}_resetBufferLine(e,t=!1){let i=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);i&&(i.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),i.isWrapped=!1)}eraseInDisplay(e,t=!1){var i;let s;switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:for(s=this._activeBuffer.y,this._dirtyRowTracker.markDirty(s),this._eraseInBufferLine(s++,this._activeBuffer.x,this._bufferService.cols,0===this._activeBuffer.x,t);s<this._bufferService.rows;s++)this._resetBufferLine(s,t);this._dirtyRowTracker.markDirty(s);break;case 1:for(s=this._activeBuffer.y,this._dirtyRowTracker.markDirty(s),this._eraseInBufferLine(s,0,this._activeBuffer.x+1,!0,t),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(s+1).isWrapped=!1);s--;)this._resetBufferLine(s,t);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(s=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,s-1);s--&&!(null==(i=this._activeBuffer.lines.get(this._activeBuffer.ybase+s))?void 0:i.getTrimmedLength()););for(;s>=0;s--)this._bufferService.scroll(this._eraseAttrData())}else{for(s=this._bufferService.rows,this._dirtyRowTracker.markDirty(s-1);s--;)this._resetBufferLine(s,t);this._dirtyRowTracker.markDirty(0)}break;case 3:let e=this._activeBuffer.lines.length-this._bufferService.rows;e>0&&(this._activeBuffer.lines.trimStart(e),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-e,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-e,0),this._onScroll.fire(0))}return!0}eraseInLine(e,t=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,0===this._activeBuffer.x,t);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t)}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let i=this._activeBuffer.ybase+this._activeBuffer.y,s=this._bufferService.rows-1-this._activeBuffer.scrollBottom,r=this._bufferService.rows-1+this._activeBuffer.ybase-s+1;for(;t--;)this._activeBuffer.lines.splice(r-1,1),this._activeBuffer.lines.splice(i,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}deleteLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let i,s=this._activeBuffer.ybase+this._activeBuffer.y;for(i=this._bufferService.rows-1-this._activeBuffer.scrollBottom,i=this._bufferService.rows-1+this._activeBuffer.ybase-i;t--;)this._activeBuffer.lines.splice(s,1),this._activeBuffer.lines.splice(i,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}insertChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.insertCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}deleteChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.deleteCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}scrollUp(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollDown(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,0,this._activeBuffer.getBlankLine(Ih));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollLeft(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let i=this._activeBuffer.scrollTop;i<=this._activeBuffer.scrollBottom;++i){let e=this._activeBuffer.lines.get(this._activeBuffer.ybase+i);e.deleteCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),e.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollRight(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let i=this._activeBuffer.scrollTop;i<=this._activeBuffer.scrollBottom;++i){let e=this._activeBuffer.lines.get(this._activeBuffer.ybase+i);e.insertCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),e.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}insertColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let i=this._activeBuffer.scrollTop;i<=this._activeBuffer.scrollBottom;++i){let e=this._activeBuffer.lines.get(this._activeBuffer.ybase+i);e.insertCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),e.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}deleteColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let i=this._activeBuffer.scrollTop;i<=this._activeBuffer.scrollBottom;++i){let e=this._activeBuffer.lines.get(this._activeBuffer.ybase+i);e.deleteCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),e.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}eraseChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.replaceCells(this._activeBuffer.x,this._activeBuffer.x+(e.params[0]||1),this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}repeatPrecedingCharacter(e){let t=this._parser.precedingJoinState;if(!t)return!0;let i=e.params[0]||1,s=hd.extractWidth(t),r=this._activeBuffer.x-s,n=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).getString(r),o=new Uint32Array(n.length*i),a=0;for(let c=0;c<n.length;){let e=n.codePointAt(c)||0;o[a++]=e,c+=e>65535?2:1}let l=a;for(let c=1;c<i;++c)o.copyWithin(l,0,a),l+=a;return this.print(o,0,l),!0}sendDeviceAttributesPrimary(e){return e.params[0]>0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(Gl.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(Gl.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(Gl.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(Gl.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(e.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(Gl.ESC+"[>83;40003;0c")),!0}_is(e){return 0===(this._optionsService.rawOptions.termName+"").indexOf(e)}setMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!0;break;case 20:this._optionsService.options.convertEol=!0}return!0}setModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._charsetService.setgCharset(0,Fh),this._charsetService.setgCharset(1,Fh),this._charsetService.setgCharset(2,Fh),this._charsetService.setgCharset(3,Fh);break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(132,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!0,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!0;break;case 12:this._optionsService.options.cursorBlink=!0;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!0;break;case 66:this._logService.debug("Serial port requested application keypad."),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire();break;case 9:this._coreMouseService.activeProtocol="X10";break;case 1e3:this._coreMouseService.activeProtocol="VT200";break;case 1002:this._coreMouseService.activeProtocol="DRAG";break;case 1003:this._coreMouseService.activeProtocol="ANY";break;case 1004:this._coreService.decPrivateModes.sendFocus=!0,this._onRequestSendFocus.fire();break;case 1005:this._logService.debug("DECSET 1005 not supported (see #2507)");break;case 1006:this._coreMouseService.activeEncoding="SGR";break;case 1015:this._logService.debug("DECSET 1015 not supported (see #2507)");break;case 1016:this._coreMouseService.activeEncoding="SGR_PIXELS";break;case 25:this._coreService.isCursorHidden=!1;break;case 1048:this.saveCursor();break;case 1049:this.saveCursor();case 47:case 1047:this._bufferService.buffers.activateAltBuffer(this._eraseAttrData()),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!0;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!0}return!0}resetMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!1;break;case 20:this._optionsService.options.convertEol=!1}return!0}resetModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!1;break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(80,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!1,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!1;break;case 12:this._optionsService.options.cursorBlink=!1;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!1;break;case 66:this._logService.debug("Switching back to normal keypad."),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire();break;case 9:case 1e3:case 1002:case 1003:this._coreMouseService.activeProtocol="NONE";break;case 1004:this._coreService.decPrivateModes.sendFocus=!1;break;case 1005:this._logService.debug("DECRST 1005 not supported (see #2507)");break;case 1006:case 1016:this._coreMouseService.activeEncoding="DEFAULT";break;case 1015:this._logService.debug("DECRST 1015 not supported (see #2507)");break;case 25:this._coreService.isCursorHidden=!0;break;case 1048:this.restoreCursor();break;case 1049:case 47:case 1047:this._bufferService.buffers.activateNormalBuffer(),1049===e.params[t]&&this.restoreCursor(),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!1;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!1,this._onRequestRefreshRows.fire(void 0)}return!0}requestMode(e,t){let i;var s;(s=i||(i={}))[s.NOT_RECOGNIZED=0]="NOT_RECOGNIZED",s[s.SET=1]="SET",s[s.RESET=2]="RESET",s[s.PERMANENTLY_SET=3]="PERMANENTLY_SET",s[s.PERMANENTLY_RESET=4]="PERMANENTLY_RESET";let r=this._coreService.decPrivateModes,{activeProtocol:n,activeEncoding:o}=this._coreMouseService,a=this._coreService,{buffers:l,cols:c}=this._bufferService,{active:h,alt:d}=l,u=this._optionsService.rawOptions,f=(e,i)=>(a.triggerDataEvent(`${Gl.ESC}[${t?"":"?"}${e};${i}$y`),!0),p=e=>e?1:2,m=e.params[0];return f(m,t?2===m?4:4===m?p(a.modes.insertMode):12===m?3:20===m?p(u.convertEol):0:1===m?p(r.applicationCursorKeys):3===m?u.windowOptions.setWinLines?80===c?2:132===c?1:0:0:6===m?p(r.origin):7===m?p(r.wraparound):8===m?3:9===m?p("X10"===n):12===m?p(u.cursorBlink):25===m?p(!a.isCursorHidden):45===m?p(r.reverseWraparound):66===m?p(r.applicationKeypad):67===m?4:1e3===m?p("VT200"===n):1002===m?p("DRAG"===n):1003===m?p("ANY"===n):1004===m?p(r.sendFocus):1005===m?4:1006===m?p("SGR"===o):1015===m?4:1016===m?p("SGR_PIXELS"===o):1048===m?1:47===m||1047===m||1049===m?p(h===d):2004===m?p(r.bracketedPasteMode):2026===m?p(r.synchronizedOutput):0)}_updateAttrColor(e,t,i,s,r){return 2===t?(e|=50331648,e&=-16777216,e|=ro.fromColorRGB([i,s,r])):5===t&&(e&=-50331904,e|=33554432|255&i),e}_extractColor(e,t,i){let s=[0,0,-1,0,0,0],r=0,n=0;do{if(s[n+r]=e.params[t+n],e.hasSubParams(t+n)){let i=e.getSubParams(t+n),o=0;do{5===s[1]&&(r=1),s[n+o+1+r]=i[o]}while(++o<i.length&&o+n+1+r<s.length);break}if(5===s[1]&&n+r>=2||2===s[1]&&n+r>=5)break;s[1]&&(r=1)}while(++n+t<e.length&&n+r<s.length);for(let o=2;o<s.length;++o)-1===s[o]&&(s[o]=0);switch(s[0]){case 38:i.fg=this._updateAttrColor(i.fg,s[1],s[3],s[4],s[5]);break;case 48:i.bg=this._updateAttrColor(i.bg,s[1],s[3],s[4],s[5]);break;case 58:i.extended=i.extended.clone(),i.extended.underlineColor=this._updateAttrColor(i.extended.underlineColor,s[1],s[3],s[4],s[5])}return n}_processUnderline(e,t){t.extended=t.extended.clone(),(!~e||e>5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,0===e&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=Ih.fg,e.bg=Ih.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(1===e.length&&0===e.params[0])return this._processSGR0(this._curAttrData),!0;let t,i=e.length,s=this._curAttrData;for(let r=0;r<i;r++)t=e.params[r],t>=30&&t<=37?(s.fg&=-50331904,s.fg|=16777216|t-30):t>=40&&t<=47?(s.bg&=-50331904,s.bg|=16777216|t-40):t>=90&&t<=97?(s.fg&=-50331904,s.fg|=16777224|t-90):t>=100&&t<=107?(s.bg&=-50331904,s.bg|=16777224|t-100):0===t?this._processSGR0(s):1===t?s.fg|=134217728:3===t?s.bg|=67108864:4===t?(s.fg|=268435456,this._processUnderline(e.hasSubParams(r)?e.getSubParams(r)[0]:1,s)):5===t?s.fg|=536870912:7===t?s.fg|=67108864:8===t?s.fg|=1073741824:9===t?s.fg|=2147483648:2===t?s.bg|=134217728:21===t?this._processUnderline(2,s):22===t?(s.fg&=-134217729,s.bg&=-134217729):23===t?s.bg&=-67108865:24===t?(s.fg&=-268435457,this._processUnderline(0,s)):25===t?s.fg&=-536870913:27===t?s.fg&=-67108865:28===t?s.fg&=-1073741825:29===t?s.fg&=2147483647:39===t?(s.fg&=-67108864,s.fg|=16777215&Ih.fg):49===t?(s.bg&=-67108864,s.bg|=16777215&Ih.bg):38===t||48===t||58===t?r+=this._extractColor(e,r,s):53===t?s.bg|=1073741824:55===t?s.bg&=-1073741825:59===t?(s.extended=s.extended.clone(),s.extended.underlineColor=-1,s.updateExtended()):100===t?(s.fg&=-67108864,s.fg|=16777215&Ih.fg,s.bg&=-67108864,s.bg|=16777215&Ih.bg):this._logService.debug("Unknown SGR attribute: %d.",t);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${Gl.ESC}[0n`);break;case 6:let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${Gl.ESC}[${e};${t}R`)}return!0}deviceStatusPrivate(e){if(6===e.params[0]){let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${Gl.ESC}[?${e};${t}R`)}return!0}softReset(e){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=Ih.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){let t=0===e.length?1:e.params[0];if(0===t)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(t){case 1:case 2:this._coreService.decPrivateModes.cursorStyle="block";break;case 3:case 4:this._coreService.decPrivateModes.cursorStyle="underline";break;case 5:case 6:this._coreService.decPrivateModes.cursorStyle="bar"}let e=t%2==1;this._coreService.decPrivateModes.cursorBlink=e}return!0}setScrollRegion(e){let t,i=e.params[0]||1;return(e.length<2||(t=e.params[1])>this._bufferService.rows||0===t)&&(t=this._bufferService.rows),t>i&&(this._activeBuffer.scrollTop=i-1,this._activeBuffer.scrollBottom=t-1,this._setCursor(0,0)),!0}windowOptions(e){if(!Ld(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;let t=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:2!==t&&this._onRequestWindowsOptionsReport.fire(0);break;case 16:this._onRequestWindowsOptionsReport.fire(1);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${Gl.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(0===t||2===t)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>10&&this._windowTitleStack.shift()),(0===t||1===t)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>10&&this._iconNameStack.shift());break;case 23:(0===t||2===t)&&this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),(0===t||1===t)&&this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop())}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){let t=[],i=e.split(";");for(;i.length>1;){let e=i.shift(),s=i.shift();if(/^\d+$/.exec(e)){let i=parseInt(e);if(Od(i))if("?"===s)t.push({type:0,index:i});else{let e=Md(s);e&&t.push({type:1,index:i,color:e})}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){let t=e.indexOf(";");if(-1===t)return!0;let i=e.slice(0,t).trim(),s=e.slice(t+1);return s?this._createHyperlink(i,s):!i.trim()&&this._finishHyperlink()}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let i,s=e.split(":"),r=s.findIndex(e=>e.startsWith("id="));return-1!==r&&(i=s[r].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:i,uri:t}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,t){let i=e.split(";");for(let s=0;s<i.length&&!(t>=this._specialColors.length);++s,++t)if("?"===i[s])this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let e=Md(i[s]);e&&this._onColor.fire([{type:1,index:this._specialColors[t],color:e}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;let t=[],i=e.split(";");for(let s=0;s<i.length;++s)if(/^\d+$/.exec(i[s])){let e=parseInt(i[s]);Od(e)&&t.push({type:2,index:e})}return t.length&&this._onColor.fire(t),!0}restoreFgColor(e){return this._onColor.fire([{type:2,index:256}]),!0}restoreBgColor(e){return this._onColor.fire([{type:2,index:257}]),!0}restoreCursorColor(e){return this._onColor.fire([{type:2,index:258}]),!0}nextLine(){return this._activeBuffer.x=0,this.index(),!0}keypadApplicationMode(){return this._logService.debug("Serial port requested application keypad."),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire(),!0}keypadNumericMode(){return this._logService.debug("Switching back to normal keypad."),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire(),!0}selectDefaultCharset(){return this._charsetService.setgLevel(0),this._charsetService.setgCharset(0,Fh),!0}selectCharset(e){return 2!==e.length?(this.selectDefaultCharset(),!0):("/"===e[0]||this._charsetService.setgCharset(Rd[e[0]],Wh[e[1]]||Fh),!0)}index(){return this._restrictCursor(),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=Ih.clone(),this._eraseAttrDataInternal=Ih.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=67108863&this._curAttrData.bg,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){let e=new oo;e.content=4194373,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t<this._bufferService.rows;++t){let i=this._activeBuffer.ybase+this._activeBuffer.y+t,s=this._activeBuffer.lines.get(i);s&&(s.fill(e),s.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(e,t){let i=this._bufferService.buffer,s=this._optionsService.rawOptions;return(e=>(this._coreService.triggerDataEvent(`${Gl.ESC}${e}${Gl.ESC}\\`),!0))('"q'===e?`P1$r${this._curAttrData.isProtected()?1:0}"q`:'"p'===e?'P1$r61;1"p':"r"===e?`P1$r${i.scrollTop+1};${i.scrollBottom+1}r`:"m"===e?"P1$r0m":" q"===e?`P1$r${{block:2,underline:4,bar:6}[s.cursorStyle]-(s.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}},Bd=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){e<this.start?this.start=e:e>this.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(Td=e,e=t,t=Td),e<this.start&&(this.start=e),t>this.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};function Od(e){return 0<=e&&e<256}Bd=Wn([Fn(0,uo)],Bd);var Ad=class extends qo{constructor(e){super(),this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this._register(new da),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(e,t){if(void 0!==t&&this._syncCalls>t)return void(this._syncCalls=0);if(this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;let i;for(this._isSyncWriting=!0;i=this._writeBuffer.shift();){this._action(i);let e=this._callbacks.shift();e&&e()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>5e7)throw new Error("write data discarded, use flow control to avoid losing data");if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput)return this._didUserInput=!1,this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t),void this._innerWrite();setTimeout(()=>this._innerWrite())}this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t)}_innerWrite(e=0,t=!0){let i=e||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let e=this._writeBuffer[this._bufferOffset],s=this._action(e,t);if(s){let e=e=>performance.now()-i>=12?setTimeout(()=>this._innerWrite(0,e)):this._innerWrite(i,e);return void s.catch(e=>(queueMicrotask(()=>{throw e}),Promise.resolve(!1))).then(e)}let r=this._callbacks[this._bufferOffset];if(r&&r(),this._bufferOffset++,this._pendingData-=e.length,performance.now()-i>=12)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>50&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout(()=>this._innerWrite())):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}},zd=class{constructor(e){this._bufferService=e,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(e){let t=this._bufferService.buffer;if(void 0===e.id){let i=t.addMarker(t.ybase+t.y),s={data:e,id:this._nextId++,lines:[i]};return i.onDispose(()=>this._removeMarkerFromLink(s,i)),this._dataByLinkId.set(s.id,s),s.id}let i=e,s=this._getEntryIdKey(i),r=this._entriesWithId.get(s);if(r)return this.addLineToLink(r.id,t.ybase+t.y),r.id;let n=t.addMarker(t.ybase+t.y),o={id:this._nextId++,key:this._getEntryIdKey(i),data:i,lines:[n]};return n.onDispose(()=>this._removeMarkerFromLink(o,n)),this._entriesWithId.set(o.key,o),this._dataByLinkId.set(o.id,o),o.id}addLineToLink(e,t){let i=this._dataByLinkId.get(e);if(i&&i.lines.every(e=>e.line!==t)){let e=this._bufferService.buffer.addMarker(t);i.lines.push(e),e.onDispose(()=>this._removeMarkerFromLink(i,e))}}getLinkData(e){var t;return null==(t=this._dataByLinkId.get(e))?void 0:t.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,t){let i=e.lines.indexOf(t);-1!==i&&(e.lines.splice(i,1),0===e.lines.length&&(void 0!==e.data.id&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};zd=Wn([Fn(0,uo)],zd);var $d=!1,Hd=class extends qo{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new Yo),this._onBinary=this._register(new da),this.onBinary=this._onBinary.event,this._onData=this._register(new da),this.onData=this._onData.event,this._onLineFeed=this._register(new da),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new da),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new da),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new da),this._instantiationService=new Rh,this.optionsService=this._register(new Gh(e)),this._instantiationService.setService(vo,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(qh)),this._instantiationService.setService(uo,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(Lh)),this._instantiationService.setService(go,this._logService),this.coreService=this._register(this._instantiationService.createInstance(ed)),this._instantiationService.setService(po,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(nd)),this._instantiationService.setService(fo,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(hd)),this._instantiationService.setService(xo,this.unicodeService),this._charsetService=this._instantiationService.createInstance(dd),this._instantiationService.setService(mo,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(zd),this._instantiationService.setService(yo,this._oscLinkService),this._inputHandler=this._register(new Id(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(Zo.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(Zo.forward(this._bufferService.onResize,this._onResize)),this._register(Zo.forward(this.coreService.onData,this._onData)),this._register(Zo.forward(this.coreService.onBinary,this._onBinary)),this._register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom(!0))),this._register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this._register(this.optionsService.onMultipleOptionChange(["windowsMode","windowsPty"],()=>this._handleWindowsPtyOptionChange())),this._register(this._bufferService.onScroll(()=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this._register(new Ad((e,t)=>this._inputHandler.parse(e,t))),this._register(Zo.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new da),this._onScroll.event(e=>{var t;null==(t=this._onScrollApi)||t.fire(e.position)})),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(e){for(let t in e)this.optionsService.options[t]=e[t]}write(e,t){this._writeBuffer.write(e,t)}writeSync(e,t){this._logService.logLevel<=3&&!$d&&(this._logService.warn("writeSync is unreliable and will be removed soon."),$d=!0),this._writeBuffer.writeSync(e,t)}input(e,t=!0){this.coreService.triggerDataEvent(e,t)}resize(e,t){isNaN(e)||isNaN(t)||(e=Math.max(e,2),t=Math.max(t,1),this._bufferService.resize(e,t))}scroll(e,t=!1){this._bufferService.scroll(e,t)}scrollLines(e,t){this._bufferService.scrollLines(e,t)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;0!==t&&this.scrollLines(t)}registerEscHandler(e,t){return this._inputHandler.registerEscHandler(e,t)}registerDcsHandler(e,t){return this._inputHandler.registerDcsHandler(e,t)}registerCsiHandler(e,t){return this._inputHandler.registerCsiHandler(e,t)}registerOscHandler(e,t){return this._inputHandler.registerOscHandler(e,t)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1,t=this.optionsService.rawOptions.windowsPty;t&&void 0!==t.buildNumber&&void 0!==t.buildNumber?e="conpty"===t.backend&&t.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let e=[];e.push(this.onLineFeed(ud.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:"H"},()=>(ud(this._bufferService),!1))),this._windowsWrappingHeuristics.value=Ko(()=>{for(let t of e)t.dispose()})}}},Wd={48:["0",")"],49:["1","!"],50:["2","@"],51:["3","#"],52:["4","$"],53:["5","%"],54:["6","^"],55:["7","&"],56:["8","*"],57:["9","("],186:[";",":"],187:["=","+"],188:[",","<"],189:["-","_"],190:[".",">"],191:["/","?"],192:["`","~"],219:["[","{"],220:["\\","|"],221:["]","}"],222:["'",'"']};var Fd=0,Kd=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new rh,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new rh,this._isFlushingDeleted=!1}clear(){this._array.length=0,this._insertedValues.length=0,this._flushInsertedTask.clear(),this._isFlushingInserted=!1,this._deletedIndices.length=0,this._flushDeletedTask.clear(),this._isFlushingDeleted=!1}insert(e){this._flushCleanupDeleted(),0===this._insertedValues.length&&this._flushInsertedTask.enqueue(()=>this._flushInserted()),this._insertedValues.push(e)}_flushInserted(){let e=this._insertedValues.sort((e,t)=>this._getKey(e)-this._getKey(t)),t=0,i=0,s=new Array(this._array.length+this._insertedValues.length);for(let r=0;r<s.length;r++)i>=this._array.length||this._getKey(e[t])<=this._getKey(this._array[i])?(s[r]=e[t],t++):s[r]=this._array[i++];this._array=s,this._insertedValues.length=0}_flushCleanupInserted(){!this._isFlushingInserted&&this._insertedValues.length>0&&this._flushInsertedTask.flush()}delete(e){if(this._flushCleanupInserted(),0===this._array.length)return!1;let t=this._getKey(e);if(void 0===t||-1===(Fd=this._search(t))||this._getKey(this._array[Fd])!==t)return!1;do{if(this._array[Fd]===e)return 0===this._deletedIndices.length&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(Fd),!0}while(++Fd<this._array.length&&this._getKey(this._array[Fd])===t);return!1}_flushDeleted(){this._isFlushingDeleted=!0;let e=this._deletedIndices.sort((e,t)=>e-t),t=0,i=new Array(this._array.length-e.length),s=0;for(let r=0;r<this._array.length;r++)e[t]===r?t++:i[s++]=this._array[r];this._array=i,this._deletedIndices.length=0,this._isFlushingDeleted=!1}_flushCleanupDeleted(){!this._isFlushingDeleted&&this._deletedIndices.length>0&&this._flushDeletedTask.flush()}*getKeyIterator(e){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),0!==this._array.length&&(!((Fd=this._search(e))<0||Fd>=this._array.length)&&this._getKey(this._array[Fd])===e))do{yield this._array[Fd]}while(++Fd<this._array.length&&this._getKey(this._array[Fd])===e)}forEachByKey(e,t){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),0!==this._array.length&&(!((Fd=this._search(e))<0||Fd>=this._array.length)&&this._getKey(this._array[Fd])===e))do{t(this._array[Fd])}while(++Fd<this._array.length&&this._getKey(this._array[Fd])===e)}values(){return this._flushCleanupInserted(),this._flushCleanupDeleted(),[...this._array].values()}_search(e){let t=0,i=this._array.length-1;for(;i>=t;){let s=t+i>>1,r=this._getKey(this._array[s]);if(r>e)i=s-1;else{if(!(r<e)){for(;s>0&&this._getKey(this._array[s-1])===e;)s--;return s}t=s+1}}return t}},Ud=0,Vd=0,qd=class extends qo{constructor(){super(),this._decorations=new Kd(e=>null==e?void 0:e.marker.line),this._onDecorationRegistered=this._register(new da),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new da),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register(Ko(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new Yd(e);if(t){let e=t.marker.onDispose(()=>t.dispose()),i=t.onDispose(()=>{i.dispose(),t&&(this._decorations.delete(t)&&this._onDecorationRemoved.fire(t),e.dispose())});this._decorations.insert(t),this._onDecorationRegistered.fire(t)}return t}reset(){for(let e of this._decorations.values())e.dispose();this._decorations.clear()}*getDecorationsAtCell(e,t,i){let s=0,r=0;for(let n of this._decorations.getKeyIterator(t))s=n.options.x??0,r=s+(n.options.width??1),e>=s&&e<r&&(!i||(n.options.layer??"bottom")===i)&&(yield n)}forEachDecorationAtCell(e,t,i,s){this._decorations.forEachByKey(t,t=>{Ud=t.options.x??0,Vd=Ud+(t.options.width??1),e>=Ud&&e<Vd&&(!i||(t.options.layer??"bottom")===i)&&s(t)})}},Yd=class extends Vo{constructor(e){super(),this.options=e,this.onRenderEmitter=this.add(new da),this.onRender=this.onRenderEmitter.event,this._onDispose=this.add(new da),this.onDispose=this._onDispose.event,this._cachedBg=null,this._cachedFg=null,this.marker=e.marker,this.options.overviewRulerOptions&&!this.options.overviewRulerOptions.position&&(this.options.overviewRulerOptions.position="full")}get backgroundColorRGB(){return null===this._cachedBg&&(this.options.backgroundColor?this._cachedBg=cc.toColor(this.options.backgroundColor):this._cachedBg=void 0),this._cachedBg}get foregroundColorRGB(){return null===this._cachedFg&&(this.options.foregroundColor?this._cachedFg=cc.toColor(this.options.foregroundColor):this._cachedFg=void 0),this._cachedFg}dispose(){this._onDispose.fire(),super.dispose()}},Xd=class{constructor(e,t=1e3){this._renderCallback=e,this._debounceThresholdMS=t,this._lastRefreshMs=0,this._additionalRefreshRequested=!1}dispose(){this._refreshTimeoutID&&clearTimeout(this._refreshTimeoutID)}refresh(e,t,i){this._rowCount=i,e=void 0!==e?e:0,t=void 0!==t?t:this._rowCount-1,this._rowStart=void 0!==this._rowStart?Math.min(this._rowStart,e):e,this._rowEnd=void 0!==this._rowEnd?Math.max(this._rowEnd,t):t;let s=performance.now();if(s-this._lastRefreshMs>=this._debounceThresholdMS)this._lastRefreshMs=s,this._innerRefresh();else if(!this._additionalRefreshRequested){let e=s-this._lastRefreshMs,t=this._debounceThresholdMS-e;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},t)}}_innerRefresh(){if(void 0===this._rowStart||void 0===this._rowEnd||void 0===this._rowCount)return;let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t)}},Gd=class extends qo{constructor(e,t,i,s){super(),this._terminal=e,this._coreBrowserService=i,this._renderService=s,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="";let r=this._coreBrowserService.mainDocument;this._accessibilityContainer=r.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=r.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let n=0;n<this._terminal.rows;n++)this._rowElements[n]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[n]);if(this._topBoundaryFocusListener=e=>this._handleBoundaryFocus(e,0),this._bottomBoundaryFocusListener=e=>this._handleBoundaryFocus(e,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=r.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this._register(new Xd(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this._register(this._terminal.onResize(e=>this._handleResize(e.rows))),this._register(this._terminal.onRender(e=>this._refreshRows(e.start,e.end))),this._register(this._terminal.onScroll(()=>this._refreshRows())),this._register(this._terminal.onA11yChar(e=>this._handleChar(e))),this._register(this._terminal.onLineFeed(()=>this._handleChar("\n"))),this._register(this._terminal.onA11yTab(e=>this._handleTab(e))),this._register(this._terminal.onKey(e=>this._handleKey(e.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(gl(r,"selectionchange",()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(Ko(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t<e;t++)this._handleChar(" ")}_handleChar(e){this._liveRegionLineCount<21&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,"\n"===e&&(this._liveRegionLineCount++,21===this._liveRegionLineCount&&(this._liveRegion.textContent+=Yn())))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),new RegExp("\\p{Control}","u").test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let i=this._terminal.buffer,s=i.lines.length.toString();for(let r=e;r<=t;r++){let e=i.lines.get(i.ydisp+r),t=[],n=(null==e?void 0:e.translateToString(!0,void 0,void 0,t))||"",o=(i.ydisp+r+1).toString(),a=this._rowElements[r];a&&(0===n.length?(a.textContent=" ",this._rowColumns.set(a,[0,1])):(a.textContent=n,this._rowColumns.set(a,t)),a.setAttribute("aria-posinset",o),a.setAttribute("aria-setsize",s),this._alignRowWidth(a))}this._announceCharacters()}_announceCharacters(){0!==this._charsToAnnounce.length&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(e,t){let i,s,r=e.target,n=this._rowElements[0===t?1:this._rowElements.length-2];if(r.getAttribute("aria-posinset")!==(0===t?"1":`${this._terminal.buffer.lines.length}`)&&e.relatedTarget===n){if(0===t?(i=r,s=this._rowElements.pop(),this._rowContainer.removeChild(s)):(i=this._rowElements.shift(),s=r,this._rowContainer.removeChild(i)),i.removeEventListener("focus",this._topBoundaryFocusListener),s.removeEventListener("focus",this._bottomBoundaryFocusListener),0===t){let e=this._createAccessibilityTreeNode();this._rowElements.unshift(e),this._rowContainer.insertAdjacentElement("afterbegin",e)}else{let e=this._createAccessibilityTreeNode();this._rowElements.push(e),this._rowContainer.appendChild(e)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(0===t?-1:1),this._rowElements[0===t?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}}_handleSelectionChange(){var e;if(0===this._rowElements.length)return;let t=this._coreBrowserService.mainDocument.getSelection();if(!t)return;if(t.isCollapsed)return void(this._rowContainer.contains(t.anchorNode)&&this._terminal.clearSelection());if(!t.anchorNode||!t.focusNode)return void console.error("anchorNode and/or focusNode are null");let i={node:t.anchorNode,offset:t.anchorOffset},s={node:t.focusNode,offset:t.focusOffset};if((i.node.compareDocumentPosition(s.node)&Node.DOCUMENT_POSITION_PRECEDING||i.node===s.node&&i.offset>s.offset)&&([i,s]=[s,i]),i.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(i={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(i.node))return;let r=this._rowElements.slice(-1)[0];if(s.node.compareDocumentPosition(r)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(s={node:r,offset:(null==(e=r.textContent)?void 0:e.length)??0}),!this._rowContainer.contains(s.node))return;let n=({node:e,offset:t})=>{let i=e instanceof Text?e.parentNode:e,s=parseInt(null==i?void 0:i.getAttribute("aria-posinset"),10)-1;if(isNaN(s))return console.warn("row is invalid. Race condition?"),null;let r=this._rowColumns.get(i);if(!r)return console.warn("columns is null. Race condition?"),null;let n=t<r.length?r[t]:r.slice(-1)[0]+1;return n>=this._terminal.cols&&(++s,n=0),{row:s,column:n}},o=n(i),a=n(s);if(o&&a){if(o.row>a.row||o.row===a.row&&o.column>=a.column)throw new Error("invalid range");this._terminal.select(o.column,o.row,(a.row-o.row)*this._terminal.cols-o.column+a.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let t=this._rowContainer.children.length;t<this._terminal.rows;t++)this._rowElements[t]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[t]);for(;this._rowElements.length>e;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){let e=this._coreBrowserService.mainDocument.createElement("div");return e.setAttribute("role","listitem"),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e<this._terminal.rows;e++)this._refreshRowDimensions(this._rowElements[e]),this._alignRowWidth(this._rowElements[e])}}_refreshRowDimensions(e){e.style.height=`${this._renderService.dimensions.css.cell.height}px`}_alignRowWidth(e){var t,i;e.style.transform="";let s=e.getBoundingClientRect().width,r=null==(i=null==(t=this._rowColumns.get(e))?void 0:t.slice(-1))?void 0:i[0];if(!r)return;let n=r*this._renderService.dimensions.css.cell.width;e.style.transform=`scaleX(${n/s})`}};Gd=Wn([Fn(1,_o),Fn(2,ko),Fn(3,No)],Gd);var Zd=class extends qo{constructor(e,t,i,s,r){super(),this._element=e,this._mouseService=t,this._renderService=i,this._bufferService=s,this._linkProviderService=r,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this._register(new da),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this._register(new da),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this._register(Ko(()=>{var e;Fo(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,null==(e=this._activeProviderReplies)||e.clear()})),this._register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this._register(gl(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(gl(this._element,"mousemove",this._handleMouseMove.bind(this))),this._register(gl(this._element,"mousedown",this._handleMouseDown.bind(this))),this._register(gl(this._element,"mouseup",this._handleMouseUp.bind(this)))}get currentLink(){return this._currentLink}_handleMouseMove(e){this._lastMouseEvent=e;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);if(!t)return;this._isMouseOut=!1;let i=e.composedPath();for(let s=0;s<i.length;s++){let e=i[s];if(e.classList.contains("xterm"))break;if(e.classList.contains("xterm-hover"))return}(!this._lastBufferCell||t.x!==this._lastBufferCell.x||t.y!==this._lastBufferCell.y)&&(this._handleHover(t),this._lastBufferCell=t)}_handleHover(e){if(this._activeLine!==e.y||this._wasResized)return this._clearCurrentLink(),this._askForLink(e,!1),void(this._wasResized=!1);this._currentLink&&this._linkAtPosition(this._currentLink.link,e)||(this._clearCurrentLink(),this._askForLink(e,!0))}_askForLink(e,t){var i,s;(!this._activeProviderReplies||!t)&&(null==(i=this._activeProviderReplies)||i.forEach(e=>{null==e||e.forEach(e=>{e.link.dispose&&e.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let r=!1;for(let[n,o]of this._linkProviderService.linkProviders.entries())t?(null==(s=this._activeProviderReplies)?void 0:s.get(n))&&(r=this._checkLinkProviderResult(n,e,r)):o.provideLinks(e.y,t=>{var i,s;if(this._isMouseOut)return;let o=null==t?void 0:t.map(e=>({link:e}));null==(i=this._activeProviderReplies)||i.set(n,o),r=this._checkLinkProviderResult(n,e,r),(null==(s=this._activeProviderReplies)?void 0:s.size)===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,t){let i=new Set;for(let s=0;s<t.size;s++){let r=t.get(s);if(r)for(let t=0;t<r.length;t++){let s=r[t],n=s.link.range.start.y<e?0:s.link.range.start.x,o=s.link.range.end.y>e?this._bufferService.cols:s.link.range.end.x;for(let e=n;e<=o;e++){if(i.has(e)){r.splice(t--,1);break}i.add(e)}}}}_checkLinkProviderResult(e,t,i){var s;if(!this._activeProviderReplies)return i;let r=this._activeProviderReplies.get(e),n=!1;for(let o=0;o<e;o++)(!this._activeProviderReplies.has(o)||this._activeProviderReplies.get(o))&&(n=!0);if(!n&&r){let e=r.find(e=>this._linkAtPosition(e.link,t));e&&(i=!0,this._handleNewLink(e))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!i)for(let o=0;o<this._activeProviderReplies.size;o++){let e=null==(s=this._activeProviderReplies.get(o))?void 0:s.find(e=>this._linkAtPosition(e.link,t));if(e){i=!0,this._handleNewLink(e);break}}return i}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);var i,s;t&&this._mouseDownLink&&(i=this._mouseDownLink.link,s=this._currentLink.link,i.text===s.text&&i.range.start.x===s.range.start.x&&i.range.start.y===s.range.start.y&&i.range.end.x===s.range.end.x&&i.range.end.y===s.range.end.y)&&this._linkAtPosition(this._currentLink.link,t)&&this._currentLink.link.activate(e,this._currentLink.link.text)}_clearCurrentLink(e,t){!this._currentLink||!this._lastMouseEvent||(!e||!t||this._currentLink.link.range.start.y>=e&&this._currentLink.link.range.end.y<=t)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,Fo(this._linkCacheDisposables),this._linkCacheDisposables.length=0)}_handleNewLink(e){if(!this._lastMouseEvent)return;let t=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);t&&this._linkAtPosition(e.link,t)&&(this._currentLink=e,this._currentLink.state={decorations:{underline:void 0===e.link.decorations||e.link.decorations.underline,pointerCursor:void 0===e.link.decorations||e.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,e.link,this._lastMouseEvent),e.link.decorations={},Object.defineProperties(e.link.decorations,{pointerCursor:{get:()=>{var e,t;return null==(t=null==(e=this._currentLink)?void 0:e.state)?void 0:t.decorations.pointerCursor},set:e=>{var t;(null==(t=this._currentLink)?void 0:t.state)&&this._currentLink.state.decorations.pointerCursor!==e&&(this._currentLink.state.decorations.pointerCursor=e,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",e))}},underline:{get:()=>{var e,t;return null==(t=null==(e=this._currentLink)?void 0:e.state)?void 0:t.decorations.underline},set:t=>{var i,s,r;(null==(i=this._currentLink)?void 0:i.state)&&(null==(r=null==(s=this._currentLink)?void 0:s.state)?void 0:r.decorations.underline)!==t&&(this._currentLink.state.decorations.underline=t,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,t))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(e=>{if(!this._currentLink)return;let t=0===e.start?0:e.start+1+this._bufferService.buffer.ydisp,i=this._bufferService.buffer.ydisp+1+e.end;if(this._currentLink.link.range.start.y>=t&&this._currentLink.link.range.end.y<=i&&(this._clearCurrentLink(t,i),this._lastMouseEvent)){let e=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);e&&this._askForLink(e,!1)}})))}_linkHover(e,t,i){var s;(null==(s=this._currentLink)?void 0:s.state)&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add("xterm-cursor-pointer")),t.hover&&t.hover(i,t.text)}_fireUnderlineEvent(e,t){let i=e.range,s=this._bufferService.buffer.ydisp,r=this._createLinkUnderlineEvent(i.start.x-1,i.start.y-s-1,i.end.x,i.end.y-s-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(r)}_linkLeave(e,t,i){var s;(null==(s=this._currentLink)?void 0:s.state)&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove("xterm-cursor-pointer")),t.leave&&t.leave(i,t.text)}_linkAtPosition(e,t){let i=e.range.start.y*this._bufferService.cols+e.range.start.x,s=e.range.end.y*this._bufferService.cols+e.range.end.x,r=t.y*this._bufferService.cols+t.x;return i<=r&&r<=s}_positionFromMouseEvent(e,t,i){let s=i.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(s)return{x:s[0],y:s[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,i,s,r){return{x1:e,y1:t,x2:i,y2:s,cols:this._bufferService.cols,fg:r}}};Zd=Wn([Fn(1,Eo),Fn(2,No),Fn(3,uo),Fn(4,Ro)],Zd);var Jd=class extends Hd{constructor(e={}){super(e),this._linkifier=this._register(new Yo),this.browser=Fc,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new Yo),this._onCursorMove=this._register(new da),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new da),this.onKey=this._onKey.event,this._onRender=this._register(new da),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new da),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new da),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new da),this.onBell=this._onBell.event,this._onFocus=this._register(new da),this._onBlur=this._register(new da),this._onA11yCharEmitter=this._register(new da),this._onA11yTabEmitter=this._register(new da),this._onWillOpen=this._register(new da),this._setup(),this._decorationService=this._instantiationService.createInstance(qd),this._instantiationService.setService(bo,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(zc),this._instantiationService.setService(Ro,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(wo)),this._register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this._register(this._inputHandler.onRequestRefreshRows(e=>this.refresh((null==e?void 0:e.start)??0,(null==e?void 0:e.end)??this.rows-1))),this._register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this._register(this._inputHandler.onRequestReset(()=>this.reset())),this._register(this._inputHandler.onRequestWindowsOptionsReport(e=>this._reportWindowsOptions(e))),this._register(this._inputHandler.onColor(e=>this._handleColorEvent(e))),this._register(Zo.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(Zo.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(Zo.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(Zo.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(e=>this._afterResize(e.cols,e.rows))),this._register(Ko(()=>{var e,t;this._customKeyEventHandler=void 0,null==(t=null==(e=this.element)?void 0:e.parentNode)||t.removeChild(this.element)}))}get linkifier(){return this._linkifier.value}get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}_handleColorEvent(e){if(this._themeService)for(let t of e){let e,i="";switch(t.index){case 256:e="foreground",i="10";break;case 257:e="background",i="11";break;case 258:e="cursor",i="12";break;default:e="ansi",i="4;"+t.index}switch(t.type){case 0:let s=lc.toColorRGB("ansi"===e?this._themeService.colors.ansi[t.index]:this._themeService.colors[e]);this.coreService.triggerDataEvent(`${Gl.ESC}]${i};${Dd(s)}${ec.ST}`);break;case 1:if("ansi"===e)this._themeService.modifyColors(e=>e.ansi[t.index]=ac.toColor(...t.color));else{let i=e;this._themeService.modifyColors(e=>e[i]=ac.toColor(...t.color))}break;case 2:this._themeService.restoreColor(t.index)}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(e){e?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(Gd,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(Gl.ESC+"[I"),this.element.classList.add("focus"),this._showCursor(),this._onFocus.fire()}blur(){var e;return null==(e=this.textarea)?void 0:e.blur()}_handleTextAreaBlur(){this.textarea.value="",this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(Gl.ESC+"[O"),this.element.classList.remove("focus"),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;let e=this.buffer.ybase+this.buffer.y,t=this.buffer.lines.get(e);if(!t)return;let i=Math.min(this.buffer.x,this.cols-1),s=this._renderService.dimensions.css.cell.height,r=t.getWidth(i),n=this._renderService.dimensions.css.cell.width*r,o=this.buffer.y*this._renderService.dimensions.css.cell.height,a=i*this._renderService.dimensions.css.cell.width;this.textarea.style.left=a+"px",this.textarea.style.top=o+"px",this.textarea.style.width=n+"px",this.textarea.style.height=s+"px",this.textarea.style.lineHeight=s+"px",this.textarea.style.zIndex="-5"}_initGlobal(){this._bindKeys(),this._register(gl(this.element,"copy",e=>{var t,i;this.hasSelection()&&(t=e,i=this._selectionService,t.clipboardData&&t.clipboardData.setData("text/plain",i.selectionText),t.preventDefault())}));let e=e=>function(e,t,i,s){e.stopPropagation(),e.clipboardData&&Gn(e.clipboardData.getData("text/plain"),t,i,s)}(e,this.textarea,this.coreService,this.optionsService);this._register(gl(this.textarea,"paste",e)),this._register(gl(this.element,"paste",e)),qc?this._register(gl(this.element,"mousedown",e=>{2===e.button&&Jn(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(gl(this.element,"contextmenu",e=>{Jn(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),th&&this._register(gl(this.element,"auxclick",e=>{1===e.button&&Zn(e,this.textarea,this.screenElement)}))}_bindKeys(){this._register(gl(this.textarea,"keyup",e=>this._keyUp(e),!0)),this._register(gl(this.textarea,"keydown",e=>this._keyDown(e),!0)),this._register(gl(this.textarea,"keypress",e=>this._keyPress(e),!0)),this._register(gl(this.textarea,"compositionstart",()=>this._compositionHelper.compositionstart())),this._register(gl(this.textarea,"compositionupdate",e=>this._compositionHelper.compositionupdate(e))),this._register(gl(this.textarea,"compositionend",()=>this._compositionHelper.compositionend())),this._register(gl(this.textarea,"input",e=>this._inputEvent(e),!0)),this._register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(e){var t;if(!e)throw new Error("Terminal requires a parent element.");if(e.isConnected||this._logService.debug("Terminal.open was called on an element that was not attached to the DOM"),(null==(t=this.element)?void 0:t.ownerDocument.defaultView)&&this._coreBrowserService)return void(this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView));this._document=e.ownerDocument,this.options.documentOverride&&this.options.documentOverride instanceof Document&&(this._document=this.optionsService.rawOptions.documentOverride),this.element=this._document.createElement("div"),this.element.dir="ltr",this.element.classList.add("terminal"),this.element.classList.add("xterm"),e.appendChild(this.element);let i=this._document.createDocumentFragment();this._viewportElement=this._document.createElement("div"),this._viewportElement.classList.add("xterm-viewport"),i.appendChild(this._viewportElement),this.screenElement=this._document.createElement("div"),this.screenElement.classList.add("xterm-screen"),this._register(gl(this.screenElement,"mousemove",e=>this.updateCursorStyle(e))),this._helperContainer=this._document.createElement("div"),this._helperContainer.classList.add("xterm-helpers"),this.screenElement.appendChild(this._helperContainer),i.appendChild(this.screenElement);let s=this.textarea=this._document.createElement("textarea");this.textarea.classList.add("xterm-helper-textarea"),this.textarea.setAttribute("aria-label",Un()),ih||this.textarea.setAttribute("aria-multiline","false"),this.textarea.setAttribute("autocorrect","off"),this.textarea.setAttribute("autocapitalize","off"),this.textarea.setAttribute("spellcheck","false"),this.textarea.tabIndex=0,this._register(this.optionsService.onSpecificOptionChange("disableStdin",()=>s.readOnly=this.optionsService.rawOptions.disableStdin)),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(Oc,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<"u"?window.document:null)),this._instantiationService.setService(ko,this._coreBrowserService),this._register(gl(this.textarea,"focus",e=>this._handleTextAreaFocus(e))),this._register(gl(this.textarea,"blur",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(Lc,this._document,this._helperContainer),this._instantiationService.setService(Co,this._charSizeService),this._themeService=this._instantiationService.createInstance(Mh),this._instantiationService.setService(Do,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(xc),this._instantiationService.setService(jo,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(oh,this.rows,this.screenElement)),this._instantiationService.setService(No,this._renderService),this._register(this._renderService.onRenderedViewportChange(e=>this._onRender.fire(e))),this.onResize(e=>this._renderService.resize(e.cols,e.rows)),this._compositionView=this._document.createElement("div"),this._compositionView.classList.add("composition-view"),this._compositionHelper=this._instantiationService.createInstance(oc,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(Hc),this._instantiationService.setService(Eo,this._mouseService);let r=this._linkifier.value=this._register(this._instantiationService.createInstance(Zd,this.screenElement));this.element.appendChild(i);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._register(this.onCursorMove(()=>{this._renderService.handleCursorMove(),this._syncTextArea()})),this._register(this.onResize(()=>this._renderService.handleResize(this.cols,this.rows))),this._register(this.onBlur(()=>this._renderService.handleBlur())),this._register(this.onFocus(()=>this._renderService.handleFocus())),this._viewport=this._register(this._instantiationService.createInstance(Yl,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines(e=>{super.scrollLines(e,!1),this.refresh(0,this.rows-1)})),this._selectionService=this._register(this._instantiationService.createInstance(vh,this.element,this.screenElement,r)),this._instantiationService.setService(Mo,this._selectionService),this._register(this._selectionService.onRequestScrollLines(e=>this.scrollLines(e.amount,e.suppressScrollEvent))),this._register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this._register(this._selectionService.onRequestRedraw(e=>this._renderService.handleSelectionChanged(e.start,e.end,e.columnSelectMode))),this._register(this._selectionService.onLinuxMouseSelection(e=>{this.textarea.value=e,this.textarea.focus(),this.textarea.select()})),this._register(Zo.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{var e;this._selectionService.refresh(),null==(e=this._viewport)||e.queueSync()})),this._register(this._instantiationService.createInstance(Xl,this.screenElement)),this._register(gl(this.element,"mousedown",e=>this._selectionService.handleMouseDown(e))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add("enable-mouse-events")):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(Gd,this)),this._register(this.optionsService.onSpecificOptionChange("screenReaderMode",e=>this._handleScreenReaderModeOptionChange(e))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(nc,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRuler",e=>{!this._overviewRulerRenderer&&e&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(nc,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(Pc,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function i(t){var i,s,r,n,o;let a,l,c=e._mouseService.getMouseReportCoords(t,e.screenElement);if(!c)return!1;switch(t.overrideType||t.type){case"mousemove":l=32,void 0===t.buttons?(a=3,void 0!==t.button&&(a=t.button<3?t.button:3)):a=1&t.buttons?0:4&t.buttons?1:2&t.buttons?2:3;break;case"mouseup":l=0,a=t.button<3?t.button:3;break;case"mousedown":l=1,a=t.button<3?t.button:3;break;case"wheel":if(e._customWheelEventHandler&&!1===e._customWheelEventHandler(t))return!1;let c=t.deltaY;if(0===c||0===e.coreMouseService.consumeWheelEvent(t,null==(n=null==(r=null==(s=null==(i=e._renderService)?void 0:i.dimensions)?void 0:s.device)?void 0:r.cell)?void 0:n.height,null==(o=e._coreBrowserService)?void 0:o.dpr))return!1;l=c<0?0:1,a=4;break;default:return!1}return!(void 0===l||void 0===a||a>4)&&e.coreMouseService.triggerMouseEvent({col:c.col,row:c.row,x:c.x,y:c.y,button:a,action:l,ctrl:t.ctrlKey,alt:t.altKey,shift:t.shiftKey})}let s={mouseup:null,wheel:null,mousedrag:null,mousemove:null},r={mouseup:e=>(i(e),e.buttons||(this._document.removeEventListener("mouseup",s.mouseup),s.mousedrag&&this._document.removeEventListener("mousemove",s.mousedrag)),this.cancel(e)),wheel:e=>(i(e),this.cancel(e,!0)),mousedrag:e=>{e.buttons&&i(e)},mousemove:e=>{e.buttons||i(e)}};this._register(this.coreMouseService.onProtocolChange(e=>{e?("debug"===this.optionsService.rawOptions.logLevel&&this._logService.debug("Binding to mouse events:",this.coreMouseService.explainEvents(e)),this.element.classList.add("enable-mouse-events"),this._selectionService.disable()):(this._logService.debug("Unbinding from mouse events."),this.element.classList.remove("enable-mouse-events"),this._selectionService.enable()),8&e?s.mousemove||(t.addEventListener("mousemove",r.mousemove),s.mousemove=r.mousemove):(t.removeEventListener("mousemove",s.mousemove),s.mousemove=null),16&e?s.wheel||(t.addEventListener("wheel",r.wheel,{passive:!1}),s.wheel=r.wheel):(t.removeEventListener("wheel",s.wheel),s.wheel=null),2&e?s.mouseup||(s.mouseup=r.mouseup):(this._document.removeEventListener("mouseup",s.mouseup),s.mouseup=null),4&e?s.mousedrag||(s.mousedrag=r.mousedrag):(this._document.removeEventListener("mousemove",s.mousedrag),s.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(gl(t,"mousedown",e=>{if(e.preventDefault(),this.focus(),this.coreMouseService.areMouseEventsActive&&!this._selectionService.shouldForceSelection(e))return i(e),s.mouseup&&this._document.addEventListener("mouseup",s.mouseup),s.mousedrag&&this._document.addEventListener("mousemove",s.mousedrag),this.cancel(e)})),this._register(gl(t,"wheel",t=>{var i,r,n,o,a;if(!s.wheel){if(this._customWheelEventHandler&&!1===this._customWheelEventHandler(t))return!1;if(!this.buffer.hasScrollback){if(0===t.deltaY)return!1;if(0===e.coreMouseService.consumeWheelEvent(t,null==(o=null==(n=null==(r=null==(i=e._renderService)?void 0:i.dimensions)?void 0:r.device)?void 0:n.cell)?void 0:o.height,null==(a=e._coreBrowserService)?void 0:a.dpr))return this.cancel(t,!0);let s=Gl.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(t.deltaY<0?"A":"B");return this.coreService.triggerDataEvent(s,!0),this.cancel(t,!0)}}},{passive:!1}))}refresh(e,t){var i;null==(i=this._renderService)||i.refreshRows(e,t)}updateCursorStyle(e){var t;(null==(t=this._selectionService)?void 0:t.shouldColumnSelect(e))?this.element.classList.add("column-select"):this.element.classList.remove("column-select")}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(e,t){this._viewport?this._viewport.scrollLines(e):super.scrollLines(e,t),this.refresh(0,this.rows-1)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){e&&this._viewport?this._viewport.scrollToLine(this.buffer.ybase,!0):this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;0!==t&&this.scrollLines(t)}paste(e){Gn(e,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(e){this._customKeyEventHandler=e}attachCustomWheelEventHandler(e){this._customWheelEventHandler=e}registerLinkProvider(e){return this._linkProviderService.registerLinkProvider(e)}registerCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");let t=this._characterJoinerService.register(e);return this.refresh(0,this.rows-1),t}deregisterCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");this._characterJoinerService.deregister(e)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(e){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e)}registerDecoration(e){return this._decorationService.registerDecoration(e)}hasSelection(){return!!this._selectionService&&this._selectionService.hasSelection}select(e,t,i){this._selectionService.setSelection(e,t,i)}getSelection(){return this._selectionService?this._selectionService.selectionText:""}getSelectionPosition(){if(this._selectionService&&this._selectionService.hasSelection)return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){var e;null==(e=this._selectionService)||e.clearSelection()}selectAll(){var e;null==(e=this._selectionService)||e.selectAll()}selectLines(e,t){var i;null==(i=this._selectionService)||i.selectLines(e,t)}_keyDown(e){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&!1===this._customKeyEventHandler(e))return!1;let t=this.browser.isMac&&this.options.macOptionIsMeta&&e.altKey;if(!t&&!this._compositionHelper.keydown(e))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(!0),!1;!t&&("Dead"===e.key||"AltGraph"===e.key)&&(this._unprocessedDeadKey=!0);let i=function(e,t,i,s){var r;let n={type:0,cancel:!1,key:void 0},o=(e.shiftKey?1:0)|(e.altKey?2:0)|(e.ctrlKey?4:0)|(e.metaKey?8:0);switch(e.keyCode){case 0:"UIKeyInputUpArrow"===e.key?n.key=t?Gl.ESC+"OA":Gl.ESC+"[A":"UIKeyInputLeftArrow"===e.key?n.key=t?Gl.ESC+"OD":Gl.ESC+"[D":"UIKeyInputRightArrow"===e.key?n.key=t?Gl.ESC+"OC":Gl.ESC+"[C":"UIKeyInputDownArrow"===e.key&&(n.key=t?Gl.ESC+"OB":Gl.ESC+"[B");break;case 8:n.key=e.ctrlKey?"\b":Gl.DEL,e.altKey&&(n.key=Gl.ESC+n.key);break;case 9:if(e.shiftKey){n.key=Gl.ESC+"[Z";break}n.key=Gl.HT,n.cancel=!0;break;case 13:n.key=e.altKey?Gl.ESC+Gl.CR:Gl.CR,n.cancel=!0;break;case 27:n.key=Gl.ESC,e.altKey&&(n.key=Gl.ESC+Gl.ESC),n.cancel=!0;break;case 37:if(e.metaKey)break;n.key=o?Gl.ESC+"[1;"+(o+1)+"D":t?Gl.ESC+"OD":Gl.ESC+"[D";break;case 39:if(e.metaKey)break;n.key=o?Gl.ESC+"[1;"+(o+1)+"C":t?Gl.ESC+"OC":Gl.ESC+"[C";break;case 38:if(e.metaKey)break;n.key=o?Gl.ESC+"[1;"+(o+1)+"A":t?Gl.ESC+"OA":Gl.ESC+"[A";break;case 40:if(e.metaKey)break;n.key=o?Gl.ESC+"[1;"+(o+1)+"B":t?Gl.ESC+"OB":Gl.ESC+"[B";break;case 45:!e.shiftKey&&!e.ctrlKey&&(n.key=Gl.ESC+"[2~");break;case 46:n.key=o?Gl.ESC+"[3;"+(o+1)+"~":Gl.ESC+"[3~";break;case 36:n.key=o?Gl.ESC+"[1;"+(o+1)+"H":t?Gl.ESC+"OH":Gl.ESC+"[H";break;case 35:n.key=o?Gl.ESC+"[1;"+(o+1)+"F":t?Gl.ESC+"OF":Gl.ESC+"[F";break;case 33:e.shiftKey?n.type=2:e.ctrlKey?n.key=Gl.ESC+"[5;"+(o+1)+"~":n.key=Gl.ESC+"[5~";break;case 34:e.shiftKey?n.type=3:e.ctrlKey?n.key=Gl.ESC+"[6;"+(o+1)+"~":n.key=Gl.ESC+"[6~";break;case 112:n.key=o?Gl.ESC+"[1;"+(o+1)+"P":Gl.ESC+"OP";break;case 113:n.key=o?Gl.ESC+"[1;"+(o+1)+"Q":Gl.ESC+"OQ";break;case 114:n.key=o?Gl.ESC+"[1;"+(o+1)+"R":Gl.ESC+"OR";break;case 115:n.key=o?Gl.ESC+"[1;"+(o+1)+"S":Gl.ESC+"OS";break;case 116:n.key=o?Gl.ESC+"[15;"+(o+1)+"~":Gl.ESC+"[15~";break;case 117:n.key=o?Gl.ESC+"[17;"+(o+1)+"~":Gl.ESC+"[17~";break;case 118:n.key=o?Gl.ESC+"[18;"+(o+1)+"~":Gl.ESC+"[18~";break;case 119:n.key=o?Gl.ESC+"[19;"+(o+1)+"~":Gl.ESC+"[19~";break;case 120:n.key=o?Gl.ESC+"[20;"+(o+1)+"~":Gl.ESC+"[20~";break;case 121:n.key=o?Gl.ESC+"[21;"+(o+1)+"~":Gl.ESC+"[21~";break;case 122:n.key=o?Gl.ESC+"[23;"+(o+1)+"~":Gl.ESC+"[23~";break;case 123:n.key=o?Gl.ESC+"[24;"+(o+1)+"~":Gl.ESC+"[24~";break;default:if(!e.ctrlKey||e.shiftKey||e.altKey||e.metaKey)if(i&&!s||!e.altKey||e.metaKey)!i||e.altKey||e.ctrlKey||e.shiftKey||!e.metaKey?e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.keyCode>=48&&1===e.key.length?n.key=e.key:e.key&&e.ctrlKey&&("_"===e.key&&(n.key=Gl.US),"@"===e.key&&(n.key=Gl.NUL)):65===e.keyCode&&(n.type=1);else{let t=null==(r=Wd[e.keyCode])?void 0:r[e.shiftKey?1:0];if(t)n.key=Gl.ESC+t;else if(e.keyCode>=65&&e.keyCode<=90){let t=e.ctrlKey?e.keyCode-64:e.keyCode+32,i=String.fromCharCode(t);e.shiftKey&&(i=i.toUpperCase()),n.key=Gl.ESC+i}else if(32===e.keyCode)n.key=Gl.ESC+(e.ctrlKey?Gl.NUL:" ");else if("Dead"===e.key&&e.code.startsWith("Key")){let t=e.code.slice(3,4);e.shiftKey||(t=t.toLowerCase()),n.key=Gl.ESC+t,n.cancel=!0}}else e.keyCode>=65&&e.keyCode<=90?n.key=String.fromCharCode(e.keyCode-64):32===e.keyCode?n.key=Gl.NUL:e.keyCode>=51&&e.keyCode<=55?n.key=String.fromCharCode(e.keyCode-51+27):56===e.keyCode?n.key=Gl.DEL:219===e.keyCode?n.key=Gl.ESC:220===e.keyCode?n.key=Gl.FS:221===e.keyCode&&(n.key=Gl.GS)}return n}(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),3===i.type||2===i.type){let t=this.rows-1;return this.scrollLines(2===i.type?-t:t),this.cancel(e,!0)}return 1===i.type&&this.selectAll(),!!(this._isThirdLevelShift(this.browser,e)||(i.cancel&&this.cancel(e,!0),!i.key)||e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&1===e.key.length&&e.key.charCodeAt(0)>=65&&e.key.charCodeAt(0)<=90)||(this._unprocessedDeadKey?(this._unprocessedDeadKey=!1,!0):((i.key===Gl.ETX||i.key===Gl.CR)&&(this.textarea.value=""),this._onKey.fire({key:i.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(i.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey?this.cancel(e,!0):void(this._keyDownHandled=!0)))}_isThirdLevelShift(e,t){let i=e.isMac&&!this.options.macOptionIsMeta&&t.altKey&&!t.ctrlKey&&!t.metaKey||e.isWindows&&t.altKey&&t.ctrlKey&&!t.metaKey||e.isWindows&&t.getModifierState("AltGraph");return"keypress"===t.type?i:i&&(!t.keyCode||t.keyCode>47)}_keyUp(e){var t;this._keyDownSeen=!1,(!this._customKeyEventHandler||!1!==this._customKeyEventHandler(e))&&(16===(t=e).keyCode||17===t.keyCode||18===t.keyCode||this.focus(),this.updateCursorStyle(e),this._keyPressHandled=!1)}_keyPress(e){let t;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&!1===this._customKeyEventHandler(e))return!1;if(this.cancel(e),e.charCode)t=e.charCode;else if(null===e.which||void 0===e.which)t=e.keyCode;else{if(0===e.which||0===e.charCode)return!1;t=e.which}return!(!t||(e.altKey||e.ctrlKey||e.metaKey)&&!this._isThirdLevelShift(this.browser,e))&&(t=String.fromCharCode(t),this._onKey.fire({key:t,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(t,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,!0)}_inputEvent(e){if(e.data&&"insertText"===e.inputType&&(!e.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;let t=e.data;return this.coreService.triggerDataEvent(t,!0),this.cancel(e),!0}return!1}resize(e,t){e!==this.cols||t!==this.rows?super.resize(e,t):this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure()}_afterResize(e,t){var i;null==(i=this._charSizeService)||i.measure()}clear(){if(0!==this.buffer.ybase||0!==this.buffer.y){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let e=1;e<this.rows;e++)this.buffer.lines.push(this.buffer.getBlankLine(Ih));this._onScroll.fire({position:this.buffer.ydisp}),this.refresh(0,this.rows-1)}}reset(){var e;this.options.rows=this.rows,this.options.cols=this.cols;let t=this._customKeyEventHandler;this._setup(),super.reset(),null==(e=this._selectionService)||e.reset(),this._decorationService.reset(),this._customKeyEventHandler=t,this.refresh(0,this.rows-1)}clearTextureAtlas(){var e;null==(e=this._renderService)||e.clearTextureAtlas()}_reportFocus(){var e;(null==(e=this.element)?void 0:e.classList.contains("focus"))?this.coreService.triggerDataEvent(Gl.ESC+"[I"):this.coreService.triggerDataEvent(Gl.ESC+"[O")}_reportWindowsOptions(e){if(this._renderService)switch(e){case 0:let e=this._renderService.dimensions.css.canvas.width.toFixed(0),t=this._renderService.dimensions.css.canvas.height.toFixed(0);this.coreService.triggerDataEvent(`${Gl.ESC}[4;${t};${e}t`);break;case 1:let i=this._renderService.dimensions.css.cell.width.toFixed(0),s=this._renderService.dimensions.css.cell.height.toFixed(0);this.coreService.triggerDataEvent(`${Gl.ESC}[6;${s};${i}t`)}}cancel(e,t){if(this.options.cancelEvents||t)return e.preventDefault(),e.stopPropagation(),!1}};var Qd=class{constructor(){this._addons=[]}dispose(){for(let e=this._addons.length-1;e>=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){let i={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(i),t.dispose=()=>this._wrappedAddonDispose(i),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let i=0;i<this._addons.length;i++)if(this._addons[i]===e){t=i;break}if(-1===t)throw new Error("Could not dispose an addon that has not been loaded");e.isDisposed=!0,e.dispose.apply(e.instance),this._addons.splice(t,1)}},eu=class{constructor(e){this._line=e}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(e,t){if(!(e<0||e>=this._line.length))return t?(this._line.loadCell(e,t),t):this._line.loadCell(e,new oo)}translateToString(e,t,i){return this._line.translateToString(e,t,i)}},tu=class{constructor(e,t){this._buffer=e,this.type=t}init(e){return this._buffer=e,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(e){let t=this._buffer.lines.get(e);if(t)return new eu(t)}getNullCell(){return new oo}},iu=class extends qo{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new da),this.onBufferChange=this._onBufferChange.event,this._normal=new tu(this._core.buffers.normal,"normal"),this._alternate=new tu(this._core.buffers.alt,"alternate"),this._core.buffers.onBufferActivate(()=>this._onBufferChange.fire(this.active))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw new Error("Active buffer is neither normal nor alternate")}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}},su=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,e=>t(e.toArray()))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,(e,i)=>t(e,i.toArray()))}addDcsHandler(e,t){return this.registerDcsHandler(e,t)}registerEscHandler(e,t){return this._core.registerEscHandler(e,t)}addEscHandler(e,t){return this.registerEscHandler(e,t)}registerOscHandler(e,t){return this._core.registerOscHandler(e,t)}addOscHandler(e,t){return this.registerOscHandler(e,t)}},ru=class{constructor(e){this._core=e}register(e){this._core.unicodeService.register(e)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(e){this._core.unicodeService.activeVersion=e}},nu=["cols","rows"],ou=0,au=class extends qo{constructor(e){super(),this._core=this._register(new Jd(e)),this._addonManager=this._register(new Qd),this._publicOptions={...this._core.options};let t=e=>this._core.options[e],i=(e,t)=>{this._checkReadonlyOptions(e),this._core.options[e]=t};for(let s in this._core.options){let e={get:t.bind(this,s),set:i.bind(this,s)};Object.defineProperty(this._publicOptions,s,e)}}_checkReadonlyOptions(e){if(nu.includes(e))throw new Error(`Option "${e}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw new Error("You must set the allowProposedApi option to true to use proposed API")}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||(this._parser=new su(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new ru(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||(this._buffer=this._register(new iu(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let e=this._core.coreService.decPrivateModes,t="none";switch(this._core.coreMouseService.activeProtocol){case"X10":t="x10";break;case"VT200":t="vt200";break;case"DRAG":t="drag";break;case"ANY":t="any"}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:t,originMode:e.origin,reverseWraparoundMode:e.reverseWraparound,sendFocusMode:e.sendFocus,synchronizedOutputMode:e.synchronizedOutput,wraparoundMode:e.wraparound}}get options(){return this._publicOptions}set options(e){for(let t in e)this._publicOptions[t]=e[t]}blur(){this._core.blur()}focus(){this._core.focus()}input(e,t=!0){this._core.input(e,t)}resize(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)}open(e){this._core.open(e)}attachCustomKeyEventHandler(e){this._core.attachCustomKeyEventHandler(e)}attachCustomWheelEventHandler(e){this._core.attachCustomWheelEventHandler(e)}registerLinkProvider(e){return this._core.registerLinkProvider(e)}registerCharacterJoiner(e){return this._checkProposedApi(),this._core.registerCharacterJoiner(e)}deregisterCharacterJoiner(e){this._checkProposedApi(),this._core.deregisterCharacterJoiner(e)}registerMarker(e=0){return this._verifyIntegers(e),this._core.registerMarker(e)}registerDecoration(e){return this._checkProposedApi(),this._verifyPositiveIntegers(e.x??0,e.width??0,e.height??0),this._core.registerDecoration(e)}hasSelection(){return this._core.hasSelection()}select(e,t,i){this._verifyIntegers(e,t,i),this._core.select(e,t,i)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(e,t){this._verifyIntegers(e,t),this._core.selectLines(e,t)}dispose(){super.dispose()}scrollLines(e){this._verifyIntegers(e),this._core.scrollLines(e)}scrollPages(e){this._verifyIntegers(e),this._core.scrollPages(e)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(e){this._verifyIntegers(e),this._core.scrollToLine(e)}clear(){this._core.clear()}write(e,t){this._core.write(e,t)}writeln(e,t){this._core.write(e),this._core.write("\r\n",t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return Un()},set promptLabel(e){Vn(e)},get tooMuchOutput(){return Yn()},set tooMuchOutput(e){Xn(e)}}}_verifyIntegers(...e){for(ou of e)if(ou===1/0||isNaN(ou)||ou%1!=0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...e){for(ou of e)if(ou&&(ou===1/0||isNaN(ou)||ou%1!=0||ou<0))throw new Error("This API only accepts positive integers")}},lu=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){var e;if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let t=this._terminal._core._renderService.dimensions;if(0===t.css.cell.width||0===t.css.cell.height)return;let i=0===this._terminal.options.scrollback?0:(null==(e=this._terminal.options.overviewRuler)?void 0:e.width)||14,s=window.getComputedStyle(this._terminal.element.parentElement),r=parseInt(s.getPropertyValue("height")),n=Math.max(0,parseInt(s.getPropertyValue("width"))),o=window.getComputedStyle(this._terminal.element),a=r-(parseInt(o.getPropertyValue("padding-top"))+parseInt(o.getPropertyValue("padding-bottom"))),l=n-(parseInt(o.getPropertyValue("padding-right"))+parseInt(o.getPropertyValue("padding-left")))-i;return{cols:Math.max(2,Math.floor(l/t.css.cell.width)),rows:Math.max(1,Math.floor(a/t.css.cell.height))}}},cu=new class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?_u.isErrorNoTelemetry(e)?new _u(e.message+"\n\n"+e.stack):new Error(e.message+"\n\n"+e.stack):e},0)}}addListener(e){return this.listeners.push(e),()=>{this._removeListener(e)}}emit(e){this.listeners.forEach(t=>{t(e)})}_removeListener(e){this.listeners.splice(this.listeners.indexOf(e),1)}setUnexpectedErrorHandler(e){this.unexpectedErrorHandler=e}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(e){this.unexpectedErrorHandler(e),this.emit(e)}onUnexpectedExternalError(e){this.unexpectedErrorHandler(e)}};function hu(e){(function(e){return e instanceof mu||e instanceof Error&&e.name===du&&e.message===du})(e)||cu.onUnexpectedError(e)}var du="Canceled";var uu,fu,pu,mu=class extends Error{constructor(){super(du),this.name=this.message}},_u=class e extends Error{constructor(e){super(e),this.name="CodeExpectedError"}static fromError(t){if(t instanceof e)return t;let i=new e;return i.message=t.message,i.stack=t.stack,i}static isErrorNoTelemetry(e){return"CodeExpectedError"===e.name}};function gu(e,t){let i,s=this,r=!1;return function(){return r||(r=!0,t||(i=e.apply(s,arguments))),i}}function vu(e){if(pu.is(e)){let t=[];for(let i of e)if(i)try{i.dispose()}catch(Nl){t.push(Nl)}if(1===t.length)throw t[0];if(t.length>1)throw new AggregateError(t,"Encountered errors while disposing of store");return Array.isArray(e)?[]:e}if(e)return e.dispose(),e}function yu(...e){return xu(()=>vu(e))}function xu(e){return{dispose:gu(()=>{e()})}}(fu=uu||(uu={})).isLessThan=function(e){return e<0},fu.isLessThanOrEqual=function(e){return e<=0},fu.isGreaterThan=function(e){return e>0},fu.isNeitherLessOrGreaterThan=function(e){return 0===e},fu.greaterThan=1,fu.lessThan=-1,fu.neitherLessOrGreaterThan=0,(e=>{function t(e){return e&&"object"==typeof e&&"function"==typeof e[Symbol.iterator]}e.is=t;let i=Object.freeze([]);function*s(e){yield e}e.empty=function(){return i},e.single=s,e.wrap=function(e){return t(e)?e:s(e)},e.from=function(e){return e||i},e.reverse=function*(e){for(let t=e.length-1;t>=0;t--)yield e[t]},e.isEmpty=function(e){return!e||!0===e[Symbol.iterator]().next().done},e.first=function(e){return e[Symbol.iterator]().next().value},e.some=function(e,t){let i=0;for(let s of e)if(t(s,i++))return!0;return!1},e.find=function(e,t){for(let i of e)if(t(i))return i},e.filter=function*(e,t){for(let i of e)t(i)&&(yield i)},e.map=function*(e,t){let i=0;for(let s of e)yield t(s,i++)},e.flatMap=function*(e,t){let i=0;for(let s of e)yield*t(s,i++)},e.concat=function*(...e){for(let t of e)yield*t},e.reduce=function(e,t,i){let s=i;for(let r of e)s=t(s,r);return s},e.slice=function*(e,t,i=e.length){for(t<0&&(t+=e.length),i<0?i+=e.length:i>e.length&&(i=e.length);t<i;t++)yield e[t]},e.consume=function(t,i=Number.POSITIVE_INFINITY){let s=[];if(0===i)return[s,t];let r=t[Symbol.iterator]();for(let n=0;n<i;n++){let t=r.next();if(t.done)return[s,e.empty()];s.push(t.value)}return[s,{[Symbol.iterator]:()=>r}]},e.asyncToArray=async function(e){let t=[];for await(let i of e)t.push(i);return Promise.resolve(t)}})(pu||(pu={}));var bu=class e{constructor(){this._toDispose=new Set,this._isDisposed=!1}dispose(){this._isDisposed||(this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(0!==this._toDispose.size)try{vu(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw new Error("Cannot register a disposable on itself!");return this._isDisposed?e.DISABLE_DISPOSED_WARNING||console.warn(new Error("Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!").stack):this._toDispose.add(t),t}delete(e){if(e){if(e===this)throw new Error("Cannot dispose a disposable on itself!");this._toDispose.delete(e),e.dispose()}}deleteAndLeak(e){e&&this._toDispose.has(e)&&this._toDispose.delete(e)}};bu.DISABLE_DISPOSED_WARNING=!1;var wu=bu,Su=class{constructor(){this._store=new wu,this._store}dispose(){this._store.dispose()}_register(e){if(e===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(e)}};Su.None=Object.freeze({dispose(){}});var Cu,ku=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(e){var t;this._isDisposed||e===this._value||(null==(t=this._value)||t.dispose(),this._value=e)}clear(){this.value=void 0}dispose(){var e;this._isDisposed=!0,null==(e=this._value)||e.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e}},Eu=globalThis.performance&&"function"==typeof globalThis.performance.now,Nu=class e{static create(t){return new e(t)}constructor(e){this._now=Eu&&!1===e?Date.now:globalThis.performance.now.bind(globalThis.performance),this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=this._now(),this._stopTime=-1}elapsed(){return-1!==this._stopTime?this._stopTime-this._startTime:this._now()-this._startTime}};(e=>{function t(e){return(t,i=null,s)=>{let r,n=!1;return r=e(e=>{if(!n)return r?r.dispose():n=!0,t.call(i,e)},null,s),n&&r.dispose(),r}}function i(e,t,i){return r((i,s=null,r)=>e(e=>i.call(s,t(e)),null,r),i)}function s(e,t,i){return r((i,s=null,r)=>e(e=>t(e)&&i.call(s,e),null,r),i)}function r(e,t){let i,s=new Au({onWillAddFirstListener(){i=e(s.fire,s)},onDidRemoveLastListener(){null==i||i.dispose()}});return null==t||t.add(s),s.event}function n(e,t,i=100,s=!1,r=!1,n,o){let a,l,c,h,d=0,u=new Au({leakWarningThreshold:n,onWillAddFirstListener(){a=e(e=>{d++,l=t(l,e),s&&!c&&(u.fire(l),l=void 0),h=()=>{let e=l;l=void 0,c=void 0,(!s||d>1)&&u.fire(e),d=0},"number"==typeof i?(clearTimeout(c),c=setTimeout(h,i)):void 0===c&&(c=0,queueMicrotask(h))})},onWillRemoveListener(){r&&d>0&&(null==h||h())},onDidRemoveLastListener(){h=void 0,a.dispose()}});return null==o||o.add(u),u.event}e.None=()=>Su.None,e.defer=function(e,t){return n(e,()=>{},0,void 0,!0,void 0,t)},e.once=t,e.map=i,e.forEach=function(e,t,i){return r((i,s=null,r)=>e(e=>{t(e),i.call(s,e)},null,r),i)},e.filter=s,e.signal=function(e){return e},e.any=function(...e){return(t,i=null,s)=>{let r=yu(...e.map(e=>e(e=>t.call(i,e))));return function(e,t){return t instanceof Array?t.push(e):t&&t.add(e),e}(r,s)}},e.reduce=function(e,t,s,r){let n=s;return i(e,e=>(n=t(n,e),n),r)},e.debounce=n,e.accumulate=function(t,i=0,s){return e.debounce(t,(e,t)=>e?(e.push(t),e):[t],i,void 0,!0,void 0,s)},e.latch=function(e,t=(e,t)=>e===t,i){let r,n=!0;return s(e,e=>{let i=n||!t(e,r);return n=!1,r=e,i},i)},e.split=function(t,i,s){return[e.filter(t,i,s),e.filter(t,e=>!i(e),s)]},e.buffer=function(e,t=!1,i=[],s){let r=i.slice(),n=e(e=>{r?r.push(e):a.fire(e)});s&&s.add(n);let o=()=>{null==r||r.forEach(e=>a.fire(e)),r=null},a=new Au({onWillAddFirstListener(){n||(n=e(e=>a.fire(e)),s&&s.add(n))},onDidAddFirstListener(){r&&(t?setTimeout(o):o())},onDidRemoveLastListener(){n&&n.dispose(),n=null}});return s&&s.add(a),a.event},e.chain=function(e,t){return(i,s,r)=>{let n=t(new a);return e(function(e){let t=n.evaluate(e);t!==o&&i.call(s,t)},void 0,r)}};let o=Symbol("HaltChainable");class a{constructor(){this.steps=[]}map(e){return this.steps.push(e),this}forEach(e){return this.steps.push(t=>(e(t),t)),this}filter(e){return this.steps.push(t=>e(t)?t:o),this}reduce(e,t){let i=t;return this.steps.push(t=>(i=e(i,t),i)),this}latch(e=(e,t)=>e===t){let t,i=!0;return this.steps.push(s=>{let r=i||!e(s,t);return i=!1,t=s,r?s:o}),this}evaluate(e){for(let t of this.steps)if((e=t(e))===o)break;return e}}e.fromNodeEventEmitter=function(e,t,i=e=>e){let s=(...e)=>r.fire(i(...e)),r=new Au({onWillAddFirstListener:()=>e.on(t,s),onDidRemoveLastListener:()=>e.removeListener(t,s)});return r.event},e.fromDOMEventEmitter=function(e,t,i=e=>e){let s=(...e)=>r.fire(i(...e)),r=new Au({onWillAddFirstListener:()=>e.addEventListener(t,s),onDidRemoveLastListener:()=>e.removeEventListener(t,s)});return r.event},e.toPromise=function(e){return new Promise(i=>t(e)(i))},e.fromPromise=function(e){let t=new Au;return e.then(e=>{t.fire(e)},()=>{t.fire(void 0)}).finally(()=>{t.dispose()}),t.event},e.forward=function(e,t){return e(e=>t.fire(e))},e.runAndSubscribe=function(e,t,i){return t(i),e(e=>t(e))};class l{constructor(e,t){this._observable=e,this._counter=0,this._hasChanged=!1;let i={onWillAddFirstListener:()=>{e.addObserver(this)},onDidRemoveLastListener:()=>{e.removeObserver(this)}};this.emitter=new Au(i),t&&t.add(this.emitter)}beginUpdate(e){this._counter++}handlePossibleChange(e){}handleChange(e,t){this._hasChanged=!0}endUpdate(e){this._counter--,0===this._counter&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}e.fromObservable=function(e,t){return new l(e,t).emitter.event},e.fromObservableLight=function(e){return(t,i,s)=>{let r=0,n=!1,o={beginUpdate(){r++},endUpdate(){r--,0===r&&(e.reportChanges(),n&&(n=!1,t.call(i)))},handlePossibleChange(){},handleChange(){n=!0}};e.addObserver(o),e.reportChanges();let a={dispose(){e.removeObserver(o)}};return s instanceof wu?s.add(a):Array.isArray(s)&&s.push(a),a}}})(Cu||(Cu={}));var Mu=class e{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${e._idPool++}`,e.all.add(this)}start(e){this._stopWatch=new Nu,this.listenerCount=e}stop(){if(this._stopWatch){let e=this._stopWatch.elapsed();this.durations.push(e),this.elapsedOverall+=e,this.invocationCount+=1,this._stopWatch=void 0}}};Mu.all=new Set,Mu._idPool=0;var ju=Mu,Du=class e{constructor(t,i,s=(e._idPool++).toString(16).padStart(3,"0")){this._errorHandler=t,this.threshold=i,this.name=s,this._warnCountdown=0}dispose(){var e;null==(e=this._stacks)||e.clear()}check(e,t){let i=this.threshold;if(i<=0||t<i)return;this._stacks||(this._stacks=new Map);let s=this._stacks.get(e.value)||0;if(this._stacks.set(e.value,s+1),this._warnCountdown-=1,this._warnCountdown<=0){this._warnCountdown=.5*i;let[e,s]=this.getMostFrequentStack(),r=`[${this.name}] potential listener LEAK detected, having ${t} listeners already. MOST frequent listener (${s}):`;console.warn(r),console.warn(e);let n=new Tu(r,e);this._errorHandler(n)}return()=>{let t=this._stacks.get(e.value)||0;this._stacks.set(e.value,t-1)}}getMostFrequentStack(){if(!this._stacks)return;let e,t=0;for(let[i,s]of this._stacks)(!e||t<s)&&(e=[i,s],t=s);return e}};Du._idPool=1;var Ru,Pu=Du,Lu=class e{constructor(e){this.value=e}static create(){let t=new Error;return new e(t.stack??"")}print(){console.warn(this.value.split("\n").slice(2).join("\n"))}},Tu=class extends Error{constructor(e,t){super(e),this.name="ListenerLeakError",this.stack=t}},Iu=class extends Error{constructor(e,t){super(e),this.name="ListenerRefusalError",this.stack=t}},Bu=0,Ou=class{constructor(e){this.value=e,this.id=Bu++}},Au=class{constructor(e){var t,i,s,r;this._size=0,this._options=e,this._leakageMon=(null==(t=this._options)?void 0:t.leakWarningThreshold)?new Pu((null==e?void 0:e.onListenerError)??hu,(null==(i=this._options)?void 0:i.leakWarningThreshold)??-1):void 0,this._perfMon=(null==(s=this._options)?void 0:s._profName)?new ju(this._options._profName):void 0,this._deliveryQueue=null==(r=this._options)?void 0:r.deliveryQueue}dispose(){var e,t,i,s;this._disposed||(this._disposed=!0,(null==(e=this._deliveryQueue)?void 0:e.current)===this&&this._deliveryQueue.reset(),this._listeners&&(this._listeners=void 0,this._size=0),null==(i=null==(t=this._options)?void 0:t.onDidRemoveLastListener)||i.call(t),null==(s=this._leakageMon)||s.dispose())}get event(){return this._event??(this._event=(e,t,i)=>{var s,r,n,o,a;if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let e=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(e);let t=this._leakageMon.getMostFrequentStack()??["UNKNOWN stack",-1],i=new Iu(`${e}. HINT: Stack shows most frequent listener (${t[1]}-times)`,t[0]);return((null==(s=this._options)?void 0:s.onListenerError)||hu)(i),Su.None}if(this._disposed)return Su.None;t&&(e=e.bind(t));let l,c=new Ou(e);this._leakageMon&&this._size>=Math.ceil(.2*this._leakageMon.threshold)&&(c.stack=Lu.create(),l=this._leakageMon.check(c.stack,this._size+1)),this._listeners?this._listeners instanceof Ou?(this._deliveryQueue??(this._deliveryQueue=new zu),this._listeners=[this._listeners,c]):this._listeners.push(c):(null==(n=null==(r=this._options)?void 0:r.onWillAddFirstListener)||n.call(r,this),this._listeners=c,null==(a=null==(o=this._options)?void 0:o.onDidAddFirstListener)||a.call(o,this)),this._size++;let h=xu(()=>{null==l||l(),this._removeListener(c)});return i instanceof wu?i.add(h):Array.isArray(i)&&i.push(h),h}),this._event}_removeListener(e){var t,i,s,r;if(null==(i=null==(t=this._options)?void 0:t.onWillRemoveListener)||i.call(t,this),!this._listeners)return;if(1===this._size)return this._listeners=void 0,null==(r=null==(s=this._options)?void 0:s.onDidRemoveLastListener)||r.call(s,this),void(this._size=0);let n=this._listeners,o=n.indexOf(e);if(-1===o)throw console.log("disposed?",this._disposed),console.log("size?",this._size),console.log("arr?",JSON.stringify(this._listeners)),new Error("Attempted to dispose unknown listener");this._size--,n[o]=void 0;let a=this._deliveryQueue.current===this;if(2*this._size<=n.length){let e=0;for(let t=0;t<n.length;t++)n[t]?n[e++]=n[t]:a&&(this._deliveryQueue.end--,e<this._deliveryQueue.i&&this._deliveryQueue.i--);n.length=e}}_deliver(e,t){var i;if(!e)return;let s=(null==(i=this._options)?void 0:i.onListenerError)||hu;if(s)try{e.value(t)}catch(Pa){s(Pa)}else e.value(t)}_deliverQueue(e){let t=e.current._listeners;for(;e.i<e.end;)this._deliver(t[e.i++],e.value);e.reset()}fire(e){var t,i,s,r;if((null==(t=this._deliveryQueue)?void 0:t.current)&&(this._deliverQueue(this._deliveryQueue),null==(i=this._perfMon)||i.stop()),null==(s=this._perfMon)||s.start(this._size),this._listeners)if(this._listeners instanceof Ou)this._deliver(this._listeners,e);else{let t=this._deliveryQueue;t.enqueue(this,e,this._listeners.length),this._deliverQueue(t)}null==(r=this._perfMon)||r.stop()}hasListeners(){return this._size>0}},zu=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,i){this.i=0,this.end=i,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},$u=Object.freeze(function(e,t){let i=setTimeout(e.bind(t),0);return{dispose(){clearTimeout(i)}}});(e=>{e.isCancellationToken=function(t){return t===e.None||t===e.Cancelled||t instanceof Fu||!(!t||"object"!=typeof t)&&("boolean"==typeof t.isCancellationRequested&&"function"==typeof t.onCancellationRequested)},e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:Cu.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:$u})})(Ru||(Ru={}));var Hu,Wu,Fu=class{constructor(){this._isCancelled=!1,this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?$u:(this._emitter||(this._emitter=new Au),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}},Ku="en",Uu=Ku,Vu=globalThis;typeof Vu.vscode<"u"&&typeof Vu.vscode.process<"u"?Wu=Vu.vscode.process:typeof process<"u"&&"string"==typeof(null==(s=null==process?void 0:process.versions)?void 0:s.node)&&(Wu=process);var qu="string"==typeof(null==(r=null==Wu?void 0:Wu.versions)?void 0:r.electron)&&"renderer"===(null==Wu?void 0:Wu.type);if("object"==typeof Wu){Wu.platform,Wu.platform,"linux"===Wu.platform&&!!Wu.env.SNAP&&Wu.env.SNAP_REVISION,!!Wu.env.CI||Wu.env.BUILD_ARTIFACTSTAGINGDIRECTORY,Uu=Ku;let e=Wu.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);t.userLocale,t.osLocale,Uu=t.resolvedLanguage||Ku,null==(n=t.languagePack)?void 0:n.translationsConfigFile}catch{}}else"object"!=typeof navigator||qu?console.error("Unable to resolve platform."):((Hu=navigator.userAgent).indexOf("Windows"),Hu.indexOf("Macintosh"),(Hu.indexOf("Macintosh")>=0||Hu.indexOf("iPad")>=0||Hu.indexOf("iPhone")>=0)&&!!navigator.maxTouchPoints&&navigator.maxTouchPoints,Hu.indexOf("Linux")>=0,null==Hu||Hu.indexOf("Mobi"),Uu=globalThis._VSCODE_NLS_LANGUAGE||Ku,navigator.language.toLowerCase());var Yu,Xu=Hu,Gu=Uu;(e=>{e.value=function(){return Gu},e.isDefaultVariant=function(){return 2===Gu.length?"en"===Gu:Gu.length>=3&&("e"===Gu[0]&&"n"===Gu[1]&&"-"===Gu[2])},e.isDefault=function(){return"en"===Gu}})(Yu||(Yu={}));var Zu="function"==typeof Vu.postMessage&&!Vu.importScripts;(()=>{if(Zu){let e=[];Vu.addEventListener("message",t=>{if(t.data&&t.data.vscodeScheduleAsyncWork)for(let i=0,s=e.length;i<s;i++){let s=e[i];if(s.id===t.data.vscodeScheduleAsyncWork)return e.splice(i,1),void s.callback()}});let t=0;return i=>{let s=++t;e.push({id:s,callback:i}),Vu.postMessage({vscodeScheduleAsyncWork:s},"*")}}})();var Ju,Qu,ef=!!(Xu&&Xu.indexOf("Chrome")>=0);function tf(e,t=0,i){let s=setTimeout(()=>{e()},t);return xu(()=>{clearTimeout(s)})}Xu&&Xu.indexOf("Firefox"),!ef&&Xu&&Xu.indexOf("Safari"),Xu&&Xu.indexOf("Edg/"),Xu&&Xu.indexOf("Android"),(Qu=Ju||(Ju={})).settled=async function(e){let t,i=await Promise.all(e.map(e=>e.then(e=>e,e=>{t||(t=e)})));if(typeof t<"u")throw t;return i},Qu.withAsyncBody=function(e){return new Promise(async(t,i)=>{try{await e(t,i)}catch(s){i(s)}})};var sf=class e{static fromArray(t){return new e(e=>{e.emitMany(t)})}static fromPromise(t){return new e(async e=>{e.emitMany(await t)})}static fromPromises(t){return new e(async e=>{await Promise.all(t.map(async t=>e.emitOne(await t)))})}static merge(t){return new e(async e=>{await Promise.all(t.map(async t=>{for await(let i of t)e.emitOne(i)}))})}constructor(e,t){this._state=0,this._results=[],this._error=null,this._onReturn=t,this._onStateChanged=new Au,queueMicrotask(async()=>{let t={emitOne:e=>this.emitOne(e),emitMany:e=>this.emitMany(e),reject:e=>this.reject(e)};try{await Promise.resolve(e(t)),this.resolve()}catch(Pa){this.reject(Pa)}finally{t.emitOne=void 0,t.emitMany=void 0,t.reject=void 0}})}[Symbol.asyncIterator](){let e=0;return{next:async()=>{for(;;){if(2===this._state)throw this._error;if(e<this._results.length)return{done:!1,value:this._results[e++]};if(1===this._state)return{done:!0,value:void 0};await Cu.toPromise(this._onStateChanged.event)}},return:async()=>{var e;return null==(e=this._onReturn)||e.call(this),{done:!0,value:void 0}}}}static map(t,i){return new e(async e=>{for await(let s of t)e.emitOne(i(s))})}map(t){return e.map(this,t)}static filter(t,i){return new e(async e=>{for await(let s of t)i(s)&&e.emitOne(s)})}filter(t){return e.filter(this,t)}static coalesce(t){return e.filter(t,e=>!!e)}coalesce(){return e.coalesce(this)}static async toPromise(e){let t=[];for await(let i of e)t.push(i);return t}toPromise(){return e.toPromise(this)}emitOne(e){0===this._state&&(this._results.push(e),this._onStateChanged.fire())}emitMany(e){0===this._state&&(this._results=this._results.concat(e),this._onStateChanged.fire())}resolve(){0===this._state&&(this._state=1,this._onStateChanged.fire())}reject(e){0===this._state&&(this._state=2,this._error=e,this._onStateChanged.fire())}};sf.EMPTY=sf.fromArray([]);var rf=class extends Su{constructor(e){super(),this._terminal=e,this._linesCacheTimeout=this._register(new ku),this._linesCacheDisposables=this._register(new ku),this._register(xu(()=>this._destroyLinesCache()))}initLinesCache(){this._linesCache||(this._linesCache=new Array(this._terminal.buffer.active.length),this._linesCacheDisposables.value=yu(this._terminal.onLineFeed(()=>this._destroyLinesCache()),this._terminal.onCursorMove(()=>this._destroyLinesCache()),this._terminal.onResize(()=>this._destroyLinesCache()))),this._linesCacheTimeout.value=tf(()=>this._destroyLinesCache(),15e3)}_destroyLinesCache(){this._linesCache=void 0,this._linesCacheDisposables.clear(),this._linesCacheTimeout.clear()}getLineFromCache(e){var t;return null==(t=this._linesCache)?void 0:t[e]}setLineInCache(e,t){this._linesCache&&(this._linesCache[e]=t)}translateBufferLineToStringWithWrap(e,t){var i;let s=[],r=[0],n=this._terminal.buffer.active.getLine(e);for(;n;){let o=this._terminal.buffer.active.getLine(e+1),a=!!o&&o.isWrapped,l=n.translateToString(!a&&t);if(a&&o){let e=n.getCell(n.length-1);e&&0===e.getCode()&&1===e.getWidth()&&2===(null==(i=o.getCell(0))?void 0:i.getWidth())&&(l=l.slice(0,-1))}if(s.push(l),!a)break;r.push(r[r.length-1]+l.length),e++,n=o}return[s.join(""),r]}},nf=class{get cachedSearchTerm(){return this._cachedSearchTerm}set cachedSearchTerm(e){this._cachedSearchTerm=e}get lastSearchOptions(){return this._lastSearchOptions}set lastSearchOptions(e){this._lastSearchOptions=e}isValidSearchTerm(e){return!!(e&&e.length>0)}didOptionsChange(e){return!this._lastSearchOptions||!!e&&(this._lastSearchOptions.caseSensitive!==e.caseSensitive||this._lastSearchOptions.regex!==e.regex||this._lastSearchOptions.wholeWord!==e.wholeWord)}shouldUpdateHighlighting(e,t){return!!(null==t?void 0:t.decorations)&&(void 0===this._cachedSearchTerm||e!==this._cachedSearchTerm||this.didOptionsChange(t))}clearCachedTerm(){this._cachedSearchTerm=void 0}reset(){this._cachedSearchTerm=void 0,this._lastSearchOptions=void 0}},of=class{constructor(e,t){this._terminal=e,this._lineCache=t}find(e,t,i,s){if(!e||0===e.length)return void this._terminal.clearSelection();if(i>this._terminal.cols)throw new Error(`Invalid col: ${i} to search in terminal of ${this._terminal.cols} cols`);this._lineCache.initLinesCache();let r={startRow:t,startCol:i},n=this._findInLine(e,r,s);if(!n)for(let o=t+1;o<this._terminal.buffer.active.baseY+this._terminal.rows&&(r.startRow=o,r.startCol=0,n=this._findInLine(e,r,s),!n);o++);return n}findNextWithSelection(e,t,i){if(!e||0===e.length)return void this._terminal.clearSelection();let s=this._terminal.getSelectionPosition();this._terminal.clearSelection();let r=0,n=0;s&&(i===e?(r=s.end.x,n=s.end.y):(r=s.start.x,n=s.start.y)),this._lineCache.initLinesCache();let o={startRow:n,startCol:r},a=this._findInLine(e,o,t);if(!a)for(let l=n+1;l<this._terminal.buffer.active.baseY+this._terminal.rows&&(o.startRow=l,o.startCol=0,a=this._findInLine(e,o,t),!a);l++);if(!a&&0!==n)for(let l=0;l<n&&(o.startRow=l,o.startCol=0,a=this._findInLine(e,o,t),!a);l++);return!a&&s&&(o.startRow=s.start.y,o.startCol=0,a=this._findInLine(e,o,t)),a}findPreviousWithSelection(e,t,i){if(!e||0===e.length)return void this._terminal.clearSelection();let s=this._terminal.getSelectionPosition();this._terminal.clearSelection();let r=this._terminal.buffer.active.baseY+this._terminal.rows-1,n=this._terminal.cols,o=!0;this._lineCache.initLinesCache();let a,l={startRow:r,startCol:n};if(s&&(l.startRow=r=s.start.y,l.startCol=n=s.start.x,i!==e&&(a=this._findInLine(e,l,t,!1),a||(l.startRow=r=s.end.y,l.startCol=n=s.end.x))),a||(a=this._findInLine(e,l,t,o)),!a){l.startCol=Math.max(l.startCol,this._terminal.cols);for(let i=r-1;i>=0&&(l.startRow=i,a=this._findInLine(e,l,t,o),!a);i--);}if(!a&&r!==this._terminal.buffer.active.baseY+this._terminal.rows-1)for(let c=this._terminal.buffer.active.baseY+this._terminal.rows-1;c>=r&&(l.startRow=c,a=this._findInLine(e,l,t,o),!a);c--);return a}_isWholeWord(e,t,i){return(0===e||" ~!@#$%^&*()+`-=[]{}|\\;:\"',./<>?".includes(t[e-1]))&&(e+i.length===t.length||" ~!@#$%^&*()+`-=[]{}|\\;:\"',./<>?".includes(t[e+i.length]))}_findInLine(e,t,i={},s=!1){var r;let n=t.startRow,o=t.startCol;if(null==(r=this._terminal.buffer.active.getLine(n))?void 0:r.isWrapped)return s?void(t.startCol+=this._terminal.cols):(t.startRow--,t.startCol+=this._terminal.cols,this._findInLine(e,t,i));let a=this._lineCache.getLineFromCache(n);a||(a=this._lineCache.translateBufferLineToStringWithWrap(n,!0),this._lineCache.setLineInCache(n,a));let[l,c]=a,h=this._bufferColsToStringOffset(n,o),d=e,u=l;i.regex||(d=i.caseSensitive?e:e.toLowerCase(),u=i.caseSensitive?l:l.toLowerCase());let f=-1;if(i.regex){let t,r=RegExp(d,i.caseSensitive?"g":"gi");if(s)for(;t=r.exec(u.slice(0,h));)f=r.lastIndex-t[0].length,e=t[0],r.lastIndex-=e.length-1;else t=r.exec(u.slice(h)),t&&t[0].length>0&&(f=h+(r.lastIndex-t[0].length),e=t[0])}else s?h-d.length>=0&&(f=u.lastIndexOf(d,h-d.length)):f=u.indexOf(d,h);if(f>=0){if(i.wholeWord&&!this._isWholeWord(f,u,e))return;let t=0;for(;t<c.length-1&&f>=c[t+1];)t++;let s=t;for(;s<c.length-1&&f+e.length>=c[s+1];)s++;let r=f-c[t],o=f+e.length-c[s],a=this._stringLengthToBufferSize(n+t,r);return{term:e,col:a,row:n+t,size:this._stringLengthToBufferSize(n+s,o)-a+this._terminal.cols*(s-t)}}}_stringLengthToBufferSize(e,t){let i=this._terminal.buffer.active.getLine(e);if(!i)return 0;for(let s=0;s<t;s++){let e=i.getCell(s);if(!e)break;let r=e.getChars();r.length>1&&(t-=r.length-1);let n=i.getCell(s+1);n&&0===n.getWidth()&&t++}return t}_bufferColsToStringOffset(e,t){let i=e,s=0,r=this._terminal.buffer.active.getLine(i);for(;t>0&&r;){for(let e=0;e<t&&e<this._terminal.cols;e++){let t=r.getCell(e);if(!t)break;t.getWidth()&&(s+=0===t.getCode()?1:t.getChars().length)}if(i++,r=this._terminal.buffer.active.getLine(i),r&&!r.isWrapped)break;t-=this._terminal.cols}return s}},af=class extends Su{constructor(e){super(),this._terminal=e,this._highlightDecorations=[],this._highlightedLines=new Set,this._register(xu(()=>this.clearHighlightDecorations()))}createHighlightDecorations(e,t){this.clearHighlightDecorations();for(let i of e){let e=this._createResultDecorations(i,t,!1);if(e)for(let t of e)this._storeDecoration(t,i)}}createActiveDecoration(e,t){let i=this._createResultDecorations(e,t,!0);if(i)return{decorations:i,match:e,dispose(){vu(i)}}}clearHighlightDecorations(){vu(this._highlightDecorations),this._highlightDecorations=[],this._highlightedLines.clear()}_storeDecoration(e,t){this._highlightedLines.add(e.marker.line),this._highlightDecorations.push({decoration:e,match:t,dispose(){e.dispose()}})}_applyStyles(e,t,i){e.classList.contains("xterm-find-result-decoration")||(e.classList.add("xterm-find-result-decoration"),t&&(e.style.outline=`1px solid ${t}`)),i&&e.classList.add("xterm-find-active-result-decoration")}_createResultDecorations(e,t,i){let s=[],r=e.col,n=e.size,o=-this._terminal.buffer.active.baseY-this._terminal.buffer.active.cursorY+e.row;for(;n>0;){let e=Math.min(this._terminal.cols-r,n);s.push([o,r,e]),r=0,n-=e,o++}let a=[];for(let l of s){let e=this._terminal.registerMarker(l[0]),s=this._terminal.registerDecoration({marker:e,x:l[1],width:l[2],backgroundColor:i?t.activeMatchBackground:t.matchBackground,overviewRulerOptions:this._highlightedLines.has(e.line)?void 0:{color:i?t.activeMatchColorOverviewRuler:t.matchOverviewRuler,position:"center"}});if(s){let r=[];r.push(e),r.push(s.onRender(e=>this._applyStyles(e,i?t.activeMatchBorder:t.matchBorder,!1))),r.push(s.onDispose(()=>vu(r))),a.push(s)}}return 0===a.length?void 0:a}},lf=class extends Su{constructor(){super(...arguments),this._searchResults=[],this._onDidChangeResults=this._register(new Au)}get onDidChangeResults(){return this._onDidChangeResults.event}get searchResults(){return this._searchResults}get selectedDecoration(){return this._selectedDecoration}set selectedDecoration(e){this._selectedDecoration=e}updateResults(e,t){this._searchResults=e.slice(0,t)}clearResults(){this._searchResults=[]}clearSelectedDecoration(){this._selectedDecoration&&(this._selectedDecoration.dispose(),this._selectedDecoration=void 0)}findResultIndex(e){for(let t=0;t<this._searchResults.length;t++){let i=this._searchResults[t];if(i.row===e.row&&i.col===e.col&&i.size===e.size)return t}return-1}fireResultsChanged(e){if(!e)return;let t=-1;this._selectedDecoration&&(t=this.findResultIndex(this._selectedDecoration.match)),this._onDidChangeResults.fire({resultIndex:t,resultCount:this._searchResults.length})}reset(){this.clearSelectedDecoration(),this.clearResults()}},cf=class extends Su{constructor(e){super(),this._highlightTimeout=this._register(new ku),this._lineCache=this._register(new ku),this._state=new nf,this._resultTracker=this._register(new lf),this._highlightLimit=(null==e?void 0:e.highlightLimit)??1e3}get onDidChangeResults(){return this._resultTracker.onDidChangeResults}activate(e){this._terminal=e,this._lineCache.value=new rf(e),this._engine=new of(e,this._lineCache.value),this._decorationManager=new af(e),this._register(this._terminal.onWriteParsed(()=>this._updateMatches())),this._register(this._terminal.onResize(()=>this._updateMatches())),this._register(xu(()=>this.clearDecorations()))}_updateMatches(){var e;this._highlightTimeout.clear(),this._state.cachedSearchTerm&&(null==(e=this._state.lastSearchOptions)?void 0:e.decorations)&&(this._highlightTimeout.value=tf(()=>{let e=this._state.cachedSearchTerm;this._state.clearCachedTerm(),this.findPrevious(e,{...this._state.lastSearchOptions,incremental:!0},{noScroll:!0})},200))}clearDecorations(e){var t;this._resultTracker.clearSelectedDecoration(),null==(t=this._decorationManager)||t.clearHighlightDecorations(),this._resultTracker.clearResults(),e||this._state.clearCachedTerm()}clearActiveDecoration(){this._resultTracker.clearSelectedDecoration()}findNext(e,t,i){if(!this._terminal||!this._engine)throw new Error("Cannot use addon until it has been loaded");this._state.lastSearchOptions=t,this._state.shouldUpdateHighlighting(e,t)&&this._highlightAllMatches(e,t);let s=this._findNextAndSelect(e,t,i);return this._fireResults(t),this._state.cachedSearchTerm=e,s}_highlightAllMatches(e,t){if(!this._terminal||!this._engine||!this._decorationManager)throw new Error("Cannot use addon until it has been loaded");if(!this._state.isValidSearchTerm(e))return void this.clearDecorations();this.clearDecorations(!0);let i,s=[],r=this._engine.find(e,0,0,t);for(;r&&((null==i?void 0:i.row)!==r.row||(null==i?void 0:i.col)!==r.col)&&!(s.length>=this._highlightLimit);)i=r,s.push(i),r=this._engine.find(e,i.col+i.term.length>=this._terminal.cols?i.row+1:i.row,i.col+i.term.length>=this._terminal.cols?0:i.col+1,t);this._resultTracker.updateResults(s,this._highlightLimit),t.decorations&&this._decorationManager.createHighlightDecorations(s,t.decorations)}_findNextAndSelect(e,t,i){if(!this._terminal||!this._engine)return!1;if(!this._state.isValidSearchTerm(e))return this._terminal.clearSelection(),this.clearDecorations(),!1;let s=this._engine.findNextWithSelection(e,t,this._state.cachedSearchTerm);return this._selectResult(s,null==t?void 0:t.decorations,null==i?void 0:i.noScroll)}findPrevious(e,t,i){if(!this._terminal||!this._engine)throw new Error("Cannot use addon until it has been loaded");this._state.lastSearchOptions=t,this._state.shouldUpdateHighlighting(e,t)&&this._highlightAllMatches(e,t);let s=this._findPreviousAndSelect(e,t,i);return this._fireResults(t),this._state.cachedSearchTerm=e,s}_fireResults(e){this._resultTracker.fireResultsChanged(!!(null==e?void 0:e.decorations))}_findPreviousAndSelect(e,t,i){if(!this._terminal||!this._engine)return!1;if(!this._state.isValidSearchTerm(e))return this._terminal.clearSelection(),this.clearDecorations(),!1;let s=this._engine.findPreviousWithSelection(e,t,this._state.cachedSearchTerm);return this._selectResult(s,null==t?void 0:t.decorations,null==i?void 0:i.noScroll)}_selectResult(e,t,i){if(!this._terminal||!this._decorationManager)return!1;if(this._resultTracker.clearSelectedDecoration(),!e)return this._terminal.clearSelection(),!1;if(this._terminal.select(e.col,e.row,e.size),t){let i=this._decorationManager.createActiveDecoration(e,t);i&&(this._resultTracker.selectedDecoration=i)}if(!i&&(e.row>=this._terminal.buffer.active.viewportY+this._terminal.rows||e.row<this._terminal.buffer.active.viewportY)){let t=e.row-this._terminal.buffer.active.viewportY;t-=Math.floor(this._terminal.rows/2),this._terminal.scrollLines(t)}return!0}};const hf={background:"#09090b",foreground:"#e4e4e7",cursor:"#a1a1aa",cursorAccent:"#09090b",selectionBackground:"#3f3f46",black:"#18181b",brightBlack:"#3f3f46",red:"#ef4444",brightRed:"#f87171",green:"#22c55e",brightGreen:"#4ade80",yellow:"#eab308",brightYellow:"#facc15",blue:"#3b82f6",brightBlue:"#60a5fa",magenta:"#a855f7",brightMagenta:"#c084fc",cyan:"#06b6d4",brightCyan:"#22d3ee",white:"#e4e4e7",brightWhite:"#f4f4f5"},df={background:"#ffffff",foreground:"#1c1c1c",cursor:"#6b7280",cursorAccent:"#ffffff",selectionBackground:"#d1d5db",black:"#1c1c1c",brightBlack:"#6b7280",red:"#dc2626",brightRed:"#ef4444",green:"#16a34a",brightGreen:"#22c55e",yellow:"#ca8a04",brightYellow:"#eab308",blue:"#2563eb",brightBlue:"#3b82f6",magenta:"#9333ea",brightMagenta:"#a855f7",cyan:"#0891b2",brightCyan:"#06b6d4",white:"#e5e7eb",brightWhite:"#f9fafb"},uf=h.forwardRef(({onInput:e,onResize:t,onReady:i,cliTool:s="claude"},r)=>{const n=h.useRef(null),o=h.useRef(null),a=h.useRef(null),l=h.useRef(null),c=h.useRef(e),u=h.useRef(t),f=h.useRef(i),p=h.useRef(!1),m=h.useRef(null);c.current=e,u.current=t,f.current=i;const{resolved:g}=d();return h.useImperativeHandle(r,()=>({write:e=>{var t;null==(t=o.current)||t.write(e)},reset:()=>{const e=o.current;e&&(e.reset(),e.clear())},search:(e,t)=>{var i;return(null==(i=l.current)?void 0:i.findNext(e,t))??!1},searchNext:(e,t)=>{var i;return(null==(i=l.current)?void 0:i.findNext(e,t))??!1},searchPrevious:(e,t)=>{var i;return(null==(i=l.current)?void 0:i.findPrevious(e,t))??!1},clearSearch:()=>{var e;null==(e=l.current)||e.clearDecorations()}})),h.useEffect(()=>{if(!n.current)return;const e=new au({theme:"dark"===g?hf:df,fontFamily:'"JetBrains Mono", "Fira Code", "Cascadia Code", Menlo, Consolas, monospace',fontSize:13,lineHeight:1.5,cursorBlink:!0,convertEol:!1,scrollback:5e3,allowProposedApi:!0}),t=new lu;e.loadAddon(t);const i=new cf;e.loadAddon(i),l.current=i,e.open(n.current),requestAnimationFrame(()=>{var i;t.fit();const{cols:s,rows:r}=e;p.current||(p.current=!0,null==(i=f.current)||i.call(f,s,r)),u.current(s,r)}),o.current=e,a.current=t,m.current=g,e.onData(e=>{c.current(e)});const s=new ResizeObserver(()=>{requestAnimationFrame(()=>{n.current&&null!==n.current.offsetParent&&(t.fit(),u.current(e.cols,e.rows))})});return s.observe(n.current),()=>{s.disconnect(),e.dispose(),o.current=null,a.current=null,l.current=null}},[]),h.useEffect(()=>{const e=o.current;if(e&&m.current!==g)if(m.current=g,e.options.theme="dark"===g?hf:df,"claude"===s){const e="dark"===g?"dark":"light";c.current(`/theme ${e}\r`)}else if("gemini"===s){const e="dark"===g?"dark":"light";c.current(`/settings theme ${e}\r`)}else if("codex"===s){const e="dark"===g?"dark":"light";c.current(`/theme ${e}\r`)}},[g,s]),_.jsx("div",{ref:n,className:"h-full w-full bg-background",style:{overflow:"hidden",padding:"4px"}})});function ff({onSearch:e,onSearchNext:t,onSearchPrev:i,onClear:s,onClose:r}){const[n,o]=h.useState(""),[a,l]=h.useState(!1),[c,d]=h.useState(!1),u=h.useRef(null);h.useEffect(()=>{var e;null==(e=u.current)||e.focus()},[]);const f=h.useMemo(()=>({caseSensitive:a,regex:c}),[a,c]);return _.jsxs("div",{className:"absolute top-2 right-2 z-20 flex items-center gap-1 bg-background border border-border rounded-md shadow-sm px-2 py-1",children:[_.jsx(oi,{className:"h-3.5 w-3.5 text-muted-foreground flex-shrink-0"}),_.jsx(q,{ref:u,value:n,onChange:t=>{return i=t.target.value,o(i),void(i?e(i,f):s());var i},onKeyDown:e=>{if("Enter"===e.key){if(!n)return;e.shiftKey?i(n,f):t(n,f)}"Escape"===e.key&&(s(),r())},placeholder:"搜索...",className:"h-6 w-44 text-xs border-0 p-0 focus-visible:ring-0 bg-transparent"}),_.jsx("button",{title:"区分大小写",onClick:()=>{const t=!a;l(t),n&&e(n,{...f,caseSensitive:t})},className:g("text-[10px] px-1 rounded font-mono transition-colors",a?"bg-accent text-foreground font-medium":"text-muted-foreground hover:text-foreground"),children:"Aa"}),_.jsx("button",{title:"正则表达式",onClick:()=>{const t=!c;d(t),n&&e(n,{...f,regex:t})},className:g("text-[10px] px-1 rounded font-mono transition-colors",c?"bg-accent text-foreground font-medium":"text-muted-foreground hover:text-foreground"),children:".*"}),_.jsx(K,{variant:"ghost",size:"icon",className:"h-5 w-5",onClick:()=>{n&&i(n,f)},disabled:!n,children:_.jsx(ni,{className:"h-3 w-3"})}),_.jsx(K,{variant:"ghost",size:"icon",className:"h-5 w-5",onClick:()=>{n&&t(n,f)},disabled:!n,children:_.jsx(ii,{className:"h-3 w-3"})}),_.jsx(K,{variant:"ghost",size:"icon",className:"h-5 w-5",onClick:()=>{s(),r()},children:_.jsx(S,{className:"h-3 w-3"})})]})}uf.displayName="WebTerminal";const pf=h.forwardRef(({projectId:e,project:t,onStatusChange:i,onChatMessage:s,onWsConnected:r,onWsDisconnected:n,onApprovalRequest:o,onApprovalResolved:a,onSemanticUpdate:l},c)=>{const d=h.useRef([]),[u,f]=h.useState(!1),[p,m]=h.useState(null),g=h.useRef(null),v=h.useRef(null),y=h.useRef(null),x=h.useRef(null),b=h.useCallback(e=>{var t;null==(t=g.current)||t.write(e)},[]),w=h.useCallback(()=>{var e;const t=v.current;t&&y.current&&y.current(t.cols,t.rows),null==(e=x.current)||e.call(x)},[]),S=h.useCallback(()=>{var e;null==(e=g.current)||e.reset()},[]),{subscribeTerminal:C,sendTerminalInput:k,sendTerminalResize:E,subscribeChatMessages:N}=ct(e,{onTerminalData:b,onTerminalReset:S,onStatus:i,onConnected:()=>{d.current=[],null==r||r(),w()},onDisconnected:()=>{null==n||n()},onChatMessage:e=>{d.current.push(e),null==s||s(e)},onApprovalRequest:e=>null==o?void 0:o(e),onApprovalResolved:e=>null==a?void 0:a(e),onContextUpdate:e=>m(e),onSemanticUpdate:e=>null==l?void 0:l(e)});h.useEffect(()=>{y.current=C},[C]),h.useEffect(()=>{x.current=N},[N]),h.useEffect(()=>{const e=e=>{(e.ctrlKey||e.metaKey)&&"f"===e.key&&(e.preventDefault(),f(e=>!e))};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[]);const M=h.useCallback((e,t)=>{v.current={cols:e,rows:t},w()},[w]);return h.useImperativeHandle(c,()=>({sendTerminalInput:k}),[k]),_.jsxs("div",{className:"flex-1 overflow-hidden min-w-0 flex flex-col",children:[_.jsxs("div",{className:"relative flex-1 min-h-0",children:[_.jsx(uf,{ref:g,onInput:k,onResize:(e,t)=>{v.current={cols:e,rows:t},E(e,t)},onReady:M,cliTool:null==t?void 0:t.cliTool}),u&&_.jsx(ff,{onSearch:(e,t)=>{var i;return(null==(i=g.current)?void 0:i.search(e,t))??!1},onSearchNext:(e,t)=>{var i;return(null==(i=g.current)?void 0:i.searchNext(e,t))??!1},onSearchPrev:(e,t)=>{var i;return(null==(i=g.current)?void 0:i.searchPrevious(e,t))??!1},onClear:()=>{var e;return null==(e=g.current)?void 0:e.clearSearch()},onClose:()=>f(!1)})]}),_.jsxs("div",{className:"flex-shrink-0 flex items-center px-3 h-7 border-t border-border bg-muted/30 gap-3",children:[_.jsx(ht,{}),p&&_.jsxs("div",{className:"flex items-center gap-1.5 text-xs",children:[_.jsx("span",{className:"text-muted-foreground",children:"上下文"}),_.jsx("div",{className:"w-20 h-1.5 bg-muted rounded-full overflow-hidden",children:_.jsx("div",{className:"h-full rounded-full transition-all "+(p.usedPercentage<50?"bg-green-500":p.usedPercentage<80?"bg-yellow-500":"bg-red-500"),style:{width:`${Math.min(p.usedPercentage,100)}%`}})}),_.jsxs("span",{className:"font-medium "+(p.usedPercentage<50?"text-green-500":p.usedPercentage<80?"text-yellow-500":"text-red-500"),children:[Math.round(p.usedPercentage),"%"]}),_.jsx("span",{className:"text-muted-foreground/50",children:p.contextWindowSize>=1e6?`${(p.contextWindowSize/1e6).toFixed(0)}M`:`${Math.round(p.contextWindowSize/1e3)}K`})]})]})]})});pf.displayName="TerminalView";const mf=new Set(["png","jpg","jpeg","gif","webp","svg","bmp","ico","avif","tiff","tif"]),_f=new Set(["js","jsx","ts","tsx","py","rb","go","rs","java","kt","swift","c","cpp","h","cs","php","sh","bash","zsh","yaml","yml","json","toml","html","htm","xml","css","scss","less","sql","graphql","gql","r","lua","dart","zig"]);function gf({projectId:e}){const t=D(t=>t.get(e).filePreviews),i=D(t=>t.get(e).activePreviewPath),s=D(e=>e.setActivePreview),r=D(e=>e.closeFilePreview),n=D(e=>e.minimizeFilePreview);return 0===t.length?null:_.jsx("div",{className:"absolute top-2 left-1/2 -translate-x-1/2 z-[60] pointer-events-auto",onContextMenu:e=>e.preventDefault(),children:_.jsx("div",{className:"flex items-center gap-1 rounded-full border border-border bg-background/85 backdrop-blur-sm shadow-sm px-1.5 py-1",children:t.map(t=>{const o=function(e){if(e.endsWith("/.notebook/graph.yaml"))return wi;const t=function(e){const t=e.split("/").pop()??"",i=t.toLowerCase();if("dockerfile"===i)return"dockerfile";if("makefile"===i)return"makefile";const s=t.lastIndexOf(".");return s>=0?t.slice(s+1).toLowerCase():""}(e);return mf.has(t)?Pt:"pdf"===t?wt:"xlsx"===t||"xls"===t?mi:"pptx"===t?Ei:"docx"===t||"md"===t?wt:_f.has(t)?ui:dt}(t.path),a=t.path===i&&!t.minimized;return _.jsxs("div",{className:g("group flex items-center gap-1 rounded-full pl-1.5 pr-1 py-0.5 max-w-[180px] cursor-pointer transition-colors",a?"bg-accent text-accent-foreground":"hover:bg-muted text-muted-foreground"),onClick:()=>{a?n(e,t.path):s(e,t.path)},title:t.path,children:[_.jsx(o,{className:"size-3.5 flex-shrink-0"}),_.jsx("span",{className:"text-xs truncate min-w-0",children:(l=t.path,l.split("/").pop()??l)}),_.jsx("button",{className:"flex-shrink-0 size-4 rounded-full flex items-center justify-center opacity-60 hover:opacity-100 hover:bg-background/60 transition-opacity",onClick:i=>{i.stopPropagation(),r(e,t.path)},title:"关闭",children:_.jsx(S,{className:"size-3"})})]},t.path);var l})})})}function vf(e){if("string"==typeof e||"number"==typeof e)return""+e;let t="";if(Array.isArray(e))for(let i,s=0;s<e.length;s++)""!==(i=vf(e[s]))&&(t+=(t&&" ")+i);else for(let i in e)e[i]&&(t+=(t&&" ")+i);return t}var yf={exports:{}},xf={},bf=h,wf=ut;var Sf="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},Cf=wf.useSyncExternalStore,kf=bf.useRef,Ef=bf.useEffect,Nf=bf.useMemo,Mf=bf.useDebugValue;xf.useSyncExternalStoreWithSelector=function(e,t,i,s,r){var n=kf(null);if(null===n.current){var o={hasValue:!1,value:null};n.current=o}else o=n.current;n=Nf(function(){function e(e){if(!l){if(l=!0,n=e,e=s(e),void 0!==r&&o.hasValue){var t=o.value;if(r(t,e))return a=t}return a=e}if(t=a,Sf(n,e))return t;var i=s(e);return void 0!==r&&r(t,i)?(n=e,t):(n=e,a=i)}var n,a,l=!1,c=void 0===i?null:i;return[function(){return e(t())},null===c?void 0:function(){return e(c())}]},[t,i,s,r]);var a=Cf(e,n[0],n[1]);return Ef(function(){o.hasValue=!0,o.value=a},[a]),Mf(a),a},yf.exports=xf;const jf=ft(yf.exports),Df={},Rf=e=>{let t;const i=new Set,s=(e,s)=>{const r="function"==typeof e?e(t):e;if(!Object.is(r,t)){const e=t;t=(null!=s?s:"object"!=typeof r||null===r)?r:Object.assign({},t,r),i.forEach(i=>i(t,e))}},r=()=>t,n={setState:s,getState:r,getInitialState:()=>o,subscribe:e=>(i.add(e),()=>i.delete(e)),destroy:()=>{"production"!==(Df?"production":void 0)&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),i.clear()}},o=t=e(s,r,n);return n},{useDebugValue:Pf}=N,{useSyncExternalStoreWithSelector:Lf}=jf,Tf=e=>e;function If(e,t=Tf,i){const s=Lf(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,i);return Pf(s),s}const Bf=(e,t)=>{const i=(e=>e?Rf(e):Rf)(e),s=(e,s=t)=>If(i,e,s);return Object.assign(s,i),s};function Of(e,t){if(Object.is(e,t))return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(const[i,s]of e)if(!Object.is(s,t.get(i)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(const i of e)if(!t.has(i))return!1;return!0}const i=Object.keys(e);if(i.length!==Object.keys(t).length)return!1;for(const s of i)if(!Object.prototype.hasOwnProperty.call(t,s)||!Object.is(e[s],t[s]))return!1;return!0}var Af={value:()=>{}};function zf(){for(var e,t=0,i=arguments.length,s={};t<i;++t){if(!(e=arguments[t]+"")||e in s||/[\s.]/.test(e))throw new Error("illegal type: "+e);s[e]=[]}return new $f(s)}function $f(e){this._=e}function Hf(e,t){for(var i,s=0,r=e.length;s<r;++s)if((i=e[s]).name===t)return i.value}function Wf(e,t,i){for(var s=0,r=e.length;s<r;++s)if(e[s].name===t){e[s]=Af,e=e.slice(0,s).concat(e.slice(s+1));break}return null!=i&&e.push({name:t,value:i}),e}$f.prototype=zf.prototype={constructor:$f,on:function(e,t){var i,s,r=this._,n=(s=r,(e+"").trim().split(/^|\s+/).map(function(e){var t="",i=e.indexOf(".");if(i>=0&&(t=e.slice(i+1),e=e.slice(0,i)),e&&!s.hasOwnProperty(e))throw new Error("unknown type: "+e);return{type:e,name:t}})),o=-1,a=n.length;if(!(arguments.length<2)){if(null!=t&&"function"!=typeof t)throw new Error("invalid callback: "+t);for(;++o<a;)if(i=(e=n[o]).type)r[i]=Wf(r[i],e.name,t);else if(null==t)for(i in r)r[i]=Wf(r[i],e.name,null);return this}for(;++o<a;)if((i=(e=n[o]).type)&&(i=Hf(r[i],e.name)))return i},copy:function(){var e={},t=this._;for(var i in t)e[i]=t[i].slice();return new $f(e)},call:function(e,t){if((i=arguments.length-2)>0)for(var i,s,r=new Array(i),n=0;n<i;++n)r[n]=arguments[n+2];if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(n=0,i=(s=this._[e]).length;n<i;++n)s[n].value.apply(t,r)},apply:function(e,t,i){if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(var s=this._[e],r=0,n=s.length;r<n;++r)s[r].value.apply(t,i)}};var Ff="http://www.w3.org/1999/xhtml";const Kf={svg:"http://www.w3.org/2000/svg",xhtml:Ff,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function Uf(e){var t=e+="",i=t.indexOf(":");return i>=0&&"xmlns"!==(t=e.slice(0,i))&&(e=e.slice(i+1)),Kf.hasOwnProperty(t)?{space:Kf[t],local:e}:e}function Vf(e){return function(){var t=this.ownerDocument,i=this.namespaceURI;return i===Ff&&t.documentElement.namespaceURI===Ff?t.createElement(e):t.createElementNS(i,e)}}function qf(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function Yf(e){var t=Uf(e);return(t.local?qf:Vf)(t)}function Xf(){}function Gf(e){return null==e?Xf:function(){return this.querySelector(e)}}function Zf(){return[]}function Jf(e){return null==e?Zf:function(){return this.querySelectorAll(e)}}function Qf(e){return function(){return null==(t=e.apply(this,arguments))?[]:Array.isArray(t)?t:Array.from(t);var t}}function ep(e){return function(){return this.matches(e)}}function tp(e){return function(t){return t.matches(e)}}var ip=Array.prototype.find;function sp(){return this.firstElementChild}var rp=Array.prototype.filter;function np(){return Array.from(this.children)}function op(e){return new Array(e.length)}function ap(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}function lp(e,t,i,s,r,n){for(var o,a=0,l=t.length,c=n.length;a<c;++a)(o=t[a])?(o.__data__=n[a],s[a]=o):i[a]=new ap(e,n[a]);for(;a<l;++a)(o=t[a])&&(r[a]=o)}function cp(e,t,i,s,r,n,o){var a,l,c,h=new Map,d=t.length,u=n.length,f=new Array(d);for(a=0;a<d;++a)(l=t[a])&&(f[a]=c=o.call(l,l.__data__,a,t)+"",h.has(c)?r[a]=l:h.set(c,l));for(a=0;a<u;++a)c=o.call(e,n[a],a,n)+"",(l=h.get(c))?(s[a]=l,l.__data__=n[a],h.delete(c)):i[a]=new ap(e,n[a]);for(a=0;a<d;++a)(l=t[a])&&h.get(f[a])===l&&(r[a]=l)}function hp(e){return e.__data__}function dp(e){return"object"==typeof e&&"length"in e?e:Array.from(e)}function up(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function fp(e){return function(){this.removeAttribute(e)}}function pp(e){return function(){this.removeAttributeNS(e.space,e.local)}}function mp(e,t){return function(){this.setAttribute(e,t)}}function _p(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function gp(e,t){return function(){var i=t.apply(this,arguments);null==i?this.removeAttribute(e):this.setAttribute(e,i)}}function vp(e,t){return function(){var i=t.apply(this,arguments);null==i?this.removeAttributeNS(e.space,e.local):this.setAttributeNS(e.space,e.local,i)}}function yp(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function xp(e){return function(){this.style.removeProperty(e)}}function bp(e,t,i){return function(){this.style.setProperty(e,t,i)}}function wp(e,t,i){return function(){var s=t.apply(this,arguments);null==s?this.style.removeProperty(e):this.style.setProperty(e,s,i)}}function Sp(e,t){return e.style.getPropertyValue(t)||yp(e).getComputedStyle(e,null).getPropertyValue(t)}function Cp(e){return function(){delete this[e]}}function kp(e,t){return function(){this[e]=t}}function Ep(e,t){return function(){var i=t.apply(this,arguments);null==i?delete this[e]:this[e]=i}}function Np(e){return e.trim().split(/^|\s+/)}function Mp(e){return e.classList||new jp(e)}function jp(e){this._node=e,this._names=Np(e.getAttribute("class")||"")}function Dp(e,t){for(var i=Mp(e),s=-1,r=t.length;++s<r;)i.add(t[s])}function Rp(e,t){for(var i=Mp(e),s=-1,r=t.length;++s<r;)i.remove(t[s])}function Pp(e){return function(){Dp(this,e)}}function Lp(e){return function(){Rp(this,e)}}function Tp(e,t){return function(){(t.apply(this,arguments)?Dp:Rp)(this,e)}}function Ip(){this.textContent=""}function Bp(e){return function(){this.textContent=e}}function Op(e){return function(){var t=e.apply(this,arguments);this.textContent=null==t?"":t}}function Ap(){this.innerHTML=""}function zp(e){return function(){this.innerHTML=e}}function $p(e){return function(){var t=e.apply(this,arguments);this.innerHTML=null==t?"":t}}function Hp(){this.nextSibling&&this.parentNode.appendChild(this)}function Wp(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function Fp(){return null}function Kp(){var e=this.parentNode;e&&e.removeChild(this)}function Up(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function Vp(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function qp(e){return function(){var t=this.__on;if(t){for(var i,s=0,r=-1,n=t.length;s<n;++s)i=t[s],e.type&&i.type!==e.type||i.name!==e.name?t[++r]=i:this.removeEventListener(i.type,i.listener,i.options);++r?t.length=r:delete this.__on}}}function Yp(e,t,i){return function(){var s,r=this.__on,n=function(e){return function(t){e.call(this,t,this.__data__)}}(t);if(r)for(var o=0,a=r.length;o<a;++o)if((s=r[o]).type===e.type&&s.name===e.name)return this.removeEventListener(s.type,s.listener,s.options),this.addEventListener(s.type,s.listener=n,s.options=i),void(s.value=t);this.addEventListener(e.type,n,i),s={type:e.type,name:e.name,value:t,listener:n,options:i},r?r.push(s):this.__on=[s]}}function Xp(e,t,i){var s=yp(e),r=s.CustomEvent;"function"==typeof r?r=new r(t,i):(r=s.document.createEvent("Event"),i?(r.initEvent(t,i.bubbles,i.cancelable),r.detail=i.detail):r.initEvent(t,!1,!1)),e.dispatchEvent(r)}function Gp(e,t){return function(){return Xp(this,e,t)}}function Zp(e,t){return function(){return Xp(this,e,t.apply(this,arguments))}}ap.prototype={constructor:ap,appendChild:function(e){return this._parent.insertBefore(e,this._next)},insertBefore:function(e,t){return this._parent.insertBefore(e,t)},querySelector:function(e){return this._parent.querySelector(e)},querySelectorAll:function(e){return this._parent.querySelectorAll(e)}},jp.prototype={add:function(e){this._names.indexOf(e)<0&&(this._names.push(e),this._node.setAttribute("class",this._names.join(" ")))},remove:function(e){var t=this._names.indexOf(e);t>=0&&(this._names.splice(t,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(e){return this._names.indexOf(e)>=0}};var Jp=[null];function Qp(e,t){this._groups=e,this._parents=t}function em(){return new Qp([[document.documentElement]],Jp)}function tm(e){return"string"==typeof e?new Qp([[document.querySelector(e)]],[document.documentElement]):new Qp([[e]],Jp)}function im(e,t){if(e=function(e){let t;for(;t=e.sourceEvent;)e=t;return e}(e),void 0===t&&(t=e.currentTarget),t){var i=t.ownerSVGElement||t;if(i.createSVGPoint){var s=i.createSVGPoint();return s.x=e.clientX,s.y=e.clientY,[(s=s.matrixTransform(t.getScreenCTM().inverse())).x,s.y]}if(t.getBoundingClientRect){var r=t.getBoundingClientRect();return[e.clientX-r.left-t.clientLeft,e.clientY-r.top-t.clientTop]}}return[e.pageX,e.pageY]}Qp.prototype=em.prototype={constructor:Qp,select:function(e){"function"!=typeof e&&(e=Gf(e));for(var t=this._groups,i=t.length,s=new Array(i),r=0;r<i;++r)for(var n,o,a=t[r],l=a.length,c=s[r]=new Array(l),h=0;h<l;++h)(n=a[h])&&(o=e.call(n,n.__data__,h,a))&&("__data__"in n&&(o.__data__=n.__data__),c[h]=o);return new Qp(s,this._parents)},selectAll:function(e){e="function"==typeof e?Qf(e):Jf(e);for(var t=this._groups,i=t.length,s=[],r=[],n=0;n<i;++n)for(var o,a=t[n],l=a.length,c=0;c<l;++c)(o=a[c])&&(s.push(e.call(o,o.__data__,c,a)),r.push(o));return new Qp(s,r)},selectChild:function(e){return this.select(null==e?sp:function(e){return function(){return ip.call(this.children,e)}}("function"==typeof e?e:tp(e)))},selectChildren:function(e){return this.selectAll(null==e?np:function(e){return function(){return rp.call(this.children,e)}}("function"==typeof e?e:tp(e)))},filter:function(e){"function"!=typeof e&&(e=ep(e));for(var t=this._groups,i=t.length,s=new Array(i),r=0;r<i;++r)for(var n,o=t[r],a=o.length,l=s[r]=[],c=0;c<a;++c)(n=o[c])&&e.call(n,n.__data__,c,o)&&l.push(n);return new Qp(s,this._parents)},data:function(e,t){if(!arguments.length)return Array.from(this,hp);var i,s=t?cp:lp,r=this._parents,n=this._groups;"function"!=typeof e&&(i=e,e=function(){return i});for(var o=n.length,a=new Array(o),l=new Array(o),c=new Array(o),h=0;h<o;++h){var d=r[h],u=n[h],f=u.length,p=dp(e.call(d,d&&d.__data__,h,r)),m=p.length,_=l[h]=new Array(m),g=a[h]=new Array(m);s(d,u,_,g,c[h]=new Array(f),p,t);for(var v,y,x=0,b=0;x<m;++x)if(v=_[x]){for(x>=b&&(b=x+1);!(y=g[b])&&++b<m;);v._next=y||null}}return(a=new Qp(a,r))._enter=l,a._exit=c,a},enter:function(){return new Qp(this._enter||this._groups.map(op),this._parents)},exit:function(){return new Qp(this._exit||this._groups.map(op),this._parents)},join:function(e,t,i){var s=this.enter(),r=this,n=this.exit();return"function"==typeof e?(s=e(s))&&(s=s.selection()):s=s.append(e+""),null!=t&&(r=t(r))&&(r=r.selection()),null==i?n.remove():i(n),s&&r?s.merge(r).order():r},merge:function(e){for(var t=e.selection?e.selection():e,i=this._groups,s=t._groups,r=i.length,n=s.length,o=Math.min(r,n),a=new Array(r),l=0;l<o;++l)for(var c,h=i[l],d=s[l],u=h.length,f=a[l]=new Array(u),p=0;p<u;++p)(c=h[p]||d[p])&&(f[p]=c);for(;l<r;++l)a[l]=i[l];return new Qp(a,this._parents)},selection:function(){return this},order:function(){for(var e=this._groups,t=-1,i=e.length;++t<i;)for(var s,r=e[t],n=r.length-1,o=r[n];--n>=0;)(s=r[n])&&(o&&4^s.compareDocumentPosition(o)&&o.parentNode.insertBefore(s,o),o=s);return this},sort:function(e){function t(t,i){return t&&i?e(t.__data__,i.__data__):!t-!i}e||(e=up);for(var i=this._groups,s=i.length,r=new Array(s),n=0;n<s;++n){for(var o,a=i[n],l=a.length,c=r[n]=new Array(l),h=0;h<l;++h)(o=a[h])&&(c[h]=o);c.sort(t)}return new Qp(r,this._parents).order()},call:function(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this},nodes:function(){return Array.from(this)},node:function(){for(var e=this._groups,t=0,i=e.length;t<i;++t)for(var s=e[t],r=0,n=s.length;r<n;++r){var o=s[r];if(o)return o}return null},size:function(){let e=0;for(const t of this)++e;return e},empty:function(){return!this.node()},each:function(e){for(var t=this._groups,i=0,s=t.length;i<s;++i)for(var r,n=t[i],o=0,a=n.length;o<a;++o)(r=n[o])&&e.call(r,r.__data__,o,n);return this},attr:function(e,t){var i=Uf(e);if(arguments.length<2){var s=this.node();return i.local?s.getAttributeNS(i.space,i.local):s.getAttribute(i)}return this.each((null==t?i.local?pp:fp:"function"==typeof t?i.local?vp:gp:i.local?_p:mp)(i,t))},style:function(e,t,i){return arguments.length>1?this.each((null==t?xp:"function"==typeof t?wp:bp)(e,t,null==i?"":i)):Sp(this.node(),e)},property:function(e,t){return arguments.length>1?this.each((null==t?Cp:"function"==typeof t?Ep:kp)(e,t)):this.node()[e]},classed:function(e,t){var i=Np(e+"");if(arguments.length<2){for(var s=Mp(this.node()),r=-1,n=i.length;++r<n;)if(!s.contains(i[r]))return!1;return!0}return this.each(("function"==typeof t?Tp:t?Pp:Lp)(i,t))},text:function(e){return arguments.length?this.each(null==e?Ip:("function"==typeof e?Op:Bp)(e)):this.node().textContent},html:function(e){return arguments.length?this.each(null==e?Ap:("function"==typeof e?$p:zp)(e)):this.node().innerHTML},raise:function(){return this.each(Hp)},lower:function(){return this.each(Wp)},append:function(e){var t="function"==typeof e?e:Yf(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})},insert:function(e,t){var i="function"==typeof e?e:Yf(e),s=null==t?Fp:"function"==typeof t?t:Gf(t);return this.select(function(){return this.insertBefore(i.apply(this,arguments),s.apply(this,arguments)||null)})},remove:function(){return this.each(Kp)},clone:function(e){return this.select(e?Vp:Up)},datum:function(e){return arguments.length?this.property("__data__",e):this.node().__data__},on:function(e,t,i){var s,r,n=function(e){return e.trim().split(/^|\s+/).map(function(e){var t="",i=e.indexOf(".");return i>=0&&(t=e.slice(i+1),e=e.slice(0,i)),{type:e,name:t}})}(e+""),o=n.length;if(!(arguments.length<2)){for(a=t?Yp:qp,s=0;s<o;++s)this.each(a(n[s],t,i));return this}var a=this.node().__on;if(a)for(var l,c=0,h=a.length;c<h;++c)for(s=0,l=a[c];s<o;++s)if((r=n[s]).type===l.type&&r.name===l.name)return l.value},dispatch:function(e,t){return this.each(("function"==typeof t?Zp:Gp)(e,t))},[Symbol.iterator]:function*(){for(var e=this._groups,t=0,i=e.length;t<i;++t)for(var s,r=e[t],n=0,o=r.length;n<o;++n)(s=r[n])&&(yield s)}};const sm={passive:!1},rm={capture:!0,passive:!1};function nm(e){e.stopImmediatePropagation()}function om(e){e.preventDefault(),e.stopImmediatePropagation()}function am(e){var t=e.document.documentElement,i=tm(e).on("dragstart.drag",om,rm);"onselectstart"in t?i.on("selectstart.drag",om,rm):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function lm(e,t){var i=e.document.documentElement,s=tm(e).on("dragstart.drag",null);t&&(s.on("click.drag",om,rm),setTimeout(function(){s.on("click.drag",null)},0)),"onselectstart"in i?s.on("selectstart.drag",null):(i.style.MozUserSelect=i.__noselect,delete i.__noselect)}const cm=e=>()=>e;function hm(e,{sourceEvent:t,subject:i,target:s,identifier:r,active:n,x:o,y:a,dx:l,dy:c,dispatch:h}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},subject:{value:i,enumerable:!0,configurable:!0},target:{value:s,enumerable:!0,configurable:!0},identifier:{value:r,enumerable:!0,configurable:!0},active:{value:n,enumerable:!0,configurable:!0},x:{value:o,enumerable:!0,configurable:!0},y:{value:a,enumerable:!0,configurable:!0},dx:{value:l,enumerable:!0,configurable:!0},dy:{value:c,enumerable:!0,configurable:!0},_:{value:h}})}function dm(e){return!e.ctrlKey&&!e.button}function um(){return this.parentNode}function fm(e,t){return null==t?{x:e.x,y:e.y}:t}function pm(){return navigator.maxTouchPoints||"ontouchstart"in this}function mm(e,t,i){e.prototype=t.prototype=i,i.constructor=e}function _m(e,t){var i=Object.create(e.prototype);for(var s in t)i[s]=t[s];return i}function gm(){}hm.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};var vm=.7,ym=1/vm,xm="\\s*([+-]?\\d+)\\s*",bm="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",wm="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",Sm=/^#([0-9a-f]{3,8})$/,Cm=new RegExp(`^rgb\\(${xm},${xm},${xm}\\)$`),km=new RegExp(`^rgb\\(${wm},${wm},${wm}\\)$`),Em=new RegExp(`^rgba\\(${xm},${xm},${xm},${bm}\\)$`),Nm=new RegExp(`^rgba\\(${wm},${wm},${wm},${bm}\\)$`),Mm=new RegExp(`^hsl\\(${bm},${wm},${wm}\\)$`),jm=new RegExp(`^hsla\\(${bm},${wm},${wm},${bm}\\)$`),Dm={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};function Rm(){return this.rgb().formatHex()}function Pm(){return this.rgb().formatRgb()}function Lm(e){var t,i;return e=(e+"").trim().toLowerCase(),(t=Sm.exec(e))?(i=t[1].length,t=parseInt(t[1],16),6===i?Tm(t):3===i?new Om(t>>8&15|t>>4&240,t>>4&15|240&t,(15&t)<<4|15&t,1):8===i?Im(t>>24&255,t>>16&255,t>>8&255,(255&t)/255):4===i?Im(t>>12&15|t>>8&240,t>>8&15|t>>4&240,t>>4&15|240&t,((15&t)<<4|15&t)/255):null):(t=Cm.exec(e))?new Om(t[1],t[2],t[3],1):(t=km.exec(e))?new Om(255*t[1]/100,255*t[2]/100,255*t[3]/100,1):(t=Em.exec(e))?Im(t[1],t[2],t[3],t[4]):(t=Nm.exec(e))?Im(255*t[1]/100,255*t[2]/100,255*t[3]/100,t[4]):(t=Mm.exec(e))?Fm(t[1],t[2]/100,t[3]/100,1):(t=jm.exec(e))?Fm(t[1],t[2]/100,t[3]/100,t[4]):Dm.hasOwnProperty(e)?Tm(Dm[e]):"transparent"===e?new Om(NaN,NaN,NaN,0):null}function Tm(e){return new Om(e>>16&255,e>>8&255,255&e,1)}function Im(e,t,i,s){return s<=0&&(e=t=i=NaN),new Om(e,t,i,s)}function Bm(e,t,i,s){return 1===arguments.length?function(e){return e instanceof gm||(e=Lm(e)),e?new Om((e=e.rgb()).r,e.g,e.b,e.opacity):new Om}(e):new Om(e,t,i,null==s?1:s)}function Om(e,t,i,s){this.r=+e,this.g=+t,this.b=+i,this.opacity=+s}function Am(){return`#${Wm(this.r)}${Wm(this.g)}${Wm(this.b)}`}function zm(){const e=$m(this.opacity);return`${1===e?"rgb(":"rgba("}${Hm(this.r)}, ${Hm(this.g)}, ${Hm(this.b)}${1===e?")":`, ${e})`}`}function $m(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function Hm(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function Wm(e){return((e=Hm(e))<16?"0":"")+e.toString(16)}function Fm(e,t,i,s){return s<=0?e=t=i=NaN:i<=0||i>=1?e=t=NaN:t<=0&&(e=NaN),new Um(e,t,i,s)}function Km(e){if(e instanceof Um)return new Um(e.h,e.s,e.l,e.opacity);if(e instanceof gm||(e=Lm(e)),!e)return new Um;if(e instanceof Um)return e;var t=(e=e.rgb()).r/255,i=e.g/255,s=e.b/255,r=Math.min(t,i,s),n=Math.max(t,i,s),o=NaN,a=n-r,l=(n+r)/2;return a?(o=t===n?(i-s)/a+6*(i<s):i===n?(s-t)/a+2:(t-i)/a+4,a/=l<.5?n+r:2-n-r,o*=60):a=l>0&&l<1?0:o,new Um(o,a,l,e.opacity)}function Um(e,t,i,s){this.h=+e,this.s=+t,this.l=+i,this.opacity=+s}function Vm(e){return(e=(e||0)%360)<0?e+360:e}function qm(e){return Math.max(0,Math.min(1,e||0))}function Ym(e,t,i){return 255*(e<60?t+(i-t)*e/60:e<180?i:e<240?t+(i-t)*(240-e)/60:t)}mm(gm,Lm,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:Rm,formatHex:Rm,formatHex8:function(){return this.rgb().formatHex8()},formatHsl:function(){return Km(this).formatHsl()},formatRgb:Pm,toString:Pm}),mm(Om,Bm,_m(gm,{brighter(e){return e=null==e?ym:Math.pow(ym,e),new Om(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=null==e?vm:Math.pow(vm,e),new Om(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new Om(Hm(this.r),Hm(this.g),Hm(this.b),$m(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:Am,formatHex:Am,formatHex8:function(){return`#${Wm(this.r)}${Wm(this.g)}${Wm(this.b)}${Wm(255*(isNaN(this.opacity)?1:this.opacity))}`},formatRgb:zm,toString:zm})),mm(Um,function(e,t,i,s){return 1===arguments.length?Km(e):new Um(e,t,i,null==s?1:s)},_m(gm,{brighter(e){return e=null==e?ym:Math.pow(ym,e),new Um(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=null==e?vm:Math.pow(vm,e),new Um(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=this.h%360+360*(this.h<0),t=isNaN(e)||isNaN(this.s)?0:this.s,i=this.l,s=i+(i<.5?i:1-i)*t,r=2*i-s;return new Om(Ym(e>=240?e-240:e+120,r,s),Ym(e,r,s),Ym(e<120?e+240:e-120,r,s),this.opacity)},clamp(){return new Um(Vm(this.h),qm(this.s),qm(this.l),$m(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const e=$m(this.opacity);return`${1===e?"hsl(":"hsla("}${Vm(this.h)}, ${100*qm(this.s)}%, ${100*qm(this.l)}%${1===e?")":`, ${e})`}`}}));const Xm=e=>()=>e;function Gm(e){return 1===(e=+e)?Zm:function(t,i){return i-t?function(e,t,i){return e=Math.pow(e,i),t=Math.pow(t,i)-e,i=1/i,function(s){return Math.pow(e+s*t,i)}}(t,i,e):Xm(isNaN(t)?i:t)}}function Zm(e,t){var i=t-e;return i?function(e,t){return function(i){return e+i*t}}(e,i):Xm(isNaN(e)?t:e)}const Jm=function e(t){var i=Gm(t);function s(e,t){var s=i((e=Bm(e)).r,(t=Bm(t)).r),r=i(e.g,t.g),n=i(e.b,t.b),o=Zm(e.opacity,t.opacity);return function(t){return e.r=s(t),e.g=r(t),e.b=n(t),e.opacity=o(t),e+""}}return s.gamma=e,s}(1);function Qm(e,t){return e=+e,t=+t,function(i){return e*(1-i)+t*i}}var e_=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,t_=new RegExp(e_.source,"g");function i_(e,t){var i,s,r,n=e_.lastIndex=t_.lastIndex=0,o=-1,a=[],l=[];for(e+="",t+="";(i=e_.exec(e))&&(s=t_.exec(t));)(r=s.index)>n&&(r=t.slice(n,r),a[o]?a[o]+=r:a[++o]=r),(i=i[0])===(s=s[0])?a[o]?a[o]+=s:a[++o]=s:(a[++o]=null,l.push({i:o,x:Qm(i,s)})),n=t_.lastIndex;return n<t.length&&(r=t.slice(n),a[o]?a[o]+=r:a[++o]=r),a.length<2?l[0]?function(e){return function(t){return e(t)+""}}(l[0].x):function(e){return function(){return e}}(t):(t=l.length,function(e){for(var i,s=0;s<t;++s)a[(i=l[s]).i]=i.x(e);return a.join("")})}var s_,r_=180/Math.PI,n_={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function o_(e,t,i,s,r,n){var o,a,l;return(o=Math.sqrt(e*e+t*t))&&(e/=o,t/=o),(l=e*i+t*s)&&(i-=e*l,s-=t*l),(a=Math.sqrt(i*i+s*s))&&(i/=a,s/=a,l/=a),e*s<t*i&&(e=-e,t=-t,l=-l,o=-o),{translateX:r,translateY:n,rotate:Math.atan2(t,e)*r_,skewX:Math.atan(l)*r_,scaleX:o,scaleY:a}}function a_(e,t,i,s){function r(e){return e.length?e.pop()+" ":""}return function(n,o){var a=[],l=[];return n=e(n),o=e(o),function(e,s,r,n,o,a){if(e!==r||s!==n){var l=o.push("translate(",null,t,null,i);a.push({i:l-4,x:Qm(e,r)},{i:l-2,x:Qm(s,n)})}else(r||n)&&o.push("translate("+r+t+n+i)}(n.translateX,n.translateY,o.translateX,o.translateY,a,l),function(e,t,i,n){e!==t?(e-t>180?t+=360:t-e>180&&(e+=360),n.push({i:i.push(r(i)+"rotate(",null,s)-2,x:Qm(e,t)})):t&&i.push(r(i)+"rotate("+t+s)}(n.rotate,o.rotate,a,l),function(e,t,i,n){e!==t?n.push({i:i.push(r(i)+"skewX(",null,s)-2,x:Qm(e,t)}):t&&i.push(r(i)+"skewX("+t+s)}(n.skewX,o.skewX,a,l),function(e,t,i,s,n,o){if(e!==i||t!==s){var a=n.push(r(n)+"scale(",null,",",null,")");o.push({i:a-4,x:Qm(e,i)},{i:a-2,x:Qm(t,s)})}else 1===i&&1===s||n.push(r(n)+"scale("+i+","+s+")")}(n.scaleX,n.scaleY,o.scaleX,o.scaleY,a,l),n=o=null,function(e){for(var t,i=-1,s=l.length;++i<s;)a[(t=l[i]).i]=t.x(e);return a.join("")}}}var l_=a_(function(e){const t=new("function"==typeof DOMMatrix?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?n_:o_(t.a,t.b,t.c,t.d,t.e,t.f)},"px, ","px)","deg)"),c_=a_(function(e){return null==e?n_:(s_||(s_=document.createElementNS("http://www.w3.org/2000/svg","g")),s_.setAttribute("transform",e),(e=s_.transform.baseVal.consolidate())?o_((e=e.matrix).a,e.b,e.c,e.d,e.e,e.f):n_)},", ",")",")");function h_(e){return((e=Math.exp(e))+1/e)/2}const d_=function e(t,i,s){function r(e,r){var n,o,a=e[0],l=e[1],c=e[2],h=r[0],d=r[1],u=r[2],f=h-a,p=d-l,m=f*f+p*p;if(m<1e-12)o=Math.log(u/c)/t,n=function(e){return[a+e*f,l+e*p,c*Math.exp(t*e*o)]};else{var _=Math.sqrt(m),g=(u*u-c*c+s*m)/(2*c*i*_),v=(u*u-c*c-s*m)/(2*u*i*_),y=Math.log(Math.sqrt(g*g+1)-g),x=Math.log(Math.sqrt(v*v+1)-v);o=(x-y)/t,n=function(e){var s,r=e*o,n=h_(y),h=c/(i*_)*(n*(s=t*r+y,((s=Math.exp(2*s))-1)/(s+1))-function(e){return((e=Math.exp(e))-1/e)/2}(y));return[a+h*f,l+h*p,c*n/h_(t*r+y)]}}return n.duration=1e3*o*t/Math.SQRT2,n}return r.rho=function(t){var i=Math.max(.001,+t),s=i*i;return e(i,s,s*s)},r}(Math.SQRT2,2,4);var u_,f_,p_=0,m_=0,__=0,g_=0,v_=0,y_=0,x_="object"==typeof performance&&performance.now?performance:Date,b_="object"==typeof window&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function w_(){return v_||(b_(S_),v_=x_.now()+y_)}function S_(){v_=0}function C_(){this._call=this._time=this._next=null}function k_(e,t,i){var s=new C_;return s.restart(e,t,i),s}function E_(){v_=(g_=x_.now())+y_,p_=m_=0;try{!function(){w_(),++p_;for(var e,t=u_;t;)(e=v_-t._time)>=0&&t._call.call(void 0,e),t=t._next;--p_}()}finally{p_=0,function(){var e,t,i=u_,s=1/0;for(;i;)i._call?(s>i._time&&(s=i._time),e=i,i=i._next):(t=i._next,i._next=null,i=e?e._next=t:u_=t);f_=e,M_(s)}(),v_=0}}function N_(){var e=x_.now(),t=e-g_;t>1e3&&(y_-=t,g_=e)}function M_(e){p_||(m_&&(m_=clearTimeout(m_)),e-v_>24?(e<1/0&&(m_=setTimeout(E_,e-x_.now()-y_)),__&&(__=clearInterval(__))):(__||(g_=x_.now(),__=setInterval(N_,1e3)),p_=1,b_(E_)))}function j_(e,t,i){var s=new C_;return t=null==t?0:+t,s.restart(i=>{s.stop(),e(i+t)},t,i),s}C_.prototype=k_.prototype={constructor:C_,restart:function(e,t,i){if("function"!=typeof e)throw new TypeError("callback is not a function");i=(null==i?w_():+i)+(null==t?0:+t),this._next||f_===this||(f_?f_._next=this:u_=this,f_=this),this._call=e,this._time=i,M_()},stop:function(){this._call&&(this._call=null,this._time=1/0,M_())}};var D_=zf("start","end","cancel","interrupt"),R_=[];function P_(e,t,i,s,r,n){var o=e.__transition;if(o){if(i in o)return}else e.__transition={};!function(e,t,i){var s,r=e.__transition;function n(e){i.state=1,i.timer.restart(o,i.delay,i.time),i.delay<=e&&o(e-i.delay)}function o(n){var c,h,d,u;if(1!==i.state)return l();for(c in r)if((u=r[c]).name===i.name){if(3===u.state)return j_(o);4===u.state?(u.state=6,u.timer.stop(),u.on.call("interrupt",e,e.__data__,u.index,u.group),delete r[c]):+c<t&&(u.state=6,u.timer.stop(),u.on.call("cancel",e,e.__data__,u.index,u.group),delete r[c])}if(j_(function(){3===i.state&&(i.state=4,i.timer.restart(a,i.delay,i.time),a(n))}),i.state=2,i.on.call("start",e,e.__data__,i.index,i.group),2===i.state){for(i.state=3,s=new Array(d=i.tween.length),c=0,h=-1;c<d;++c)(u=i.tween[c].value.call(e,e.__data__,i.index,i.group))&&(s[++h]=u);s.length=h+1}}function a(t){for(var r=t<i.duration?i.ease.call(null,t/i.duration):(i.timer.restart(l),i.state=5,1),n=-1,o=s.length;++n<o;)s[n].call(e,r);5===i.state&&(i.on.call("end",e,e.__data__,i.index,i.group),l())}function l(){for(var s in i.state=6,i.timer.stop(),delete r[t],r)return;delete e.__transition}r[t]=i,i.timer=k_(n,0,i.time)}(e,i,{name:t,index:s,group:r,on:D_,tween:R_,time:n.time,delay:n.delay,duration:n.duration,ease:n.ease,timer:null,state:0})}function L_(e,t){var i=I_(e,t);if(i.state>0)throw new Error("too late; already scheduled");return i}function T_(e,t){var i=I_(e,t);if(i.state>3)throw new Error("too late; already running");return i}function I_(e,t){var i=e.__transition;if(!i||!(i=i[t]))throw new Error("transition not found");return i}function B_(e,t){var i,s,r,n=e.__transition,o=!0;if(n){for(r in t=null==t?null:t+"",n)(i=n[r]).name===t?(s=i.state>2&&i.state<5,i.state=6,i.timer.stop(),i.on.call(s?"interrupt":"cancel",e,e.__data__,i.index,i.group),delete n[r]):o=!1;o&&delete e.__transition}}function O_(e,t){var i,s;return function(){var r=T_(this,e),n=r.tween;if(n!==i)for(var o=0,a=(s=i=n).length;o<a;++o)if(s[o].name===t){(s=s.slice()).splice(o,1);break}r.tween=s}}function A_(e,t,i){var s,r;if("function"!=typeof i)throw new Error;return function(){var n=T_(this,e),o=n.tween;if(o!==s){r=(s=o).slice();for(var a={name:t,value:i},l=0,c=r.length;l<c;++l)if(r[l].name===t){r[l]=a;break}l===c&&r.push(a)}n.tween=r}}function z_(e,t,i){var s=e._id;return e.each(function(){var e=T_(this,s);(e.value||(e.value={}))[t]=i.apply(this,arguments)}),function(e){return I_(e,s).value[t]}}function $_(e,t){var i;return("number"==typeof t?Qm:t instanceof Lm?Jm:(i=Lm(t))?(t=i,Jm):i_)(e,t)}function H_(e){return function(){this.removeAttribute(e)}}function W_(e){return function(){this.removeAttributeNS(e.space,e.local)}}function F_(e,t,i){var s,r,n=i+"";return function(){var o=this.getAttribute(e);return o===n?null:o===s?r:r=t(s=o,i)}}function K_(e,t,i){var s,r,n=i+"";return function(){var o=this.getAttributeNS(e.space,e.local);return o===n?null:o===s?r:r=t(s=o,i)}}function U_(e,t,i){var s,r,n;return function(){var o,a,l=i(this);if(null!=l)return(o=this.getAttribute(e))===(a=l+"")?null:o===s&&a===r?n:(r=a,n=t(s=o,l));this.removeAttribute(e)}}function V_(e,t,i){var s,r,n;return function(){var o,a,l=i(this);if(null!=l)return(o=this.getAttributeNS(e.space,e.local))===(a=l+"")?null:o===s&&a===r?n:(r=a,n=t(s=o,l));this.removeAttributeNS(e.space,e.local)}}function q_(e,t){var i,s;function r(){var r=t.apply(this,arguments);return r!==s&&(i=(s=r)&&function(e,t){return function(i){this.setAttributeNS(e.space,e.local,t.call(this,i))}}(e,r)),i}return r._value=t,r}function Y_(e,t){var i,s;function r(){var r=t.apply(this,arguments);return r!==s&&(i=(s=r)&&function(e,t){return function(i){this.setAttribute(e,t.call(this,i))}}(e,r)),i}return r._value=t,r}function X_(e,t){return function(){L_(this,e).delay=+t.apply(this,arguments)}}function G_(e,t){return t=+t,function(){L_(this,e).delay=t}}function Z_(e,t){return function(){T_(this,e).duration=+t.apply(this,arguments)}}function J_(e,t){return t=+t,function(){T_(this,e).duration=t}}var Q_=em.prototype.constructor;function eg(e){return function(){this.style.removeProperty(e)}}var tg=0;function ig(e,t,i,s){this._groups=e,this._parents=t,this._name=i,this._id=s}function sg(){return++tg}var rg=em.prototype;ig.prototype={constructor:ig,select:function(e){var t=this._name,i=this._id;"function"!=typeof e&&(e=Gf(e));for(var s=this._groups,r=s.length,n=new Array(r),o=0;o<r;++o)for(var a,l,c=s[o],h=c.length,d=n[o]=new Array(h),u=0;u<h;++u)(a=c[u])&&(l=e.call(a,a.__data__,u,c))&&("__data__"in a&&(l.__data__=a.__data__),d[u]=l,P_(d[u],t,i,u,d,I_(a,i)));return new ig(n,this._parents,t,i)},selectAll:function(e){var t=this._name,i=this._id;"function"!=typeof e&&(e=Jf(e));for(var s=this._groups,r=s.length,n=[],o=[],a=0;a<r;++a)for(var l,c=s[a],h=c.length,d=0;d<h;++d)if(l=c[d]){for(var u,f=e.call(l,l.__data__,d,c),p=I_(l,i),m=0,_=f.length;m<_;++m)(u=f[m])&&P_(u,t,i,m,f,p);n.push(f),o.push(l)}return new ig(n,o,t,i)},selectChild:rg.selectChild,selectChildren:rg.selectChildren,filter:function(e){"function"!=typeof e&&(e=ep(e));for(var t=this._groups,i=t.length,s=new Array(i),r=0;r<i;++r)for(var n,o=t[r],a=o.length,l=s[r]=[],c=0;c<a;++c)(n=o[c])&&e.call(n,n.__data__,c,o)&&l.push(n);return new ig(s,this._parents,this._name,this._id)},merge:function(e){if(e._id!==this._id)throw new Error;for(var t=this._groups,i=e._groups,s=t.length,r=i.length,n=Math.min(s,r),o=new Array(s),a=0;a<n;++a)for(var l,c=t[a],h=i[a],d=c.length,u=o[a]=new Array(d),f=0;f<d;++f)(l=c[f]||h[f])&&(u[f]=l);for(;a<s;++a)o[a]=t[a];return new ig(o,this._parents,this._name,this._id)},selection:function(){return new Q_(this._groups,this._parents)},transition:function(){for(var e=this._name,t=this._id,i=sg(),s=this._groups,r=s.length,n=0;n<r;++n)for(var o,a=s[n],l=a.length,c=0;c<l;++c)if(o=a[c]){var h=I_(o,t);P_(o,e,i,c,a,{time:h.time+h.delay+h.duration,delay:0,duration:h.duration,ease:h.ease})}return new ig(s,this._parents,e,i)},call:rg.call,nodes:rg.nodes,node:rg.node,size:rg.size,empty:rg.empty,each:rg.each,on:function(e,t){var i=this._id;return arguments.length<2?I_(this.node(),i).on.on(e):this.each(function(e,t,i){var s,r,n=function(e){return(e+"").trim().split(/^|\s+/).every(function(e){var t=e.indexOf(".");return t>=0&&(e=e.slice(0,t)),!e||"start"===e})}(t)?L_:T_;return function(){var o=n(this,e),a=o.on;a!==s&&(r=(s=a).copy()).on(t,i),o.on=r}}(i,e,t))},attr:function(e,t){var i=Uf(e),s="transform"===i?c_:$_;return this.attrTween(e,"function"==typeof t?(i.local?V_:U_)(i,s,z_(this,"attr."+e,t)):null==t?(i.local?W_:H_)(i):(i.local?K_:F_)(i,s,t))},attrTween:function(e,t){var i="attr."+e;if(arguments.length<2)return(i=this.tween(i))&&i._value;if(null==t)return this.tween(i,null);if("function"!=typeof t)throw new Error;var s=Uf(e);return this.tween(i,(s.local?q_:Y_)(s,t))},style:function(e,t,i){var s="transform"==(e+="")?l_:$_;return null==t?this.styleTween(e,function(e,t){var i,s,r;return function(){var n=Sp(this,e),o=(this.style.removeProperty(e),Sp(this,e));return n===o?null:n===i&&o===s?r:r=t(i=n,s=o)}}(e,s)).on("end.style."+e,eg(e)):"function"==typeof t?this.styleTween(e,function(e,t,i){var s,r,n;return function(){var o=Sp(this,e),a=i(this),l=a+"";return null==a&&(this.style.removeProperty(e),l=a=Sp(this,e)),o===l?null:o===s&&l===r?n:(r=l,n=t(s=o,a))}}(e,s,z_(this,"style."+e,t))).each(function(e,t){var i,s,r,n,o="style."+t,a="end."+o;return function(){var l=T_(this,e),c=l.on,h=null==l.value[o]?n||(n=eg(t)):void 0;c===i&&r===h||(s=(i=c).copy()).on(a,r=h),l.on=s}}(this._id,e)):this.styleTween(e,function(e,t,i){var s,r,n=i+"";return function(){var o=Sp(this,e);return o===n?null:o===s?r:r=t(s=o,i)}}(e,s,t),i).on("end.style."+e,null)},styleTween:function(e,t,i){var s="style."+(e+="");if(arguments.length<2)return(s=this.tween(s))&&s._value;if(null==t)return this.tween(s,null);if("function"!=typeof t)throw new Error;return this.tween(s,function(e,t,i){var s,r;function n(){var n=t.apply(this,arguments);return n!==r&&(s=(r=n)&&function(e,t,i){return function(s){this.style.setProperty(e,t.call(this,s),i)}}(e,n,i)),s}return n._value=t,n}(e,t,null==i?"":i))},text:function(e){return this.tween("text","function"==typeof e?function(e){return function(){var t=e(this);this.textContent=null==t?"":t}}(z_(this,"text",e)):function(e){return function(){this.textContent=e}}(null==e?"":e+""))},textTween:function(e){var t="text";if(arguments.length<1)return(t=this.tween(t))&&t._value;if(null==e)return this.tween(t,null);if("function"!=typeof e)throw new Error;return this.tween(t,function(e){var t,i;function s(){var s=e.apply(this,arguments);return s!==i&&(t=(i=s)&&function(e){return function(t){this.textContent=e.call(this,t)}}(s)),t}return s._value=e,s}(e))},remove:function(){return this.on("end.remove",(e=this._id,function(){var t=this.parentNode;for(var i in this.__transition)if(+i!==e)return;t&&t.removeChild(this)}));var e},tween:function(e,t){var i=this._id;if(e+="",arguments.length<2){for(var s,r=I_(this.node(),i).tween,n=0,o=r.length;n<o;++n)if((s=r[n]).name===e)return s.value;return null}return this.each((null==t?O_:A_)(i,e,t))},delay:function(e){var t=this._id;return arguments.length?this.each(("function"==typeof e?X_:G_)(t,e)):I_(this.node(),t).delay},duration:function(e){var t=this._id;return arguments.length?this.each(("function"==typeof e?Z_:J_)(t,e)):I_(this.node(),t).duration},ease:function(e){var t=this._id;return arguments.length?this.each(function(e,t){if("function"!=typeof t)throw new Error;return function(){T_(this,e).ease=t}}(t,e)):I_(this.node(),t).ease},easeVarying:function(e){if("function"!=typeof e)throw new Error;return this.each(function(e,t){return function(){var i=t.apply(this,arguments);if("function"!=typeof i)throw new Error;T_(this,e).ease=i}}(this._id,e))},end:function(){var e,t,i=this,s=i._id,r=i.size();return new Promise(function(n,o){var a={value:o},l={value:function(){0===--r&&n()}};i.each(function(){var i=T_(this,s),r=i.on;r!==e&&((t=(e=r).copy())._.cancel.push(a),t._.interrupt.push(a),t._.end.push(l)),i.on=t}),0===r&&n()})},[Symbol.iterator]:rg[Symbol.iterator]};var ng={time:null,delay:0,duration:250,ease:function(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}};function og(e,t){for(var i;!(i=e.__transition)||!(i=i[t]);)if(!(e=e.parentNode))throw new Error(`transition ${t} not found`);return i}em.prototype.interrupt=function(e){return this.each(function(){B_(this,e)})},em.prototype.transition=function(e){var t,i;e instanceof ig?(t=e._id,e=e._name):(t=sg(),(i=ng).time=w_(),e=null==e?null:e+"");for(var s=this._groups,r=s.length,n=0;n<r;++n)for(var o,a=s[n],l=a.length,c=0;c<l;++c)(o=a[c])&&P_(o,e,t,c,a,i||og(o,t));return new ig(s,this._parents,e,t)};const ag=e=>()=>e;function lg(e,{sourceEvent:t,target:i,transform:s,dispatch:r}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},target:{value:i,enumerable:!0,configurable:!0},transform:{value:s,enumerable:!0,configurable:!0},_:{value:r}})}function cg(e,t,i){this.k=e,this.x=t,this.y=i}cg.prototype={constructor:cg,scale:function(e){return 1===e?this:new cg(this.k*e,this.x,this.y)},translate:function(e,t){return 0===e&0===t?this:new cg(this.k,this.x+this.k*e,this.y+this.k*t)},apply:function(e){return[e[0]*this.k+this.x,e[1]*this.k+this.y]},applyX:function(e){return e*this.k+this.x},applyY:function(e){return e*this.k+this.y},invert:function(e){return[(e[0]-this.x)/this.k,(e[1]-this.y)/this.k]},invertX:function(e){return(e-this.x)/this.k},invertY:function(e){return(e-this.y)/this.k},rescaleX:function(e){return e.copy().domain(e.range().map(this.invertX,this).map(e.invert,e))},rescaleY:function(e){return e.copy().domain(e.range().map(this.invertY,this).map(e.invert,e))},toString:function(){return"translate("+this.x+","+this.y+") scale("+this.k+")"}};var hg=new cg(1,0,0);function dg(e){e.stopImmediatePropagation()}function ug(e){e.preventDefault(),e.stopImmediatePropagation()}function fg(e){return!(e.ctrlKey&&"wheel"!==e.type||e.button)}function pg(){var e=this;return e instanceof SVGElement?(e=e.ownerSVGElement||e).hasAttribute("viewBox")?[[(e=e.viewBox.baseVal).x,e.y],[e.x+e.width,e.y+e.height]]:[[0,0],[e.width.baseVal.value,e.height.baseVal.value]]:[[0,0],[e.clientWidth,e.clientHeight]]}function mg(){return this.__zoom||hg}function _g(e){return-e.deltaY*(1===e.deltaMode?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function gg(){return navigator.maxTouchPoints||"ontouchstart"in this}function vg(e,t,i){var s=e.invertX(t[0][0])-i[0][0],r=e.invertX(t[1][0])-i[1][0],n=e.invertY(t[0][1])-i[0][1],o=e.invertY(t[1][1])-i[1][1];return e.translate(r>s?(s+r)/2:Math.min(0,s)||Math.max(0,r),o>n?(n+o)/2:Math.min(0,n)||Math.max(0,o))}function yg(){var e,t,i,s=fg,r=pg,n=vg,o=_g,a=gg,l=[0,1/0],c=[[-1/0,-1/0],[1/0,1/0]],h=250,d=d_,u=zf("start","zoom","end"),f=0,p=10;function m(e){e.property("__zoom",mg).on("wheel.zoom",w,{passive:!1}).on("mousedown.zoom",S).on("dblclick.zoom",C).filter(a).on("touchstart.zoom",k).on("touchmove.zoom",E).on("touchend.zoom touchcancel.zoom",N).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function _(e,t){return(t=Math.max(l[0],Math.min(l[1],t)))===e.k?e:new cg(t,e.x,e.y)}function g(e,t,i){var s=t[0]-i[0]*e.k,r=t[1]-i[1]*e.k;return s===e.x&&r===e.y?e:new cg(e.k,s,r)}function v(e){return[(+e[0][0]+ +e[1][0])/2,(+e[0][1]+ +e[1][1])/2]}function y(e,t,i,s){e.on("start.zoom",function(){x(this,arguments).event(s).start()}).on("interrupt.zoom end.zoom",function(){x(this,arguments).event(s).end()}).tween("zoom",function(){var e=this,n=arguments,o=x(e,n).event(s),a=r.apply(e,n),l=null==i?v(a):"function"==typeof i?i.apply(e,n):i,c=Math.max(a[1][0]-a[0][0],a[1][1]-a[0][1]),h=e.__zoom,u="function"==typeof t?t.apply(e,n):t,f=d(h.invert(l).concat(c/h.k),u.invert(l).concat(c/u.k));return function(e){if(1===e)e=u;else{var t=f(e),i=c/t[2];e=new cg(i,l[0]-t[0]*i,l[1]-t[1]*i)}o.zoom(null,e)}})}function x(e,t,i){return!i&&e.__zooming||new b(e,t)}function b(e,t){this.that=e,this.args=t,this.active=0,this.sourceEvent=null,this.extent=r.apply(e,t),this.taps=0}function w(e,...t){if(s.apply(this,arguments)){var i=x(this,t).event(e),r=this.__zoom,a=Math.max(l[0],Math.min(l[1],r.k*Math.pow(2,o.apply(this,arguments)))),h=im(e);if(i.wheel)i.mouse[0][0]===h[0]&&i.mouse[0][1]===h[1]||(i.mouse[1]=r.invert(i.mouse[0]=h)),clearTimeout(i.wheel);else{if(r.k===a)return;i.mouse=[h,r.invert(h)],B_(this),i.start()}ug(e),i.wheel=setTimeout(function(){i.wheel=null,i.end()},150),i.zoom("mouse",n(g(_(r,a),i.mouse[0],i.mouse[1]),i.extent,c))}}function S(e,...t){if(!i&&s.apply(this,arguments)){var r=e.currentTarget,o=x(this,t,!0).event(e),a=tm(e.view).on("mousemove.zoom",function(e){if(ug(e),!o.moved){var t=e.clientX-h,i=e.clientY-d;o.moved=t*t+i*i>f}o.event(e).zoom("mouse",n(g(o.that.__zoom,o.mouse[0]=im(e,r),o.mouse[1]),o.extent,c))},!0).on("mouseup.zoom",function(e){a.on("mousemove.zoom mouseup.zoom",null),lm(e.view,o.moved),ug(e),o.event(e).end()},!0),l=im(e,r),h=e.clientX,d=e.clientY;am(e.view),dg(e),o.mouse=[l,this.__zoom.invert(l)],B_(this),o.start()}}function C(e,...t){if(s.apply(this,arguments)){var i=this.__zoom,o=im(e.changedTouches?e.changedTouches[0]:e,this),a=i.invert(o),l=i.k*(e.shiftKey?.5:2),d=n(g(_(i,l),o,a),r.apply(this,t),c);ug(e),h>0?tm(this).transition().duration(h).call(y,d,o,e):tm(this).call(m.transform,d,o,e)}}function k(i,...r){if(s.apply(this,arguments)){var n,o,a,l,c=i.touches,h=c.length,d=x(this,r,i.changedTouches.length===h).event(i);for(dg(i),o=0;o<h;++o)l=[l=im(a=c[o],this),this.__zoom.invert(l),a.identifier],d.touch0?d.touch1||d.touch0[2]===l[2]||(d.touch1=l,d.taps=0):(d.touch0=l,n=!0,d.taps=1+!!e);e&&(e=clearTimeout(e)),n&&(d.taps<2&&(t=l[0],e=setTimeout(function(){e=null},500)),B_(this),d.start())}}function E(e,...t){if(this.__zooming){var i,s,r,o,a=x(this,t).event(e),l=e.changedTouches,h=l.length;for(ug(e),i=0;i<h;++i)r=im(s=l[i],this),a.touch0&&a.touch0[2]===s.identifier?a.touch0[0]=r:a.touch1&&a.touch1[2]===s.identifier&&(a.touch1[0]=r);if(s=a.that.__zoom,a.touch1){var d=a.touch0[0],u=a.touch0[1],f=a.touch1[0],p=a.touch1[1],m=(m=f[0]-d[0])*m+(m=f[1]-d[1])*m,v=(v=p[0]-u[0])*v+(v=p[1]-u[1])*v;s=_(s,Math.sqrt(m/v)),r=[(d[0]+f[0])/2,(d[1]+f[1])/2],o=[(u[0]+p[0])/2,(u[1]+p[1])/2]}else{if(!a.touch0)return;r=a.touch0[0],o=a.touch0[1]}a.zoom("touch",n(g(s,r,o),a.extent,c))}}function N(e,...s){if(this.__zooming){var r,n,o=x(this,s).event(e),a=e.changedTouches,l=a.length;for(dg(e),i&&clearTimeout(i),i=setTimeout(function(){i=null},500),r=0;r<l;++r)n=a[r],o.touch0&&o.touch0[2]===n.identifier?delete o.touch0:o.touch1&&o.touch1[2]===n.identifier&&delete o.touch1;if(o.touch1&&!o.touch0&&(o.touch0=o.touch1,delete o.touch1),o.touch0)o.touch0[1]=this.__zoom.invert(o.touch0[0]);else if(o.end(),2===o.taps&&(n=im(n,this),Math.hypot(t[0]-n[0],t[1]-n[1])<p)){var c=tm(this).on("dblclick.zoom");c&&c.apply(this,arguments)}}}return m.transform=function(e,t,i,s){var r=e.selection?e.selection():e;r.property("__zoom",mg),e!==r?y(e,t,i,s):r.interrupt().each(function(){x(this,arguments).event(s).start().zoom(null,"function"==typeof t?t.apply(this,arguments):t).end()})},m.scaleBy=function(e,t,i,s){m.scaleTo(e,function(){return this.__zoom.k*("function"==typeof t?t.apply(this,arguments):t)},i,s)},m.scaleTo=function(e,t,i,s){m.transform(e,function(){var e=r.apply(this,arguments),s=this.__zoom,o=null==i?v(e):"function"==typeof i?i.apply(this,arguments):i,a=s.invert(o),l="function"==typeof t?t.apply(this,arguments):t;return n(g(_(s,l),o,a),e,c)},i,s)},m.translateBy=function(e,t,i,s){m.transform(e,function(){return n(this.__zoom.translate("function"==typeof t?t.apply(this,arguments):t,"function"==typeof i?i.apply(this,arguments):i),r.apply(this,arguments),c)},null,s)},m.translateTo=function(e,t,i,s,o){m.transform(e,function(){var e=r.apply(this,arguments),o=this.__zoom,a=null==s?v(e):"function"==typeof s?s.apply(this,arguments):s;return n(hg.translate(a[0],a[1]).scale(o.k).translate("function"==typeof t?-t.apply(this,arguments):-t,"function"==typeof i?-i.apply(this,arguments):-i),e,c)},s,o)},b.prototype={event:function(e){return e&&(this.sourceEvent=e),this},start:function(){return 1===++this.active&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(e,t){return this.mouse&&"mouse"!==e&&(this.mouse[1]=t.invert(this.mouse[0])),this.touch0&&"touch"!==e&&(this.touch0[1]=t.invert(this.touch0[0])),this.touch1&&"touch"!==e&&(this.touch1[1]=t.invert(this.touch1[0])),this.that.__zoom=t,this.emit("zoom"),this},end:function(){return 0===--this.active&&(delete this.that.__zooming,this.emit("end")),this},emit:function(e){var t=tm(this.that).datum();u.call(e,this.that,new lg(e,{sourceEvent:this.sourceEvent,target:m,transform:this.that.__zoom,dispatch:u}),t)}},m.wheelDelta=function(e){return arguments.length?(o="function"==typeof e?e:ag(+e),m):o},m.filter=function(e){return arguments.length?(s="function"==typeof e?e:ag(!!e),m):s},m.touchable=function(e){return arguments.length?(a="function"==typeof e?e:ag(!!e),m):a},m.extent=function(e){return arguments.length?(r="function"==typeof e?e:ag([[+e[0][0],+e[0][1]],[+e[1][0],+e[1][1]]]),m):r},m.scaleExtent=function(e){return arguments.length?(l[0]=+e[0],l[1]=+e[1],m):[l[0],l[1]]},m.translateExtent=function(e){return arguments.length?(c[0][0]=+e[0][0],c[1][0]=+e[1][0],c[0][1]=+e[0][1],c[1][1]=+e[1][1],m):[[c[0][0],c[0][1]],[c[1][0],c[1][1]]]},m.constrain=function(e){return arguments.length?(n=e,m):n},m.duration=function(e){return arguments.length?(h=+e,m):h},m.interpolate=function(e){return arguments.length?(d=e,m):d},m.on=function(){var e=u.on.apply(u,arguments);return e===u?m:e},m.clickDistance=function(e){return arguments.length?(f=(e=+e)*e,m):Math.sqrt(f)},m.tapDistance=function(e){return arguments.length?(p=+e,m):p},m}cg.prototype;const xg=h.createContext(null),bg=xg.Provider,wg=e=>`Node type "${e}" not found. Using fallback type "default".`,Sg=()=>"The React Flow parent container needs a width and a height to render the graph.",Cg=()=>"Only child nodes can use a parent extent.",kg=e=>`Marker type "${e}" doesn't exist.`,Eg=(e,t)=>`Couldn't create edge for ${e?"target":"source"} handle id: "${e?t.targetHandle:t.sourceHandle}", edge id: ${t.id}.`,Ng=()=>"Handle: No node id found. Make sure to only use a Handle inside a custom Node.",Mg=e=>`Edge type "${e}" not found. Using fallback type "default".`,jg=e=>`Node with id "${e}" does not exist, it may have been removed. This can happen when a node is deleted before the "onNodeClick" handler is called.`,Dg=(()=>"[React Flow]: Seems like you have not used zustand provider as an ancestor. Help: https://reactflow.dev/error#001")();function Rg(e,t){const i=h.useContext(xg);if(null===i)throw new Error(Dg);return If(i,e,t)}const Pg=()=>{const e=h.useContext(xg);if(null===e)throw new Error(Dg);return h.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe,destroy:e.destroy}),[e])},Lg=e=>e.userSelectionActive?"none":"all";function Tg({position:e,children:t,className:i,style:s,...r}){const n=Rg(Lg),o=`${e}`.split("-");return N.createElement("div",{className:vf(["react-flow__panel",i,...o]),style:{...s,pointerEvents:n},...r},t)}function Ig({proOptions:e,position:t="bottom-right"}){return(null==e?void 0:e.hideAttribution)?null:N.createElement(Tg,{position:t,className:"react-flow__attribution","data-message":"Please only hide this attribution when you are subscribed to React Flow Pro: https://reactflow.dev/pro"},N.createElement("a",{href:"https://reactflow.dev",target:"_blank",rel:"noopener noreferrer","aria-label":"React Flow attribution"},"React Flow"))}var Bg=h.memo(({x:e,y:t,label:i,labelStyle:s={},labelShowBg:r=!0,labelBgStyle:n={},labelBgPadding:o=[2,4],labelBgBorderRadius:a=2,children:l,className:c,...d})=>{const u=h.useRef(null),[f,p]=h.useState({x:0,y:0,width:0,height:0}),m=vf(["react-flow__edge-textwrapper",c]);return h.useEffect(()=>{if(u.current){const e=u.current.getBBox();p({x:e.x,y:e.y,width:e.width,height:e.height})}},[i]),void 0!==i&&i?N.createElement("g",{transform:`translate(${e-f.width/2} ${t-f.height/2})`,className:m,visibility:f.width?"visible":"hidden",...d},r&&N.createElement("rect",{width:f.width+2*o[0],x:-o[0],y:-o[1],height:f.height+2*o[1],className:"react-flow__edge-textbg",style:n,rx:a,ry:a}),N.createElement("text",{className:"react-flow__edge-text",y:f.height/2,dy:"0.3em",ref:u,style:s},i),l):null});const Og=e=>({width:e.offsetWidth,height:e.offsetHeight}),Ag=(e,t=0,i=1)=>Math.min(Math.max(e,t),i),zg=(e={x:0,y:0},t)=>({x:Ag(e.x,t[0][0],t[1][0]),y:Ag(e.y,t[0][1],t[1][1])}),$g=(e,t,i)=>e<t?Ag(Math.abs(e-t),1,50)/50:e>i?-Ag(Math.abs(e-i),1,50)/50:0,Hg=(e,t)=>[20*$g(e.x,35,t.width-35),20*$g(e.y,35,t.height-35)],Wg=e=>{var t;return(null==(t=e.getRootNode)?void 0:t.call(e))||(null==window?void 0:window.document)},Fg=(e,t)=>({x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),x2:Math.max(e.x2,t.x2),y2:Math.max(e.y2,t.y2)}),Kg=({x:e,y:t,width:i,height:s})=>({x:e,y:t,x2:e+i,y2:t+s}),Ug=({x:e,y:t,x2:i,y2:s})=>({x:e,y:t,width:i-e,height:s-t}),Vg=e=>({...e.positionAbsolute||{x:0,y:0},width:e.width||0,height:e.height||0}),qg=(e,t)=>{const i=Math.max(0,Math.min(e.x+e.width,t.x+t.width)-Math.max(e.x,t.x)),s=Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y));return Math.ceil(i*s)},Yg=e=>!isNaN(e)&&isFinite(e),Xg=Symbol.for("internals"),Gg=["Enter"," ","Escape"];function Zg(e){var t,i;const s=(e=>"nativeEvent"in e)(e)?e.nativeEvent:e,r=(null==(i=null==(t=s.composedPath)?void 0:t.call(s))?void 0:i[0])||e.target;return["INPUT","SELECT","TEXTAREA"].includes(null==r?void 0:r.nodeName)||(null==r?void 0:r.hasAttribute("contenteditable"))||!!(null==r?void 0:r.closest(".nokey"))}const Jg=e=>"clientX"in e,Qg=(e,t)=>{var i,s;const r=Jg(e),n=r?e.clientX:null==(i=e.touches)?void 0:i[0].clientX,o=r?e.clientY:null==(s=e.touches)?void 0:s[0].clientY;return{x:n-((null==t?void 0:t.left)??0),y:o-((null==t?void 0:t.top)??0)}},ev=()=>{var e;return"undefined"!=typeof navigator&&(null==(e=null==navigator?void 0:navigator.userAgent)?void 0:e.indexOf("Mac"))>=0},tv=({id:e,path:t,labelX:i,labelY:s,label:r,labelStyle:n,labelShowBg:o,labelBgStyle:a,labelBgPadding:l,labelBgBorderRadius:c,style:h,markerEnd:d,markerStart:u,interactionWidth:f=20})=>N.createElement(N.Fragment,null,N.createElement("path",{id:e,style:h,d:t,fill:"none",className:"react-flow__edge-path",markerEnd:d,markerStart:u}),f&&N.createElement("path",{d:t,fill:"none",strokeOpacity:0,strokeWidth:f,className:"react-flow__edge-interaction"}),r&&Yg(i)&&Yg(s)?N.createElement(Bg,{x:i,y:s,label:r,labelStyle:n,labelShowBg:o,labelBgStyle:a,labelBgPadding:l,labelBgBorderRadius:c}):null);function iv(e,t,i){return void 0===i?i:s=>{const r=t().edges.find(t=>t.id===e);r&&i(s,{...r})}}function sv({sourceX:e,sourceY:t,targetX:i,targetY:s}){const r=Math.abs(i-e)/2,n=i<e?i+r:i-r,o=Math.abs(s-t)/2;return[n,s<t?s+o:s-o,r,o]}function rv({sourceX:e,sourceY:t,targetX:i,targetY:s,sourceControlX:r,sourceControlY:n,targetControlX:o,targetControlY:a}){const l=.125*e+.375*r+.375*o+.125*i,c=.125*t+.375*n+.375*a+.125*s;return[l,c,Math.abs(l-e),Math.abs(c-t)]}var nv,ov,av,lv,cv,hv,dv,uv,fv,pv,mv,_v;function gv({pos:e,x1:t,y1:i,x2:s,y2:r}){return e===mv.Left||e===mv.Right?[.5*(t+s),i]:[t,.5*(i+r)]}function vv({sourceX:e,sourceY:t,sourcePosition:i=mv.Bottom,targetX:s,targetY:r,targetPosition:n=mv.Top}){const[o,a]=gv({pos:i,x1:e,y1:t,x2:s,y2:r}),[l,c]=gv({pos:n,x1:s,y1:r,x2:e,y2:t}),[h,d,u,f]=rv({sourceX:e,sourceY:t,targetX:s,targetY:r,sourceControlX:o,sourceControlY:a,targetControlX:l,targetControlY:c});return[`M${e},${t} C${o},${a} ${l},${c} ${s},${r}`,h,d,u,f]}tv.displayName="BaseEdge",(ov=nv||(nv={})).Strict="strict",ov.Loose="loose",(lv=av||(av={})).Free="free",lv.Vertical="vertical",lv.Horizontal="horizontal",(hv=cv||(cv={})).Partial="partial",hv.Full="full",(uv=dv||(dv={})).Bezier="default",uv.Straight="straight",uv.Step="step",uv.SmoothStep="smoothstep",uv.SimpleBezier="simplebezier",(pv=fv||(fv={})).Arrow="arrow",pv.ArrowClosed="arrowclosed",(_v=mv||(mv={})).Left="left",_v.Top="top",_v.Right="right",_v.Bottom="bottom";const yv=h.memo(({sourceX:e,sourceY:t,targetX:i,targetY:s,sourcePosition:r=mv.Bottom,targetPosition:n=mv.Top,label:o,labelStyle:a,labelShowBg:l,labelBgStyle:c,labelBgPadding:h,labelBgBorderRadius:d,style:u,markerEnd:f,markerStart:p,interactionWidth:m})=>{const[_,g,v]=vv({sourceX:e,sourceY:t,sourcePosition:r,targetX:i,targetY:s,targetPosition:n});return N.createElement(tv,{path:_,labelX:g,labelY:v,label:o,labelStyle:a,labelShowBg:l,labelBgStyle:c,labelBgPadding:h,labelBgBorderRadius:d,style:u,markerEnd:f,markerStart:p,interactionWidth:m})});yv.displayName="SimpleBezierEdge";const xv={[mv.Left]:{x:-1,y:0},[mv.Right]:{x:1,y:0},[mv.Top]:{x:0,y:-1},[mv.Bottom]:{x:0,y:1}},bv=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function wv({source:e,sourcePosition:t=mv.Bottom,target:i,targetPosition:s=mv.Top,center:r,offset:n}){const o=xv[t],a=xv[s],l={x:e.x+o.x*n,y:e.y+o.y*n},c={x:i.x+a.x*n,y:i.y+a.y*n},h=(({source:e,sourcePosition:t=mv.Bottom,target:i})=>t===mv.Left||t===mv.Right?e.x<i.x?{x:1,y:0}:{x:-1,y:0}:e.y<i.y?{x:0,y:1}:{x:0,y:-1})({source:l,sourcePosition:t,target:c}),d=0!==h.x?"x":"y",u=h[d];let f,p,m=[];const _={x:0,y:0},g={x:0,y:0},[v,y,x,b]=sv({sourceX:e.x,sourceY:e.y,targetX:i.x,targetY:i.y});if(o[d]*a[d]===-1){f=r.x??v,p=r.y??y;const e=[{x:f,y:l.y},{x:f,y:c.y}],t=[{x:l.x,y:p},{x:c.x,y:p}];m=o[d]===u?"x"===d?e:t:"x"===d?t:e}else{const r=[{x:l.x,y:c.y}],h=[{x:c.x,y:l.y}];if(m="x"===d?o.x===u?h:r:o.y===u?r:h,t===s){const t=Math.abs(e[d]-i[d]);if(t<=n){const s=Math.min(n-1,n-t);o[d]===u?_[d]=(l[d]>e[d]?-1:1)*s:g[d]=(c[d]>i[d]?-1:1)*s}}if(t!==s){const e="x"===d?"y":"x",t=o[d]===a[e],i=l[e]>c[e],s=l[e]<c[e];(1===o[d]&&(!t&&i||t&&s)||1!==o[d]&&(!t&&s||t&&i))&&(m="x"===d?r:h)}const v={x:l.x+_.x,y:l.y+_.y},y={x:c.x+g.x,y:c.y+g.y};Math.max(Math.abs(v.x-m[0].x),Math.abs(y.x-m[0].x))>=Math.max(Math.abs(v.y-m[0].y),Math.abs(y.y-m[0].y))?(f=(v.x+y.x)/2,p=m[0].y):(f=m[0].x,p=(v.y+y.y)/2)}return[[e,{x:l.x+_.x,y:l.y+_.y},...m,{x:c.x+g.x,y:c.y+g.y},i],f,p,x,b]}function Sv({sourceX:e,sourceY:t,sourcePosition:i=mv.Bottom,targetX:s,targetY:r,targetPosition:n=mv.Top,borderRadius:o=5,centerX:a,centerY:l,offset:c=20}){const[h,d,u,f,p]=wv({source:{x:e,y:t},sourcePosition:i,target:{x:s,y:r},targetPosition:n,center:{x:a,y:l},offset:c}),m=h.reduce((e,t,i)=>{let s="";return s=i>0&&i<h.length-1?function(e,t,i,s){const r=Math.min(bv(e,t)/2,bv(t,i)/2,s),{x:n,y:o}=t;if(e.x===n&&n===i.x||e.y===o&&o===i.y)return`L${n} ${o}`;if(e.y===o)return`L ${n+r*(e.x<i.x?-1:1)},${o}Q ${n},${o} ${n},${o+r*(e.y<i.y?1:-1)}`;const a=e.x<i.x?1:-1;return`L ${n},${o+r*(e.y<i.y?-1:1)}Q ${n},${o} ${n+r*a},${o}`}(h[i-1],t,h[i+1],o):`${0===i?"M":"L"}${t.x} ${t.y}`,e+=s},"");return[m,d,u,f,p]}const Cv=h.memo(({sourceX:e,sourceY:t,targetX:i,targetY:s,label:r,labelStyle:n,labelShowBg:o,labelBgStyle:a,labelBgPadding:l,labelBgBorderRadius:c,style:h,sourcePosition:d=mv.Bottom,targetPosition:u=mv.Top,markerEnd:f,markerStart:p,pathOptions:m,interactionWidth:_})=>{const[g,v,y]=Sv({sourceX:e,sourceY:t,sourcePosition:d,targetX:i,targetY:s,targetPosition:u,borderRadius:null==m?void 0:m.borderRadius,offset:null==m?void 0:m.offset});return N.createElement(tv,{path:g,labelX:v,labelY:y,label:r,labelStyle:n,labelShowBg:o,labelBgStyle:a,labelBgPadding:l,labelBgBorderRadius:c,style:h,markerEnd:f,markerStart:p,interactionWidth:_})});Cv.displayName="SmoothStepEdge";const kv=h.memo(e=>{var t;return N.createElement(Cv,{...e,pathOptions:h.useMemo(()=>{var t;return{borderRadius:0,offset:null==(t=e.pathOptions)?void 0:t.offset}},[null==(t=e.pathOptions)?void 0:t.offset])})});kv.displayName="StepEdge";const Ev=h.memo(({sourceX:e,sourceY:t,targetX:i,targetY:s,label:r,labelStyle:n,labelShowBg:o,labelBgStyle:a,labelBgPadding:l,labelBgBorderRadius:c,style:h,markerEnd:d,markerStart:u,interactionWidth:f})=>{const[p,m,_]=function({sourceX:e,sourceY:t,targetX:i,targetY:s}){const[r,n,o,a]=sv({sourceX:e,sourceY:t,targetX:i,targetY:s});return[`M ${e},${t}L ${i},${s}`,r,n,o,a]}({sourceX:e,sourceY:t,targetX:i,targetY:s});return N.createElement(tv,{path:p,labelX:m,labelY:_,label:r,labelStyle:n,labelShowBg:o,labelBgStyle:a,labelBgPadding:l,labelBgBorderRadius:c,style:h,markerEnd:d,markerStart:u,interactionWidth:f})});function Nv(e,t){return e>=0?.5*e:25*t*Math.sqrt(-e)}function Mv({pos:e,x1:t,y1:i,x2:s,y2:r,c:n}){switch(e){case mv.Left:return[t-Nv(t-s,n),i];case mv.Right:return[t+Nv(s-t,n),i];case mv.Top:return[t,i-Nv(i-r,n)];case mv.Bottom:return[t,i+Nv(r-i,n)]}}function jv({sourceX:e,sourceY:t,sourcePosition:i=mv.Bottom,targetX:s,targetY:r,targetPosition:n=mv.Top,curvature:o=.25}){const[a,l]=Mv({pos:i,x1:e,y1:t,x2:s,y2:r,c:o}),[c,h]=Mv({pos:n,x1:s,y1:r,x2:e,y2:t,c:o}),[d,u,f,p]=rv({sourceX:e,sourceY:t,targetX:s,targetY:r,sourceControlX:a,sourceControlY:l,targetControlX:c,targetControlY:h});return[`M${e},${t} C${a},${l} ${c},${h} ${s},${r}`,d,u,f,p]}Ev.displayName="StraightEdge";const Dv=h.memo(({sourceX:e,sourceY:t,targetX:i,targetY:s,sourcePosition:r=mv.Bottom,targetPosition:n=mv.Top,label:o,labelStyle:a,labelShowBg:l,labelBgStyle:c,labelBgPadding:h,labelBgBorderRadius:d,style:u,markerEnd:f,markerStart:p,pathOptions:m,interactionWidth:_})=>{const[g,v,y]=jv({sourceX:e,sourceY:t,sourcePosition:r,targetX:i,targetY:s,targetPosition:n,curvature:null==m?void 0:m.curvature});return N.createElement(tv,{path:g,labelX:v,labelY:y,label:o,labelStyle:a,labelShowBg:l,labelBgStyle:c,labelBgPadding:h,labelBgBorderRadius:d,style:u,markerEnd:f,markerStart:p,interactionWidth:_})});Dv.displayName="BezierEdge";const Rv=h.createContext(null),Pv=Rv.Provider;Rv.Consumer;const Lv=({source:e,sourceHandle:t,target:i,targetHandle:s})=>`reactflow__edge-${e}${t||""}-${i}${s||""}`,Tv=(e,t)=>{if(void 0===e)return"";if("string"==typeof e)return e;return`${t?`${t}__`:""}${Object.keys(e).sort().map(t=>`${t}=${e[t]}`).join("&")}`},Iv=({x:e,y:t},[i,s,r],n,[o,a])=>{const l={x:(e-i)/r,y:(t-s)/r};return n?{x:o*Math.round(l.x/o),y:a*Math.round(l.y/a)}:l},Bv=({x:e,y:t},[i,s,r])=>({x:e*r+i,y:t*r+s}),Ov=(e,t=[0,0])=>{if(!e)return{x:0,y:0,positionAbsolute:{x:0,y:0}};const i=(e.width??0)*t[0],s=(e.height??0)*t[1],r={x:e.position.x-i,y:e.position.y-s};return{...r,positionAbsolute:e.positionAbsolute?{x:e.positionAbsolute.x-i,y:e.positionAbsolute.y-s}:r}},Av=(e,t=[0,0])=>{if(0===e.length)return{x:0,y:0,width:0,height:0};const i=e.reduce((e,i)=>{const{x:s,y:r}=Ov(i,t).positionAbsolute;return Fg(e,Kg({x:s,y:r,width:i.width||0,height:i.height||0}))},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return Ug(i)},zv=(e,t,[i,s,r]=[0,0,1],n=!1,o=!1,a=[0,0])=>{const l={x:(t.x-i)/r,y:(t.y-s)/r,width:t.width/r,height:t.height/r},c=[];return e.forEach(e=>{const{width:t,height:i,selectable:s=!0,hidden:r=!1}=e;if(o&&!s||r)return!1;const{positionAbsolute:h}=Ov(e,a),d={x:h.x,y:h.y,width:t||0,height:i||0},u=qg(l,d);(void 0===t||void 0===i||null===t||null===i||n&&u>0||u>=(t||0)*(i||0)||e.dragging)&&c.push(e)}),c},$v=(e,t)=>{const i=e.map(e=>e.id);return t.filter(e=>i.includes(e.source)||i.includes(e.target))},Hv=(e,t,i,s,r,n=.1)=>{const o=t/(e.width*(1+n)),a=i/(e.height*(1+n)),l=Math.min(o,a),c=Ag(l,s,r);return{x:t/2-(e.x+e.width/2)*c,y:i/2-(e.y+e.height/2)*c,zoom:c}},Wv=(e,t=0)=>e.transition().duration(t);function Fv(e,t,i,s){return(t[i]||[]).reduce((t,r)=>{var n,o;return`${e.id}-${r.id}-${i}`!==s&&t.push({id:r.id||null,type:i,nodeId:e.id,x:((null==(n=e.positionAbsolute)?void 0:n.x)??0)+r.x+r.width/2,y:((null==(o=e.positionAbsolute)?void 0:o.y)??0)+r.y+r.height/2}),t},[])}const Kv={source:null,target:null,sourceHandle:null,targetHandle:null},Uv=()=>({handleDomNode:null,isValid:!1,connection:Kv,endHandle:null});function Vv(e,t,i,s,r,n,o){const a="target"===r,l=o.querySelector(`.react-flow__handle[data-id="${null==e?void 0:e.nodeId}-${null==e?void 0:e.id}-${null==e?void 0:e.type}"]`),c={...Uv(),handleDomNode:l};if(l){const e=qv(void 0,l),r=l.getAttribute("data-nodeid"),o=l.getAttribute("data-handleid"),h=l.classList.contains("connectable"),d=l.classList.contains("connectableend"),u={source:a?r:i,sourceHandle:a?o:s,target:a?i:r,targetHandle:a?s:o};c.connection=u;h&&d&&(t===nv.Strict?a&&"source"===e||!a&&"target"===e:r!==i||o!==s)&&(c.endHandle={nodeId:r,handleId:o,type:e},c.isValid=n(u))}return c}function qv(e,t){return e||((null==t?void 0:t.classList.contains("target"))?"target":(null==t?void 0:t.classList.contains("source"))?"source":null)}function Yv(e){null==e||e.classList.remove("valid","connecting","react-flow__handle-valid","react-flow__handle-connecting")}function Xv(e,t){let i=null;return t?i="valid":e&&!t&&(i="invalid"),i}function Gv({event:e,handleId:t,nodeId:i,onConnect:s,isTarget:r,getState:n,setState:o,isValidConnection:a,edgeUpdaterType:l,onReconnectEnd:c}){const h=Wg(e.target),{connectionMode:d,domNode:u,autoPanOnConnect:f,connectionRadius:p,onConnectStart:m,panBy:_,getNodes:g,cancelConnection:v}=n();let y,x=0;const{x:b,y:w}=Qg(e),S=null==h?void 0:h.elementFromPoint(b,w),C=qv(l,S),k=null==u?void 0:u.getBoundingClientRect();if(!k||!C)return;let E,N=Qg(e,k),M=!1,j=null,D=!1,R=null;const P=function({nodes:e,nodeId:t,handleId:i,handleType:s}){return e.reduce((e,r)=>{if(r[Xg]){const{handleBounds:n}=r[Xg];let o=[],a=[];n&&(o=Fv(r,n,"source",`${t}-${i}-${s}`),a=Fv(r,n,"target",`${t}-${i}-${s}`)),e.push(...o,...a)}return e},[])}({nodes:g(),nodeId:i,handleId:t,handleType:C}),L=()=>{if(!f)return;const[e,t]=Hg(N,k);_({x:e,y:t}),x=requestAnimationFrame(L)};function T(e){const{transform:s}=n();N=Qg(e,k);const{handle:l,validHandleResult:c}=function(e,t,i,s,r,n){const{x:o,y:a}=Qg(e),l=t.elementsFromPoint(o,a).find(e=>e.classList.contains("react-flow__handle"));if(l){const e=l.getAttribute("data-nodeid");if(e){const t=qv(void 0,l),s=l.getAttribute("data-handleid"),o=n({nodeId:e,id:s,type:t});if(o){const n=r.find(i=>i.nodeId===e&&i.type===t&&i.id===s);return{handle:{id:s,type:t,nodeId:e,x:(null==n?void 0:n.x)||i.x,y:(null==n?void 0:n.y)||i.y},validHandleResult:o}}}}let c=[],h=1/0;if(r.forEach(e=>{const t=Math.sqrt((e.x-i.x)**2+(e.y-i.y)**2);if(t<=s){const i=n(e);t<=h&&(t<h?c=[{handle:e,validHandleResult:i}]:t===h&&c.push({handle:e,validHandleResult:i}),h=t)}}),!c.length)return{handle:null,validHandleResult:Uv()};if(1===c.length)return c[0];const d=c.some(({validHandleResult:e})=>e.isValid),u=c.some(({handle:e})=>"target"===e.type);return c.find(({handle:e,validHandleResult:t})=>u?"target"===e.type:!d||t.isValid)||c[0]}(e,h,Iv(N,s,!1,[1,1]),p,P,e=>Vv(e,d,i,t,r?"target":"source",a,h));if(y=l,M||(L(),M=!0),R=c.handleDomNode,j=c.connection,D=c.isValid,o({connectionPosition:y&&D?Bv({x:y.x,y:y.y},s):N,connectionStatus:Xv(!!y,D),connectionEndHandle:c.endHandle}),!y&&!D&&!R)return Yv(E);j.source!==j.target&&R&&(Yv(E),E=R,R.classList.add("connecting","react-flow__handle-connecting"),R.classList.toggle("valid",D),R.classList.toggle("react-flow__handle-valid",D))}function I(e){var t,i;(y||R)&&j&&D&&(null==s||s(j)),null==(i=(t=n()).onConnectEnd)||i.call(t,e),l&&(null==c||c(e)),Yv(E),v(),cancelAnimationFrame(x),M=!1,D=!1,j=null,R=null,h.removeEventListener("mousemove",T),h.removeEventListener("mouseup",I),h.removeEventListener("touchmove",T),h.removeEventListener("touchend",I)}o({connectionPosition:N,connectionStatus:null,connectionNodeId:i,connectionHandleId:t,connectionHandleType:C,connectionStartHandle:{nodeId:i,handleId:t,type:C},connectionEndHandle:null}),null==m||m(e,{nodeId:i,handleId:t,handleType:C}),h.addEventListener("mousemove",T),h.addEventListener("mouseup",I),h.addEventListener("touchmove",T),h.addEventListener("touchend",I)}const Zv=()=>!0,Jv=e=>({connectionStartHandle:e.connectionStartHandle,connectOnClick:e.connectOnClick,noPanClassName:e.noPanClassName}),Qv=h.forwardRef(({type:e="source",position:t=mv.Top,isValidConnection:i,isConnectable:s=!0,isConnectableStart:r=!0,isConnectableEnd:n=!0,id:o,onConnect:a,children:l,className:c,onMouseDown:d,onTouchStart:u,...f},p)=>{var m,_;const g=o||null,v="target"===e,y=Pg(),x=h.useContext(Rv),{connectOnClick:b,noPanClassName:w}=Rg(Jv,Of),{connecting:S,clickConnecting:C}=Rg(((e,t,i)=>s=>{const{connectionStartHandle:r,connectionEndHandle:n,connectionClickStartHandle:o}=s;return{connecting:(null==r?void 0:r.nodeId)===e&&(null==r?void 0:r.handleId)===t&&(null==r?void 0:r.type)===i||(null==n?void 0:n.nodeId)===e&&(null==n?void 0:n.handleId)===t&&(null==n?void 0:n.type)===i,clickConnecting:(null==o?void 0:o.nodeId)===e&&(null==o?void 0:o.handleId)===t&&(null==o?void 0:o.type)===i}})(x,g,e),Of);x||null==(_=(m=y.getState()).onError)||_.call(m,"010",Ng());const k=e=>{const{defaultEdgeOptions:t,onConnect:i,hasDefaultEdges:s}=y.getState(),r={...t,...e};if(s){const{edges:e,setEdges:t}=y.getState();t(((e,t)=>{if(!e.source||!e.target)return t;let i;var s;return i="id"in(s=e)&&"source"in s&&"target"in s?{...e}:{...e,id:Lv(e)},((e,t)=>t.some(t=>!(t.source!==e.source||t.target!==e.target||t.sourceHandle!==e.sourceHandle&&(t.sourceHandle||e.sourceHandle)||t.targetHandle!==e.targetHandle&&(t.targetHandle||e.targetHandle))))(i,t)?t:t.concat(i)})(r,e))}null==i||i(r),null==a||a(r)},E=e=>{if(!x)return;const t=Jg(e);r&&(t&&0===e.button||!t)&&Gv({event:e,handleId:g,nodeId:x,onConnect:k,isTarget:v,getState:y.getState,setState:y.setState,isValidConnection:i||y.getState().isValidConnection||Zv}),t?null==d||d(e):null==u||u(e)};return N.createElement("div",{"data-handleid":g,"data-nodeid":x,"data-handlepos":t,"data-id":`${x}-${g}-${e}`,className:vf(["react-flow__handle",`react-flow__handle-${t}`,"nodrag",w,c,{source:!v,target:v,connectable:s,connectablestart:r,connectableend:n,connecting:C,connectionindicator:s&&(r&&!S||n&&S)}]),onMouseDown:E,onTouchStart:E,onClick:b?t=>{const{onClickConnectStart:s,onClickConnectEnd:n,connectionClickStartHandle:o,connectionMode:a,isValidConnection:l}=y.getState();if(!x||!o&&!r)return;if(!o)return null==s||s(t,{nodeId:x,handleId:g,handleType:e}),void y.setState({connectionClickStartHandle:{nodeId:x,type:e,handleId:g}});const c=Wg(t.target),h=i||l||Zv,{connection:d,isValid:u}=Vv({nodeId:x,id:g,type:e},a,o.nodeId,o.handleId||null,o.type,h,c);u&&k(d),null==n||n(t),y.setState({connectionClickStartHandle:null})}:void 0,ref:p,...f},l)});Qv.displayName="Handle";var ey=h.memo(Qv);const ty=({data:e,isConnectable:t,targetPosition:i=mv.Top,sourcePosition:s=mv.Bottom})=>N.createElement(N.Fragment,null,N.createElement(ey,{type:"target",position:i,isConnectable:t}),null==e?void 0:e.label,N.createElement(ey,{type:"source",position:s,isConnectable:t}));ty.displayName="DefaultNode";var iy=h.memo(ty);const sy=({data:e,isConnectable:t,sourcePosition:i=mv.Bottom})=>N.createElement(N.Fragment,null,null==e?void 0:e.label,N.createElement(ey,{type:"source",position:i,isConnectable:t}));sy.displayName="InputNode";var ry=h.memo(sy);const ny=({data:e,isConnectable:t,targetPosition:i=mv.Top})=>N.createElement(N.Fragment,null,N.createElement(ey,{type:"target",position:i,isConnectable:t}),null==e?void 0:e.label);ny.displayName="OutputNode";var oy=h.memo(ny);const ay=()=>null;ay.displayName="GroupNode";const ly=e=>({selectedNodes:e.getNodes().filter(e=>e.selected),selectedEdges:e.edges.filter(e=>e.selected).map(e=>({...e}))}),cy=e=>e.id;function hy(e,t){return Of(e.selectedNodes.map(cy),t.selectedNodes.map(cy))&&Of(e.selectedEdges.map(cy),t.selectedEdges.map(cy))}const dy=h.memo(({onSelectionChange:e})=>{const t=Pg(),{selectedNodes:i,selectedEdges:s}=Rg(ly,hy);return h.useEffect(()=>{const r={nodes:i,edges:s};null==e||e(r),t.getState().onSelectionChange.forEach(e=>e(r))},[i,s,e]),null});dy.displayName="SelectionListener";const uy=e=>!!e.onSelectionChange;function fy({onSelectionChange:e}){const t=Rg(uy);return e||t?N.createElement(dy,{onSelectionChange:e}):null}const py=e=>({setNodes:e.setNodes,setEdges:e.setEdges,setDefaultNodesAndEdges:e.setDefaultNodesAndEdges,setMinZoom:e.setMinZoom,setMaxZoom:e.setMaxZoom,setTranslateExtent:e.setTranslateExtent,setNodeExtent:e.setNodeExtent,reset:e.reset});function my(e,t){h.useEffect(()=>{void 0!==e&&t(e)},[e])}function _y(e,t,i){h.useEffect(()=>{void 0!==t&&i({[e]:t})},[t])}const gy=({nodes:e,edges:t,defaultNodes:i,defaultEdges:s,onConnect:r,onConnectStart:n,onConnectEnd:o,onClickConnectStart:a,onClickConnectEnd:l,nodesDraggable:c,nodesConnectable:d,nodesFocusable:u,edgesFocusable:f,edgesUpdatable:p,elevateNodesOnSelect:m,minZoom:_,maxZoom:g,nodeExtent:v,onNodesChange:y,onEdgesChange:x,elementsSelectable:b,connectionMode:w,snapGrid:S,snapToGrid:C,translateExtent:k,connectOnClick:E,defaultEdgeOptions:N,fitView:M,fitViewOptions:j,onNodesDelete:D,onEdgesDelete:R,onNodeDrag:P,onNodeDragStart:L,onNodeDragStop:T,onSelectionDrag:I,onSelectionDragStart:B,onSelectionDragStop:O,noPanClassName:A,nodeOrigin:z,rfId:$,autoPanOnConnect:H,autoPanOnNodeDrag:W,onError:F,connectionRadius:K,isValidConnection:U,nodeDragThreshold:V})=>{const{setNodes:q,setEdges:Y,setDefaultNodesAndEdges:X,setMinZoom:G,setMaxZoom:Z,setTranslateExtent:J,setNodeExtent:Q,reset:ee}=Rg(py,Of),te=Pg();return h.useEffect(()=>{const e=null==s?void 0:s.map(e=>({...e,...N}));return X(i,e),()=>{ee()}},[]),_y("defaultEdgeOptions",N,te.setState),_y("connectionMode",w,te.setState),_y("onConnect",r,te.setState),_y("onConnectStart",n,te.setState),_y("onConnectEnd",o,te.setState),_y("onClickConnectStart",a,te.setState),_y("onClickConnectEnd",l,te.setState),_y("nodesDraggable",c,te.setState),_y("nodesConnectable",d,te.setState),_y("nodesFocusable",u,te.setState),_y("edgesFocusable",f,te.setState),_y("edgesUpdatable",p,te.setState),_y("elementsSelectable",b,te.setState),_y("elevateNodesOnSelect",m,te.setState),_y("snapToGrid",C,te.setState),_y("snapGrid",S,te.setState),_y("onNodesChange",y,te.setState),_y("onEdgesChange",x,te.setState),_y("connectOnClick",E,te.setState),_y("fitViewOnInit",M,te.setState),_y("fitViewOnInitOptions",j,te.setState),_y("onNodesDelete",D,te.setState),_y("onEdgesDelete",R,te.setState),_y("onNodeDrag",P,te.setState),_y("onNodeDragStart",L,te.setState),_y("onNodeDragStop",T,te.setState),_y("onSelectionDrag",I,te.setState),_y("onSelectionDragStart",B,te.setState),_y("onSelectionDragStop",O,te.setState),_y("noPanClassName",A,te.setState),_y("nodeOrigin",z,te.setState),_y("rfId",$,te.setState),_y("autoPanOnConnect",H,te.setState),_y("autoPanOnNodeDrag",W,te.setState),_y("onError",F,te.setState),_y("connectionRadius",K,te.setState),_y("isValidConnection",U,te.setState),_y("nodeDragThreshold",V,te.setState),my(e,q),my(t,Y),my(_,G),my(g,Z),my(k,J),my(v,Q),null},vy={display:"none"},yy={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},xy="react-flow__node-desc",by="react-flow__edge-desc",wy=e=>e.ariaLiveMessage;function Sy({rfId:e}){const t=Rg(wy);return N.createElement("div",{id:`react-flow__aria-live-${e}`,"aria-live":"assertive","aria-atomic":"true",style:yy},t)}function Cy({rfId:e,disableKeyboardA11y:t}){return N.createElement(N.Fragment,null,N.createElement("div",{id:`${xy}-${e}`,style:vy},"Press enter or space to select a node.",!t&&"You can then use the arrow keys to move the node around."," Press delete to remove it and escape to cancel."," "),N.createElement("div",{id:`${by}-${e}`,style:vy},"Press enter or space to select an edge. You can then press delete to remove it or escape to cancel."),!t&&N.createElement(Sy,{rfId:e}))}var ky=(e=null,t={actInsideInputWithModifier:!0})=>{const[i,s]=h.useState(!1),r=h.useRef(!1),n=h.useRef(new Set([])),[o,a]=h.useMemo(()=>{if(null!==e){const t=(Array.isArray(e)?e:[e]).filter(e=>"string"==typeof e).map(e=>e.split("+")),i=t.reduce((e,t)=>e.concat(...t),[]);return[t,i]}return[[],[]]},[e]);return h.useEffect(()=>{const i="undefined"!=typeof document?document:null,l=(null==t?void 0:t.target)||i;if(null!==e){const e=e=>{r.current=e.ctrlKey||e.metaKey||e.shiftKey;if((!r.current||r.current&&!t.actInsideInputWithModifier)&&Zg(e))return!1;const i=Ny(e.code,a);n.current.add(e[i]),Ey(o,n.current,!1)&&(e.preventDefault(),s(!0))},i=e=>{if((!r.current||r.current&&!t.actInsideInputWithModifier)&&Zg(e))return!1;const i=Ny(e.code,a);Ey(o,n.current,!0)?(s(!1),n.current.clear()):n.current.delete(e[i]),"Meta"===e.key&&n.current.clear(),r.current=!1},c=()=>{n.current.clear(),s(!1)};return null==l||l.addEventListener("keydown",e),null==l||l.addEventListener("keyup",i),window.addEventListener("blur",c),()=>{null==l||l.removeEventListener("keydown",e),null==l||l.removeEventListener("keyup",i),window.removeEventListener("blur",c)}}},[e,s]),i};function Ey(e,t,i){return e.filter(e=>i||e.length===t.size).some(e=>e.every(e=>t.has(e)))}function Ny(e,t){return t.includes(e)?"code":"key"}function My(e,t,i,s){var r,n;const o=e.parentNode||e.parentId;if(!o)return i;const a=t.get(o),l=Ov(a,s);return My(a,t,{x:(i.x??0)+l.x,y:(i.y??0)+l.y,z:((null==(r=a[Xg])?void 0:r.z)??0)>(i.z??0)?(null==(n=a[Xg])?void 0:n.z)??0:i.z??0},s)}function jy(e,t,i){e.forEach(s=>{var r;const n=s.parentNode||s.parentId;if(n&&!e.has(n))throw new Error(`Parent node ${n} not found`);if(n||(null==i?void 0:i[s.id])){const{x:n,y:o,z:a}=My(s,e,{...s.position,z:(null==(r=s[Xg])?void 0:r.z)??0},t);s.positionAbsolute={x:n,y:o},s[Xg].z=a,(null==i?void 0:i[s.id])&&(s[Xg].isParent=!0)}})}function Dy(e,t,i,s){const r=new Map,n={},o=s?1e3:0;return e.forEach(e=>{var i;const s=(Yg(e.zIndex)?e.zIndex:0)+(e.selected?o:0),a=t.get(e.id),l={...e,positionAbsolute:{x:e.position.x,y:e.position.y}},c=e.parentNode||e.parentId;c&&(n[c]=!0);const h=(null==a?void 0:a.type)&&(null==a?void 0:a.type)!==e.type;Object.defineProperty(l,Xg,{enumerable:!1,value:{handleBounds:h||null==(i=null==a?void 0:a[Xg])?void 0:i.handleBounds,z:s}}),r.set(e.id,l)}),jy(r,i,n),r}function Ry(e,t={}){const{getNodes:i,width:s,height:r,minZoom:n,maxZoom:o,d3Zoom:a,d3Selection:l,fitViewOnInitDone:c,fitViewOnInit:h,nodeOrigin:d}=e(),u=t.initial&&!c&&h;if(a&&l&&(u||!t.initial)){const e=i().filter(e=>{var i;const s=t.includeHiddenNodes?e.width&&e.height:!e.hidden;return(null==(i=t.nodes)?void 0:i.length)?s&&t.nodes.some(t=>t.id===e.id):s}),c=e.every(e=>e.width&&e.height);if(e.length>0&&c){const i=Av(e,d),{x:c,y:h,zoom:u}=Hv(i,s,r,t.minZoom??n,t.maxZoom??o,t.padding??.1),f=hg.translate(c,h).scale(u);return"number"==typeof t.duration&&t.duration>0?a.transform(Wv(l,t.duration),f):a.transform(l,f),!0}}return!1}function Py(e,t){return e.forEach(e=>{const i=t.get(e.id);i&&t.set(i.id,{...i,[Xg]:i[Xg],selected:e.selected})}),new Map(t)}function Ly(e,t){return t.map(t=>{const i=e.find(e=>e.id===t.id);return i&&(t.selected=i.selected),t})}function Ty({changedNodes:e,changedEdges:t,get:i,set:s}){const{nodeInternals:r,edges:n,onNodesChange:o,onEdgesChange:a,hasDefaultNodes:l,hasDefaultEdges:c}=i();(null==e?void 0:e.length)&&(l&&s({nodeInternals:Py(e,r)}),null==o||o(e)),(null==t?void 0:t.length)&&(c&&s({edges:Ly(t,n)}),null==a||a(t))}const Iy=()=>{},By={zoomIn:Iy,zoomOut:Iy,zoomTo:Iy,getZoom:()=>1,setViewport:Iy,getViewport:()=>({x:0,y:0,zoom:1}),fitView:()=>!1,setCenter:Iy,fitBounds:Iy,project:e=>e,screenToFlowPosition:e=>e,flowToScreenPosition:e=>e,viewportInitialized:!1},Oy=e=>({d3Zoom:e.d3Zoom,d3Selection:e.d3Selection});function Ay(){const e=(()=>{const e=Pg(),{d3Zoom:t,d3Selection:i}=Rg(Oy,Of);return h.useMemo(()=>i&&t?{zoomIn:e=>t.scaleBy(Wv(i,null==e?void 0:e.duration),1.2),zoomOut:e=>t.scaleBy(Wv(i,null==e?void 0:e.duration),1/1.2),zoomTo:(e,s)=>t.scaleTo(Wv(i,null==s?void 0:s.duration),e),getZoom:()=>e.getState().transform[2],setViewport:(s,r)=>{const[n,o,a]=e.getState().transform,l=hg.translate(s.x??n,s.y??o).scale(s.zoom??a);t.transform(Wv(i,null==r?void 0:r.duration),l)},getViewport:()=>{const[t,i,s]=e.getState().transform;return{x:t,y:i,zoom:s}},fitView:t=>Ry(e.getState,t),setCenter:(s,r,n)=>{const{width:o,height:a,maxZoom:l}=e.getState(),c=void 0!==(null==n?void 0:n.zoom)?n.zoom:l,h=o/2-s*c,d=a/2-r*c,u=hg.translate(h,d).scale(c);t.transform(Wv(i,null==n?void 0:n.duration),u)},fitBounds:(s,r)=>{const{width:n,height:o,minZoom:a,maxZoom:l}=e.getState(),{x:c,y:h,zoom:d}=Hv(s,n,o,a,l,(null==r?void 0:r.padding)??.1),u=hg.translate(c,h).scale(d);t.transform(Wv(i,null==r?void 0:r.duration),u)},project:t=>{const{transform:i,snapToGrid:s,snapGrid:r}=e.getState();return console.warn("[DEPRECATED] `project` is deprecated. Instead use `screenToFlowPosition`. There is no need to subtract the react flow bounds anymore! https://reactflow.dev/api-reference/types/react-flow-instance#screen-to-flow-position"),Iv(t,i,s,r)},screenToFlowPosition:t=>{const{transform:i,snapToGrid:s,snapGrid:r,domNode:n}=e.getState();if(!n)return t;const{x:o,y:a}=n.getBoundingClientRect(),l={x:t.x-o,y:t.y-a};return Iv(l,i,s,r)},flowToScreenPosition:t=>{const{transform:i,domNode:s}=e.getState();if(!s)return t;const{x:r,y:n}=s.getBoundingClientRect(),o=Bv(t,i);return{x:o.x+r,y:o.y+n}},viewportInitialized:!0}:By,[t,i])})(),t=Pg(),i=h.useCallback(()=>t.getState().getNodes().map(e=>({...e})),[]),s=h.useCallback(e=>t.getState().nodeInternals.get(e),[]),r=h.useCallback(()=>{const{edges:e=[]}=t.getState();return e.map(e=>({...e}))},[]),n=h.useCallback(e=>{const{edges:i=[]}=t.getState();return i.find(t=>t.id===e)},[]),o=h.useCallback(e=>{const{getNodes:i,setNodes:s,hasDefaultNodes:r,onNodesChange:n}=t.getState(),o=i(),a="function"==typeof e?e(o):e;if(r)s(a);else if(n){n(0===a.length?o.map(e=>({type:"remove",id:e.id})):a.map(e=>({item:e,type:"reset"})))}},[]),a=h.useCallback(e=>{const{edges:i=[],setEdges:s,hasDefaultEdges:r,onEdgesChange:n}=t.getState(),o="function"==typeof e?e(i):e;if(r)s(o);else if(n){n(0===o.length?i.map(e=>({type:"remove",id:e.id})):o.map(e=>({item:e,type:"reset"})))}},[]),l=h.useCallback(e=>{const i=Array.isArray(e)?e:[e],{getNodes:s,setNodes:r,hasDefaultNodes:n,onNodesChange:o}=t.getState();if(n){r([...s(),...i])}else if(o){o(i.map(e=>({item:e,type:"add"})))}},[]),c=h.useCallback(e=>{const i=Array.isArray(e)?e:[e],{edges:s=[],setEdges:r,hasDefaultEdges:n,onEdgesChange:o}=t.getState();if(n)r([...s,...i]);else if(o){o(i.map(e=>({item:e,type:"add"})))}},[]),d=h.useCallback(()=>{const{getNodes:e,edges:i=[],transform:s}=t.getState(),[r,n,o]=s;return{nodes:e().map(e=>({...e})),edges:i.map(e=>({...e})),viewport:{x:r,y:n,zoom:o}}},[]),u=h.useCallback(({nodes:e,edges:i})=>{const{nodeInternals:s,getNodes:r,edges:n,hasDefaultNodes:o,hasDefaultEdges:a,onNodesDelete:l,onEdgesDelete:c,onNodesChange:h,onEdgesChange:d}=t.getState(),u=(e||[]).map(e=>e.id),f=(i||[]).map(e=>e.id),p=r().reduce((e,t)=>{const i=t.parentNode||t.parentId,s=!u.includes(t.id)&&i&&e.find(e=>e.id===i);return("boolean"!=typeof t.deletable||t.deletable)&&(u.includes(t.id)||s)&&e.push(t),e},[]),m=n.filter(e=>"boolean"!=typeof e.deletable||e.deletable),_=m.filter(e=>f.includes(e.id));if(p||_){const e=$v(p,m),i=[..._,...e],r=i.reduce((e,t)=>(e.includes(t.id)||e.push(t.id),e),[]);if((a||o)&&(a&&t.setState({edges:n.filter(e=>!r.includes(e.id))}),o&&(p.forEach(e=>{s.delete(e.id)}),t.setState({nodeInternals:new Map(s)}))),r.length>0&&(null==c||c(i),d&&d(r.map(e=>({id:e,type:"remove"})))),p.length>0&&(null==l||l(p),h)){const e=p.map(e=>({id:e.id,type:"remove"}));h(e)}}},[]),f=h.useCallback(e=>{const i=Yg((s=e).width)&&Yg(s.height)&&Yg(s.x)&&Yg(s.y);var s;const r=i?null:t.getState().nodeInternals.get(e.id);if(!i&&!r)return[null,null,i];return[i?e:Vg(r),r,i]},[]),p=h.useCallback((e,i=!0,s)=>{const[r,n,o]=f(e);return r?(s||t.getState().getNodes()).filter(e=>{if(!(o||e.id!==n.id&&e.positionAbsolute))return!1;const t=Vg(e),s=qg(t,r);return i&&s>0||s>=r.width*r.height}):[]},[]),m=h.useCallback((e,t,i=!0)=>{const[s]=f(e);if(!s)return!1;const r=qg(s,t);return i&&r>0||r>=s.width*s.height},[]);return h.useMemo(()=>({...e,getNodes:i,getNode:s,getEdges:r,getEdge:n,setNodes:o,setEdges:a,addNodes:l,addEdges:c,toObject:d,deleteElements:u,getIntersectingNodes:p,isNodeIntersecting:m}),[e,i,s,r,n,o,a,l,c,d,u,p,m])}const zy={actInsideInputWithModifier:!1};const $y={position:"absolute",width:"100%",height:"100%",top:0,left:0},Hy=e=>({x:e.x,y:e.y,zoom:e.k}),Wy=(e,t)=>e.target.closest(`.${t}`),Fy=(e,t)=>2===t&&Array.isArray(e)&&e.includes(2),Ky=e=>{const t=e.ctrlKey&&ev()?10:1;return-e.deltaY*(1===e.deltaMode?.05:e.deltaMode?1:.002)*t},Uy=e=>({d3Zoom:e.d3Zoom,d3Selection:e.d3Selection,d3ZoomHandler:e.d3ZoomHandler,userSelectionActive:e.userSelectionActive}),Vy=({onMove:e,onMoveStart:t,onMoveEnd:i,onPaneContextMenu:s,zoomOnScroll:r=!0,zoomOnPinch:n=!0,panOnScroll:o=!1,panOnScrollSpeed:a=.5,panOnScrollMode:l=av.Free,zoomOnDoubleClick:c=!0,elementsSelectable:d,panOnDrag:u=!0,defaultViewport:f,translateExtent:p,minZoom:m,maxZoom:_,zoomActivationKeyCode:g,preventScrolling:v=!0,children:y,noWheelClassName:x,noPanClassName:b})=>{const w=h.useRef(),S=Pg(),C=h.useRef(!1),k=h.useRef(!1),E=h.useRef(null),M=h.useRef({x:0,y:0,zoom:0}),{d3Zoom:j,d3Selection:D,d3ZoomHandler:R,userSelectionActive:P}=Rg(Uy,Of),L=ky(g),T=h.useRef(0),I=h.useRef(!1),B=h.useRef();return function(e){const t=Pg();h.useEffect(()=>{let i;const s=()=>{var i,s;if(!e.current)return;const r=Og(e.current);0!==r.height&&0!==r.width||null==(s=(i=t.getState()).onError)||s.call(i,"004",Sg()),t.setState({width:r.width||500,height:r.height||500})};return s(),window.addEventListener("resize",s),e.current&&(i=new ResizeObserver(()=>s()),i.observe(e.current)),()=>{window.removeEventListener("resize",s),i&&e.current&&i.unobserve(e.current)}},[])}(E),h.useEffect(()=>{if(E.current){const e=E.current.getBoundingClientRect(),t=yg().scaleExtent([m,_]).translateExtent(p),i=tm(E.current).call(t),s=hg.translate(f.x,f.y).scale(Ag(f.zoom,m,_)),r=[[0,0],[e.width,e.height]],n=t.constrain()(s,r,p);t.transform(i,n),t.wheelDelta(Ky),S.setState({d3Zoom:t,d3Selection:i,d3ZoomHandler:i.on("wheel.zoom"),transform:[n.x,n.y,n.k],domNode:E.current.closest(".react-flow")})}},[]),h.useEffect(()=>{D&&j&&(!o||L||P?void 0!==R&&D.on("wheel.zoom",function(e,t){if(!v&&"wheel"===e.type&&!e.ctrlKey||Wy(e,x))return null;e.preventDefault(),R.call(this,e,t)},{passive:!1}):D.on("wheel.zoom",s=>{if(Wy(s,x))return!1;s.preventDefault(),s.stopImmediatePropagation();const r=D.property("__zoom").k||1;if(s.ctrlKey&&n){const e=im(s),t=Ky(s),i=r*Math.pow(2,t);return void j.scaleTo(D,i,e,s)}const o=1===s.deltaMode?20:1;let c=l===av.Vertical?0:s.deltaX*o,h=l===av.Horizontal?0:s.deltaY*o;!ev()&&s.shiftKey&&l!==av.Vertical&&(c=s.deltaY*o,h=0),j.translateBy(D,-c/r*a,-h/r*a,{internal:!0});const d=Hy(D.property("__zoom")),{onViewportChangeStart:u,onViewportChange:f,onViewportChangeEnd:p}=S.getState();clearTimeout(B.current),I.current||(I.current=!0,null==t||t(s,d),null==u||u(d)),I.current&&(null==e||e(s,d),null==f||f(d),B.current=setTimeout(()=>{null==i||i(s,d),null==p||p(d),I.current=!1},150))},{passive:!1}))},[P,o,l,D,j,R,L,n,v,x,t,e,i]),h.useEffect(()=>{j&&j.on("start",e=>{var i,s;if(!e.sourceEvent||e.sourceEvent.internal)return null;T.current=null==(i=e.sourceEvent)?void 0:i.button;const{onViewportChangeStart:r}=S.getState(),n=Hy(e.transform);C.current=!0,M.current=n,"mousedown"===(null==(s=e.sourceEvent)?void 0:s.type)&&S.setState({paneDragging:!0}),null==r||r(n),null==t||t(e.sourceEvent,n)})},[j,t]),h.useEffect(()=>{j&&(P&&!C.current?j.on("zoom",null):P||j.on("zoom",t=>{var i;const{onViewportChange:r}=S.getState();if(S.setState({transform:[t.transform.x,t.transform.y,t.transform.k]}),k.current=!(!s||!Fy(u,T.current??0)),(e||r)&&!(null==(i=t.sourceEvent)?void 0:i.internal)){const i=Hy(t.transform);null==r||r(i),null==e||e(t.sourceEvent,i)}}))},[P,j,e,u,s]),h.useEffect(()=>{j&&j.on("end",e=>{if(!e.sourceEvent||e.sourceEvent.internal)return null;const{onViewportChangeEnd:t}=S.getState();if(C.current=!1,S.setState({paneDragging:!1}),s&&Fy(u,T.current??0)&&!k.current&&s(e.sourceEvent),k.current=!1,(i||t)&&(r=M.current,n=e.transform,r.x!==n.x||r.y!==n.y||r.zoom!==n.k)){const s=Hy(e.transform);M.current=s,clearTimeout(w.current),w.current=setTimeout(()=>{null==t||t(s),null==i||i(e.sourceEvent,s)},o?150:0)}var r,n})},[j,o,u,i,s]),h.useEffect(()=>{j&&j.filter(e=>{const t=L||r,i=n&&e.ctrlKey;if((!0===u||Array.isArray(u)&&u.includes(1))&&1===e.button&&"mousedown"===e.type&&(Wy(e,"react-flow__node")||Wy(e,"react-flow__edge")))return!0;if(!(u||t||o||c||n))return!1;if(P)return!1;if(!c&&"dblclick"===e.type)return!1;if(Wy(e,x)&&"wheel"===e.type)return!1;if(Wy(e,b)&&("wheel"!==e.type||o&&"wheel"===e.type&&!L))return!1;if(!n&&e.ctrlKey&&"wheel"===e.type)return!1;if(!t&&!o&&!i&&"wheel"===e.type)return!1;if(!u&&("mousedown"===e.type||"touchstart"===e.type))return!1;if(Array.isArray(u)&&!u.includes(e.button)&&"mousedown"===e.type)return!1;const s=Array.isArray(u)&&u.includes(e.button)||!e.button||e.button<=1;return(!e.ctrlKey||"wheel"===e.type)&&s})},[P,j,r,n,o,c,u,d,L]),N.createElement("div",{className:"react-flow__renderer",ref:E,style:$y},y)},qy=e=>({userSelectionActive:e.userSelectionActive,userSelectionRect:e.userSelectionRect});function Yy(){const{userSelectionActive:e,userSelectionRect:t}=Rg(qy,Of);return e&&t?N.createElement("div",{className:"react-flow__selection react-flow__container",style:{width:t.width,height:t.height,transform:`translate(${t.x}px, ${t.y}px)`}}):null}function Xy(e,t){const i=t.parentNode||t.parentId,s=e.find(e=>e.id===i);if(s){const e=t.position.x+t.width-s.width,i=t.position.y+t.height-s.height;if(e>0||i>0||t.position.x<0||t.position.y<0){if(s.style={...s.style},s.style.width=s.style.width??s.width,s.style.height=s.style.height??s.height,e>0&&(s.style.width+=e),i>0&&(s.style.height+=i),t.position.x<0){const e=Math.abs(t.position.x);s.position.x=s.position.x-e,s.style.width+=e,t.position.x=0}if(t.position.y<0){const e=Math.abs(t.position.y);s.position.y=s.position.y-e,s.style.height+=e,t.position.y=0}s.width=s.style.width,s.height=s.style.height}}}function Gy(e,t){return function(e,t){if(e.some(e=>"reset"===e.type))return e.filter(e=>"reset"===e.type).map(e=>e.item);const i=e.filter(e=>"add"===e.type).map(e=>e.item);return t.reduce((t,i)=>{const s=e.filter(e=>e.id===i.id);if(0===s.length)return t.push(i),t;const r={...i};for(const e of s)if(e)switch(e.type){case"select":r.selected=e.selected;break;case"position":void 0!==e.position&&(r.position=e.position),void 0!==e.positionAbsolute&&(r.positionAbsolute=e.positionAbsolute),void 0!==e.dragging&&(r.dragging=e.dragging),r.expandParent&&Xy(t,r);break;case"dimensions":void 0!==e.dimensions&&(r.width=e.dimensions.width,r.height=e.dimensions.height),void 0!==e.updateStyle&&(r.style={...r.style||{},...e.dimensions}),"boolean"==typeof e.resizing&&(r.resizing=e.resizing),r.expandParent&&Xy(t,r);break;case"remove":return t}return t.push(r),t},i)}(e,t)}const Zy=(e,t)=>({id:e,type:"select",selected:t});function Jy(e,t){return e.reduce((e,i)=>{const s=t.includes(i.id);return!i.selected&&s?(i.selected=!0,e.push(Zy(i.id,!0))):i.selected&&!s&&(i.selected=!1,e.push(Zy(i.id,!1))),e},[])}const Qy=(e,t)=>i=>{i.target===t.current&&(null==e||e(i))},ex=e=>({userSelectionActive:e.userSelectionActive,elementsSelectable:e.elementsSelectable,dragging:e.paneDragging}),tx=h.memo(({isSelecting:e,selectionMode:t=cv.Full,panOnDrag:i,onSelectionStart:s,onSelectionEnd:r,onPaneClick:n,onPaneContextMenu:o,onPaneScroll:a,onPaneMouseEnter:l,onPaneMouseMove:c,onPaneMouseLeave:d,children:u})=>{const f=h.useRef(null),p=Pg(),m=h.useRef(0),_=h.useRef(0),g=h.useRef(),{userSelectionActive:v,elementsSelectable:y,dragging:x}=Rg(ex,Of),b=()=>{p.setState({userSelectionActive:!1,userSelectionRect:null}),m.current=0,_.current=0},w=e=>{null==n||n(e),p.getState().resetSelectedElements(),p.setState({nodesSelectionActive:!1})},S=a?e=>a(e):void 0,C=y&&(e||v);return N.createElement("div",{className:vf(["react-flow__pane",{dragging:x,selection:e}]),onClick:C?void 0:Qy(w,f),onContextMenu:Qy(e=>{Array.isArray(i)&&(null==i?void 0:i.includes(2))?e.preventDefault():null==o||o(e)},f),onWheel:Qy(S,f),onMouseEnter:C?void 0:l,onMouseDown:C?t=>{const{resetSelectedElements:i,domNode:r}=p.getState();if(g.current=null==r?void 0:r.getBoundingClientRect(),!y||!e||0!==t.button||t.target!==f.current||!g.current)return;const{x:n,y:o}=Qg(t,g.current);i(),p.setState({userSelectionRect:{width:0,height:0,startX:n,startY:o,x:n,y:o}}),null==s||s(t)}:void 0,onMouseMove:C?i=>{const{userSelectionRect:s,nodeInternals:r,edges:n,transform:o,onNodesChange:a,onEdgesChange:l,nodeOrigin:c,getNodes:h}=p.getState();if(!e||!g.current||!s)return;p.setState({userSelectionActive:!0,nodesSelectionActive:!1});const d=Qg(i,g.current),u=s.startX??0,f=s.startY??0,v={...s,x:d.x<u?d.x:u,y:d.y<f?d.y:f,width:Math.abs(d.x-u),height:Math.abs(d.y-f)},y=h(),x=zv(r,v,o,t===cv.Partial,!0,c),b=$v(x,n).map(e=>e.id),w=x.map(e=>e.id);if(m.current!==w.length){m.current=w.length;const e=Jy(y,w);e.length&&(null==a||a(e))}if(_.current!==b.length){_.current=b.length;const e=Jy(n,b);e.length&&(null==l||l(e))}p.setState({userSelectionRect:v})}:c,onMouseUp:C?e=>{if(0!==e.button)return;const{userSelectionRect:t}=p.getState();!v&&t&&e.target===f.current&&(null==w||w(e)),p.setState({nodesSelectionActive:m.current>0}),b(),null==r||r(e)}:void 0,onMouseLeave:C?e=>{v&&(p.setState({nodesSelectionActive:m.current>0}),null==r||r(e)),b()}:d,ref:f,style:$y},u,N.createElement(Yy,null))});function ix(e,t){const i=e.parentNode||e.parentId;if(!i)return!1;const s=t.get(i);return!!s&&(!!s.selected||ix(s,t))}function sx(e,t,i){let s=e;do{if(null==s?void 0:s.matches(t))return!0;if(s===i.current)return!1;s=s.parentElement}while(s);return!1}function rx(e,t,i,s){return Array.from(e.values()).filter(i=>(i.selected||i.id===s)&&(!i.parentNode||i.parentId||!ix(i,e))&&(i.draggable||t&&void 0===i.draggable)).map(e=>{var t,s;return{id:e.id,position:e.position||{x:0,y:0},positionAbsolute:e.positionAbsolute||{x:0,y:0},distance:{x:i.x-((null==(t=e.positionAbsolute)?void 0:t.x)??0),y:i.y-((null==(s=e.positionAbsolute)?void 0:s.y)??0)},delta:{x:0,y:0},extent:e.extent,parentNode:e.parentNode||e.parentId,parentId:e.parentNode||e.parentId,width:e.width,height:e.height,expandParent:e.expandParent}})}function nx(e,t,i,s,r=[0,0],n){const o=function(e,t){return t&&"parent"!==t?[t[0],[t[1][0]-(e.width||0),t[1][1]-(e.height||0)]]:t}(e,e.extent||s);let a=o;const l=e.parentNode||e.parentId;if("parent"!==e.extent||e.expandParent){if(e.extent&&l&&"parent"!==e.extent){const t=i.get(l),{x:s,y:n}=Ov(t,r).positionAbsolute;a=[[e.extent[0][0]+s,e.extent[0][1]+n],[e.extent[1][0]+s,e.extent[1][1]+n]]}}else if(l&&e.width&&e.height){const t=i.get(l),{x:s,y:n}=Ov(t,r).positionAbsolute;a=t&&Yg(s)&&Yg(n)&&Yg(t.width)&&Yg(t.height)?[[s+e.width*r[0],n+e.height*r[1]],[s+t.width-e.width+e.width*r[0],n+t.height-e.height+e.height*r[1]]]:a}else null==n||n("005",Cg()),a=o;let c={x:0,y:0};if(l){const e=i.get(l);c=Ov(e,r).positionAbsolute}const h=a&&"parent"!==a?zg(t,a):t;return{position:{x:h.x-c.x,y:h.y-c.y},positionAbsolute:h}}function ox({nodeId:e,dragItems:t,nodeInternals:i}){const s=t.map(e=>({...i.get(e.id),position:e.position,positionAbsolute:e.positionAbsolute}));return[e?s.find(t=>t.id===e):s[0],s]}tx.displayName="Pane";const ax=(e,t,i,s)=>{const r=t.querySelectorAll(e);if(!r||!r.length)return null;const n=Array.from(r),o=t.getBoundingClientRect(),a=o.width*s[0],l=o.height*s[1];return n.map(e=>{const t=e.getBoundingClientRect();return{id:e.getAttribute("data-handleid"),position:e.getAttribute("data-handlepos"),x:(t.left-o.left-a)/i,y:(t.top-o.top-l)/i,...Og(e)}})};function lx(e,t,i){return void 0===i?i:s=>{const r=t().nodeInternals.get(e);r&&i(s,{...r})}}function cx({id:e,store:t,unselect:i=!1,nodeRef:s}){const{addSelectedNodes:r,unselectNodesAndEdges:n,multiSelectionActive:o,nodeInternals:a,onError:l}=t.getState(),c=a.get(e);c?(t.setState({nodesSelectionActive:!1}),c.selected?(i||c.selected&&o)&&(n({nodes:[c],edges:[]}),requestAnimationFrame(()=>{var e;return null==(e=null==s?void 0:s.current)?void 0:e.blur()})):r([e])):null==l||l("012",jg(e))}function hx(e){return(t,i,s)=>null==e?void 0:e(t,s)}function dx({nodeRef:e,disabled:t=!1,noDragClassName:i,handleSelector:s,nodeId:r,isSelectable:n,selectNodesOnDrag:o}){const a=Pg(),[l,c]=h.useState(!1),d=h.useRef([]),u=h.useRef({x:null,y:null}),f=h.useRef(0),p=h.useRef(null),m=h.useRef({x:0,y:0}),_=h.useRef(null),g=h.useRef(!1),v=h.useRef(!1),y=h.useRef(!1),x=function(){const e=Pg();return h.useCallback(({sourceEvent:t})=>{const{transform:i,snapGrid:s,snapToGrid:r}=e.getState(),n=t.touches?t.touches[0].clientX:t.clientX,o=t.touches?t.touches[0].clientY:t.clientY,a={x:(n-i[0])/i[2],y:(o-i[1])/i[2]};return{xSnapped:r?s[0]*Math.round(a.x/s[0]):a.x,ySnapped:r?s[1]*Math.round(a.y/s[1]):a.y,...a}},[])}();return h.useEffect(()=>{if(null==e?void 0:e.current){const l=tm(e.current),h=({x:e,y:t})=>{const{nodeInternals:i,onNodeDrag:s,onSelectionDrag:n,updateNodePositions:o,nodeExtent:l,snapGrid:h,snapToGrid:f,nodeOrigin:p,onError:m}=a.getState();u.current={x:e,y:t};let g=!1,v={x:0,y:0,x2:0,y2:0};if(d.current.length>1&&l){const e=Av(d.current,p);v=Kg(e)}if(d.current=d.current.map(s=>{const r={x:e-s.distance.x,y:t-s.distance.y};f&&(r.x=h[0]*Math.round(r.x/h[0]),r.y=h[1]*Math.round(r.y/h[1]));const n=[[l[0][0],l[0][1]],[l[1][0],l[1][1]]];d.current.length>1&&l&&!s.extent&&(n[0][0]=s.positionAbsolute.x-v.x+l[0][0],n[1][0]=s.positionAbsolute.x+(s.width??0)-v.x2+l[1][0],n[0][1]=s.positionAbsolute.y-v.y+l[0][1],n[1][1]=s.positionAbsolute.y+(s.height??0)-v.y2+l[1][1]);const o=nx(s,r,i,n,p,m);return g=g||s.position.x!==o.position.x||s.position.y!==o.position.y,s.position=o.position,s.positionAbsolute=o.positionAbsolute,s}),!g)return;o(d.current,!0,!0),c(!0);const y=r?s:hx(n);if(y&&_.current){const[e,t]=ox({nodeId:r,dragItems:d.current,nodeInternals:i});y(_.current,e,t)}},b=()=>{if(!p.current)return;const[e,t]=Hg(m.current,p.current);if(0!==e||0!==t){const{transform:i,panBy:s}=a.getState();u.current.x=(u.current.x??0)-e/i[2],u.current.y=(u.current.y??0)-t/i[2],s({x:e,y:t})&&h(u.current)}f.current=requestAnimationFrame(b)},w=t=>{var i;const{nodeInternals:s,multiSelectionActive:l,nodesDraggable:c,unselectNodesAndEdges:h,onNodeDragStart:f,onSelectionDragStart:p}=a.getState();v.current=!0;const m=r?f:hx(p);o&&n||l||!r||(null==(i=s.get(r))?void 0:i.selected)||h(),r&&n&&o&&cx({id:r,store:a,nodeRef:e});const _=x(t);if(u.current=_,d.current=rx(s,c,_,r),m&&d.current){const[e,i]=ox({nodeId:r,dragItems:d.current,nodeInternals:s});m(t.sourceEvent,e,i)}};if(!t){const t=function(){var e,t,i,s,r=dm,n=um,o=fm,a=pm,l={},c=zf("start","drag","end"),h=0,d=0;function u(e){e.on("mousedown.drag",f).filter(a).on("touchstart.drag",_).on("touchmove.drag",g,sm).on("touchend.drag touchcancel.drag",v).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function f(o,a){if(!s&&r.call(this,o,a)){var l=y(this,n.call(this,o,a),o,a,"mouse");l&&(tm(o.view).on("mousemove.drag",p,rm).on("mouseup.drag",m,rm),am(o.view),nm(o),i=!1,e=o.clientX,t=o.clientY,l("start",o))}}function p(s){if(om(s),!i){var r=s.clientX-e,n=s.clientY-t;i=r*r+n*n>d}l.mouse("drag",s)}function m(e){tm(e.view).on("mousemove.drag mouseup.drag",null),lm(e.view,i),om(e),l.mouse("end",e)}function _(e,t){if(r.call(this,e,t)){var i,s,o=e.changedTouches,a=n.call(this,e,t),l=o.length;for(i=0;i<l;++i)(s=y(this,a,e,t,o[i].identifier,o[i]))&&(nm(e),s("start",e,o[i]))}}function g(e){var t,i,s=e.changedTouches,r=s.length;for(t=0;t<r;++t)(i=l[s[t].identifier])&&(om(e),i("drag",e,s[t]))}function v(e){var t,i,r=e.changedTouches,n=r.length;for(s&&clearTimeout(s),s=setTimeout(function(){s=null},500),t=0;t<n;++t)(i=l[r[t].identifier])&&(nm(e),i("end",e,r[t]))}function y(e,t,i,s,r,n){var a,d,f,p=c.copy(),m=im(n||i,t);if(null!=(f=o.call(e,new hm("beforestart",{sourceEvent:i,target:u,identifier:r,active:h,x:m[0],y:m[1],dx:0,dy:0,dispatch:p}),s)))return a=f.x-m[0]||0,d=f.y-m[1]||0,function i(n,o,c){var _,g=m;switch(n){case"start":l[r]=i,_=h++;break;case"end":delete l[r],--h;case"drag":m=im(c||o,t),_=h}p.call(n,e,new hm(n,{sourceEvent:o,subject:f,target:u,identifier:r,active:_,x:m[0]+a,y:m[1]+d,dx:m[0]-g[0],dy:m[1]-g[1],dispatch:p}),s)}}return u.filter=function(e){return arguments.length?(r="function"==typeof e?e:cm(!!e),u):r},u.container=function(e){return arguments.length?(n="function"==typeof e?e:cm(e),u):n},u.subject=function(e){return arguments.length?(o="function"==typeof e?e:cm(e),u):o},u.touchable=function(e){return arguments.length?(a="function"==typeof e?e:cm(!!e),u):a},u.on=function(){var e=c.on.apply(c,arguments);return e===c?u:e},u.clickDistance=function(e){return arguments.length?(d=(e=+e)*e,u):Math.sqrt(d)},u}().on("start",e=>{const{domNode:t,nodeDragThreshold:i}=a.getState();0===i&&w(e),y.current=!1;const s=x(e);u.current=s,p.current=(null==t?void 0:t.getBoundingClientRect())||null,m.current=Qg(e.sourceEvent,p.current)}).on("drag",e=>{var t,i;const s=x(e),{autoPanOnNodeDrag:r,nodeDragThreshold:n}=a.getState();if("touchmove"===e.sourceEvent.type&&e.sourceEvent.touches.length>1&&(y.current=!0),!y.current){if(!g.current&&v.current&&r&&(g.current=!0,b()),!v.current){const r=s.xSnapped-((null==(t=null==u?void 0:u.current)?void 0:t.x)??0),o=s.ySnapped-((null==(i=null==u?void 0:u.current)?void 0:i.y)??0);Math.sqrt(r*r+o*o)>n&&w(e)}(u.current.x!==s.xSnapped||u.current.y!==s.ySnapped)&&d.current&&v.current&&(_.current=e.sourceEvent,m.current=Qg(e.sourceEvent,p.current),h(s))}}).on("end",e=>{if(v.current&&!y.current&&(c(!1),g.current=!1,v.current=!1,cancelAnimationFrame(f.current),d.current)){const{updateNodePositions:t,nodeInternals:i,onNodeDragStop:s,onSelectionDragStop:n}=a.getState(),o=r?s:hx(n);if(t(d.current,!1,!1),o){const[t,s]=ox({nodeId:r,dragItems:d.current,nodeInternals:i});o(e.sourceEvent,t,s)}}}).filter(t=>{const r=t.target;return!t.button&&(!i||!sx(r,`.${i}`,e))&&(!s||sx(r,s,e))});return l.call(t),()=>{l.on(".drag",null)}}l.on(".drag",null)}},[e,t,i,s,n,a,r,o,x]),l}function ux(){const e=Pg(),t=h.useCallback(t=>{const{nodeInternals:i,nodeExtent:s,updateNodePositions:r,getNodes:n,snapToGrid:o,snapGrid:a,onError:l,nodesDraggable:c}=e.getState(),h=n().filter(e=>e.selected&&(e.draggable||c&&void 0===e.draggable)),d=o?a[0]:5,u=o?a[1]:5,f=t.isShiftPressed?4:1,p=t.x*d*f,m=t.y*u*f,_=h.map(e=>{if(e.positionAbsolute){const t={x:e.positionAbsolute.x+p,y:e.positionAbsolute.y+m};o&&(t.x=a[0]*Math.round(t.x/a[0]),t.y=a[1]*Math.round(t.y/a[1]));const{positionAbsolute:r,position:n}=nx(e,t,i,s,void 0,l);e.position=n,e.positionAbsolute=r}return e});r(_,!0,!1)},[]);return t}const fx={ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1},ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0}};var px=e=>{const t=({id:t,type:i,data:s,xPos:r,yPos:n,xPosOrigin:o,yPosOrigin:a,selected:l,onClick:c,onMouseEnter:d,onMouseMove:u,onMouseLeave:f,onContextMenu:p,onDoubleClick:m,style:_,className:g,isDraggable:v,isSelectable:y,isConnectable:x,isFocusable:b,selectNodesOnDrag:w,sourcePosition:S,targetPosition:C,hidden:k,resizeObserver:E,dragHandle:M,zIndex:j,isParent:D,noDragClassName:R,noPanClassName:P,initialized:L,disableKeyboardA11y:T,ariaLabel:I,rfId:B,hasHandleBounds:O})=>{const A=Pg(),z=h.useRef(null),$=h.useRef(null),H=h.useRef(S),W=h.useRef(C),F=h.useRef(i),K=y||v||c||d||u||f,U=ux(),V=lx(t,A.getState,d),q=lx(t,A.getState,u),Y=lx(t,A.getState,f),X=lx(t,A.getState,p),G=lx(t,A.getState,m);h.useEffect(()=>()=>{$.current&&(null==E||E.unobserve($.current),$.current=null)},[]),h.useEffect(()=>{if(z.current&&!k){const e=z.current;L&&O&&$.current===e||($.current&&(null==E||E.unobserve($.current)),null==E||E.observe(e),$.current=e)}},[k,L,O]),h.useEffect(()=>{const e=F.current!==i,s=H.current!==S,r=W.current!==C;z.current&&(e||s||r)&&(e&&(F.current=i),s&&(H.current=S),r&&(W.current=C),A.getState().updateNodeDimensions([{id:t,nodeElement:z.current,forceUpdate:!0}]))},[t,i,S,C]);const Z=dx({nodeRef:z,disabled:k||!v,noDragClassName:R,handleSelector:M,nodeId:t,isSelectable:y,selectNodesOnDrag:w});return k?null:N.createElement("div",{className:vf(["react-flow__node",`react-flow__node-${i}`,{[P]:v},g,{selected:l,selectable:y,parent:D,dragging:Z}]),ref:z,style:{zIndex:j,transform:`translate(${o}px,${a}px)`,pointerEvents:K?"all":"none",visibility:L?"visible":"hidden",..._},"data-id":t,"data-testid":`rf__node-${t}`,onMouseEnter:V,onMouseMove:q,onMouseLeave:Y,onContextMenu:X,onClick:e=>{const{nodeDragThreshold:i}=A.getState();if(y&&(!w||!v||i>0)&&cx({id:t,store:A,nodeRef:z}),c){const i=A.getState().nodeInternals.get(t);i&&c(e,{...i})}},onDoubleClick:G,onKeyDown:b?e=>{if(!Zg(e)&&!T)if(Gg.includes(e.key)&&y){const i="Escape"===e.key;cx({id:t,store:A,unselect:i,nodeRef:z})}else v&&l&&Object.prototype.hasOwnProperty.call(fx,e.key)&&(A.setState({ariaLiveMessage:`Moved selected node ${e.key.replace("Arrow","").toLowerCase()}. New position, x: ${~~r}, y: ${~~n}`}),U({x:fx[e.key].x,y:fx[e.key].y,isShiftPressed:e.shiftKey}))}:void 0,tabIndex:b?0:void 0,role:b?"button":void 0,"aria-describedby":T?void 0:`${xy}-${B}`,"aria-label":I},N.createElement(Pv,{value:t},N.createElement(e,{id:t,data:s,type:i,xPos:r,yPos:n,selected:l,isConnectable:x,sourcePosition:S,targetPosition:C,dragging:Z,dragHandle:M,zIndex:j})))};return t.displayName="NodeWrapper",h.memo(t)};const mx=e=>{const t=e.getNodes().filter(e=>e.selected);return{...Av(t,e.nodeOrigin),transformString:`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]})`,userSelectionActive:e.userSelectionActive}};var _x=h.memo(function({onSelectionContextMenu:e,noPanClassName:t,disableKeyboardA11y:i}){const s=Pg(),{width:r,height:n,x:o,y:a,transformString:l,userSelectionActive:c}=Rg(mx,Of),d=ux(),u=h.useRef(null);if(h.useEffect(()=>{var e;i||null==(e=u.current)||e.focus({preventScroll:!0})},[i]),dx({nodeRef:u}),c||!r||!n)return null;const f=e?t=>{const i=s.getState().getNodes().filter(e=>e.selected);e(t,i)}:void 0;return N.createElement("div",{className:vf(["react-flow__nodesselection","react-flow__container",t]),style:{transform:l}},N.createElement("div",{ref:u,className:"react-flow__nodesselection-rect",onContextMenu:f,tabIndex:i?void 0:-1,onKeyDown:i?void 0:e=>{Object.prototype.hasOwnProperty.call(fx,e.key)&&d({x:fx[e.key].x,y:fx[e.key].y,isShiftPressed:e.shiftKey})},style:{width:r,height:n,top:a,left:o}}))});const gx=e=>e.nodesSelectionActive,vx=({children:e,onPaneClick:t,onPaneMouseEnter:i,onPaneMouseMove:s,onPaneMouseLeave:r,onPaneContextMenu:n,onPaneScroll:o,deleteKeyCode:a,onMove:l,onMoveStart:c,onMoveEnd:d,selectionKeyCode:u,selectionOnDrag:f,selectionMode:p,onSelectionStart:m,onSelectionEnd:_,multiSelectionKeyCode:g,panActivationKeyCode:v,zoomActivationKeyCode:y,elementsSelectable:x,zoomOnScroll:b,zoomOnPinch:w,panOnScroll:S,panOnScrollSpeed:C,panOnScrollMode:k,zoomOnDoubleClick:E,panOnDrag:M,defaultViewport:j,translateExtent:D,minZoom:R,maxZoom:P,preventScrolling:L,onSelectionContextMenu:T,noWheelClassName:I,noPanClassName:B,disableKeyboardA11y:O})=>{const A=Rg(gx),z=ky(u),$=ky(v),H=$||M,W=$||S,F=z||f&&!0!==H;return(({deleteKeyCode:e,multiSelectionKeyCode:t})=>{const i=Pg(),{deleteElements:s}=Ay(),r=ky(e,zy),n=ky(t);h.useEffect(()=>{if(r){const{edges:e,getNodes:t}=i.getState(),r=t().filter(e=>e.selected),n=e.filter(e=>e.selected);s({nodes:r,edges:n}),i.setState({nodesSelectionActive:!1})}},[r]),h.useEffect(()=>{i.setState({multiSelectionActive:n})},[n])})({deleteKeyCode:a,multiSelectionKeyCode:g}),N.createElement(Vy,{onMove:l,onMoveStart:c,onMoveEnd:d,onPaneContextMenu:n,elementsSelectable:x,zoomOnScroll:b,zoomOnPinch:w,panOnScroll:W,panOnScrollSpeed:C,panOnScrollMode:k,zoomOnDoubleClick:E,panOnDrag:!z&&H,defaultViewport:j,translateExtent:D,minZoom:R,maxZoom:P,zoomActivationKeyCode:y,preventScrolling:L,noWheelClassName:I,noPanClassName:B},N.createElement(tx,{onSelectionStart:m,onSelectionEnd:_,onPaneClick:t,onPaneMouseEnter:i,onPaneMouseMove:s,onPaneMouseLeave:r,onPaneContextMenu:n,onPaneScroll:o,panOnDrag:H,isSelecting:!!F,selectionMode:p},e,A&&N.createElement(_x,{onSelectionContextMenu:T,noPanClassName:B,disableKeyboardA11y:O})))};vx.displayName="FlowRenderer";var yx=h.memo(vx);function xx(e){return{...{input:px(e.input||ry),default:px(e.default||iy),output:px(e.output||oy),group:px(e.group||ay)},...Object.keys(e).filter(e=>!["input","default","output","group"].includes(e)).reduce((t,i)=>(t[i]=px(e[i]||iy),t),{})}}const bx=e=>({nodesDraggable:e.nodesDraggable,nodesConnectable:e.nodesConnectable,nodesFocusable:e.nodesFocusable,elementsSelectable:e.elementsSelectable,updateNodeDimensions:e.updateNodeDimensions,onError:e.onError}),wx=e=>{const{nodesDraggable:t,nodesConnectable:i,nodesFocusable:s,elementsSelectable:r,updateNodeDimensions:n,onError:o}=Rg(bx,Of),a=(l=e.onlyRenderVisibleElements,Rg(h.useCallback(e=>l?zv(e.nodeInternals,{x:0,y:0,width:e.width,height:e.height},e.transform,!0):e.getNodes(),[l])));var l;const c=h.useRef(),d=h.useMemo(()=>{if("undefined"==typeof ResizeObserver)return null;const e=new ResizeObserver(e=>{const t=e.map(e=>({id:e.target.getAttribute("data-id"),nodeElement:e.target,forceUpdate:!0}));n(t)});return c.current=e,e},[]);return h.useEffect(()=>()=>{var e;null==(e=null==c?void 0:c.current)||e.disconnect()},[]),N.createElement("div",{className:"react-flow__nodes",style:$y},a.map(n=>{var a,l,c;let h=n.type||"default";e.nodeTypes[h]||(null==o||o("003",wg(h)),h="default");const u=e.nodeTypes[h]||e.nodeTypes.default,f=!!(n.draggable||t&&void 0===n.draggable),p=!!(n.selectable||r&&void 0===n.selectable),m=!!(n.connectable||i&&void 0===n.connectable),_=!!(n.focusable||s&&void 0===n.focusable),g=e.nodeExtent?zg(n.positionAbsolute,e.nodeExtent):n.positionAbsolute,v=(null==g?void 0:g.x)??0,y=(null==g?void 0:g.y)??0,x=(({x:e,y:t,width:i,height:s,origin:r})=>i&&s?r[0]<0||r[1]<0||r[0]>1||r[1]>1?{x:e,y:t}:{x:e-i*r[0],y:t-s*r[1]}:{x:e,y:t})({x:v,y:y,width:n.width??0,height:n.height??0,origin:e.nodeOrigin});return N.createElement(u,{key:n.id,id:n.id,className:n.className,style:n.style,type:h,data:n.data,sourcePosition:n.sourcePosition||mv.Bottom,targetPosition:n.targetPosition||mv.Top,hidden:n.hidden,xPos:v,yPos:y,xPosOrigin:x.x,yPosOrigin:x.y,selectNodesOnDrag:e.selectNodesOnDrag,onClick:e.onNodeClick,onMouseEnter:e.onNodeMouseEnter,onMouseMove:e.onNodeMouseMove,onMouseLeave:e.onNodeMouseLeave,onContextMenu:e.onNodeContextMenu,onDoubleClick:e.onNodeDoubleClick,selected:!!n.selected,isDraggable:f,isSelectable:p,isConnectable:m,isFocusable:_,resizeObserver:d,dragHandle:n.dragHandle,zIndex:(null==(a=n[Xg])?void 0:a.z)??0,isParent:!!(null==(l=n[Xg])?void 0:l.isParent),noDragClassName:e.noDragClassName,noPanClassName:e.noPanClassName,initialized:!!n.width&&!!n.height,rfId:e.rfId,disableKeyboardA11y:e.disableKeyboardA11y,ariaLabel:n.ariaLabel,hasHandleBounds:!!(null==(c=n[Xg])?void 0:c.handleBounds)})}))};wx.displayName="NodeRenderer";var Sx=h.memo(wx);const Cx=(e,t,i)=>i===mv.Left?e-t:i===mv.Right?e+t:e,kx=(e,t,i)=>i===mv.Top?e-t:i===mv.Bottom?e+t:e,Ex="react-flow__edgeupdater",Nx=({position:e,centerX:t,centerY:i,radius:s=10,onMouseDown:r,onMouseEnter:n,onMouseOut:o,type:a})=>N.createElement("circle",{onMouseDown:r,onMouseEnter:n,onMouseOut:o,className:vf([Ex,`${Ex}-${a}`]),cx:Cx(t,s,e),cy:kx(i,s,e),r:s,stroke:"transparent",fill:"transparent"}),Mx=()=>!0;var jx=e=>{const t=({id:t,className:i,type:s,data:r,onClick:n,onEdgeDoubleClick:o,selected:a,animated:l,label:c,labelStyle:d,labelShowBg:u,labelBgStyle:f,labelBgPadding:p,labelBgBorderRadius:m,style:_,source:g,target:v,sourceX:y,sourceY:x,targetX:b,targetY:w,sourcePosition:S,targetPosition:C,elementsSelectable:k,hidden:E,sourceHandleId:M,targetHandleId:j,onContextMenu:D,onMouseEnter:R,onMouseMove:P,onMouseLeave:L,reconnectRadius:T,onReconnect:I,onReconnectStart:B,onReconnectEnd:O,markerEnd:A,markerStart:z,rfId:$,ariaLabel:H,isFocusable:W,isReconnectable:F,pathOptions:K,interactionWidth:U,disableKeyboardA11y:V})=>{const q=h.useRef(null),[Y,X]=h.useState(!1),[G,Z]=h.useState(!1),J=Pg(),Q=h.useMemo(()=>`url('#${Tv(z,$)}')`,[z,$]),ee=h.useMemo(()=>`url('#${Tv(A,$)}')`,[A,$]);if(E)return null;const te=iv(t,J.getState,o),ie=iv(t,J.getState,D),se=iv(t,J.getState,R),re=iv(t,J.getState,P),ne=iv(t,J.getState,L),oe=(e,i)=>{if(0!==e.button)return;const{edges:s,isValidConnection:r}=J.getState(),n=i?v:g,o=(i?j:M)||null,a=i?"target":"source",l=r||Mx,c=i,h=s.find(e=>e.id===t);Z(!0),null==B||B(e,h,a);Gv({event:e,handleId:o,nodeId:n,onConnect:e=>null==I?void 0:I(h,e),isTarget:c,getState:J.getState,setState:J.setState,isValidConnection:l,edgeUpdaterType:a,onReconnectEnd:e=>{Z(!1),null==O||O(e,h,a)}})},ae=()=>X(!0),le=()=>X(!1),ce=!k&&!n;return N.createElement("g",{className:vf(["react-flow__edge",`react-flow__edge-${s}`,i,{selected:a,animated:l,inactive:ce,updating:Y}]),onClick:e=>{var i;const{edges:s,addSelectedEdges:r,unselectNodesAndEdges:o,multiSelectionActive:a}=J.getState(),l=s.find(e=>e.id===t);l&&(k&&(J.setState({nodesSelectionActive:!1}),l.selected&&a?(o({nodes:[],edges:[l]}),null==(i=q.current)||i.blur()):r([t])),n&&n(e,l))},onDoubleClick:te,onContextMenu:ie,onMouseEnter:se,onMouseMove:re,onMouseLeave:ne,onKeyDown:W?e=>{var i;if(!V&&Gg.includes(e.key)&&k){const{unselectNodesAndEdges:s,addSelectedEdges:r,edges:n}=J.getState();"Escape"===e.key?(null==(i=q.current)||i.blur(),s({edges:[n.find(e=>e.id===t)]})):r([t])}}:void 0,tabIndex:W?0:void 0,role:W?"button":"img","data-testid":`rf__edge-${t}`,"aria-label":null===H?void 0:H||`Edge from ${g} to ${v}`,"aria-describedby":W?`${by}-${$}`:void 0,ref:q},!G&&N.createElement(e,{id:t,source:g,target:v,selected:a,animated:l,label:c,labelStyle:d,labelShowBg:u,labelBgStyle:f,labelBgPadding:p,labelBgBorderRadius:m,data:r,style:_,sourceX:y,sourceY:x,targetX:b,targetY:w,sourcePosition:S,targetPosition:C,sourceHandleId:M,targetHandleId:j,markerStart:Q,markerEnd:ee,pathOptions:K,interactionWidth:U}),F&&N.createElement(N.Fragment,null,("source"===F||!0===F)&&N.createElement(Nx,{position:S,centerX:y,centerY:x,radius:T,onMouseDown:e=>oe(e,!0),onMouseEnter:ae,onMouseOut:le,type:"source"}),("target"===F||!0===F)&&N.createElement(Nx,{position:C,centerX:b,centerY:w,radius:T,onMouseDown:e=>oe(e,!1),onMouseEnter:ae,onMouseOut:le,type:"target"})))};return t.displayName="EdgeWrapper",h.memo(t)};function Dx(e){return{...{default:jx(e.default||Dv),straight:jx(e.bezier||Ev),step:jx(e.step||kv),smoothstep:jx(e.step||Cv),simplebezier:jx(e.simplebezier||yv)},...Object.keys(e).filter(e=>!["default","bezier"].includes(e)).reduce((t,i)=>(t[i]=jx(e[i]||Dv),t),{})}}function Rx(e,t,i=null){const s=((null==i?void 0:i.x)||0)+t.x,r=((null==i?void 0:i.y)||0)+t.y,n=(null==i?void 0:i.width)||t.width,o=(null==i?void 0:i.height)||t.height;switch(e){case mv.Top:return{x:s+n/2,y:r};case mv.Right:return{x:s+n,y:r+o/2};case mv.Bottom:return{x:s+n/2,y:r+o};case mv.Left:return{x:s,y:r+o/2}}}function Px(e,t){return e?1!==e.length&&t?t&&e.find(e=>e.id===t)||null:e[0]:null}function Lx(e){var t,i,s,r,n;const o=(null==(t=null==e?void 0:e[Xg])?void 0:t.handleBounds)||null,a=o&&(null==e?void 0:e.width)&&(null==e?void 0:e.height)&&void 0!==(null==(i=null==e?void 0:e.positionAbsolute)?void 0:i.x)&&void 0!==(null==(s=null==e?void 0:e.positionAbsolute)?void 0:s.y);return[{x:(null==(r=null==e?void 0:e.positionAbsolute)?void 0:r.x)||0,y:(null==(n=null==e?void 0:e.positionAbsolute)?void 0:n.y)||0,width:(null==e?void 0:e.width)||0,height:(null==e?void 0:e.height)||0},o,!!a]}const Tx=[{level:0,isMaxLevel:!0,edges:[]}];function Ix(e,t,i){const s=Rg(h.useCallback(i=>e?i.edges.filter(e=>{const s=t.get(e.source),r=t.get(e.target);return(null==s?void 0:s.width)&&(null==s?void 0:s.height)&&(null==r?void 0:r.width)&&(null==r?void 0:r.height)&&function({sourcePos:e,targetPos:t,sourceWidth:i,sourceHeight:s,targetWidth:r,targetHeight:n,width:o,height:a,transform:l}){const c={x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),x2:Math.max(e.x+i,t.x+r),y2:Math.max(e.y+s,t.y+n)};c.x===c.x2&&(c.x2+=1),c.y===c.y2&&(c.y2+=1);const h=Kg({x:(0-l[0])/l[2],y:(0-l[1])/l[2],width:o/l[2],height:a/l[2]}),d=Math.max(0,Math.min(h.x2,c.x2)-Math.max(h.x,c.x)),u=Math.max(0,Math.min(h.y2,c.y2)-Math.max(h.y,c.y));return Math.ceil(d*u)>0}({sourcePos:s.positionAbsolute||{x:0,y:0},targetPos:r.positionAbsolute||{x:0,y:0},sourceWidth:s.width,sourceHeight:s.height,targetWidth:r.width,targetHeight:r.height,width:i.width,height:i.height,transform:i.transform})}):i.edges,[e,t]));return function(e,t,i=!1){let s=-1;const r=e.reduce((e,r)=>{var n,o;const a=Yg(r.zIndex);let l=a?r.zIndex:0;if(i){const e=t.get(r.target),i=t.get(r.source),s=r.selected||(null==e?void 0:e.selected)||(null==i?void 0:i.selected),c=Math.max((null==(n=null==i?void 0:i[Xg])?void 0:n.z)||0,(null==(o=null==e?void 0:e[Xg])?void 0:o.z)||0,1e3);l=(a?r.zIndex:0)+(s?c:0)}return e[l]?e[l].push(r):e[l]=[r],s=l>s?l:s,e},{}),n=Object.entries(r).map(([e,t])=>{const i=+e;return{edges:t,level:i,isMaxLevel:i===s}});return 0===n.length?Tx:n}(s,t,i)}const Bx={[fv.Arrow]:({color:e="none",strokeWidth:t=1})=>N.createElement("polyline",{style:{stroke:e,strokeWidth:t},strokeLinecap:"round",strokeLinejoin:"round",fill:"none",points:"-5,-4 0,0 -5,4"}),[fv.ArrowClosed]:({color:e="none",strokeWidth:t=1})=>N.createElement("polyline",{style:{stroke:e,fill:e,strokeWidth:t},strokeLinecap:"round",strokeLinejoin:"round",points:"-5,-4 0,0 -5,4 -5,-4"})};const Ox=({id:e,type:t,color:i,width:s=12.5,height:r=12.5,markerUnits:n="strokeWidth",strokeWidth:o,orient:a="auto-start-reverse"})=>{const l=function(e){const t=Pg();return h.useMemo(()=>{var i,s;return Object.prototype.hasOwnProperty.call(Bx,e)?Bx[e]:(null==(s=(i=t.getState()).onError)||s.call(i,"009",kg(e)),null)},[e])}(t);return l?N.createElement("marker",{className:"react-flow__arrowhead",id:e,markerWidth:`${s}`,markerHeight:`${r}`,viewBox:"-10 -10 20 20",markerUnits:n,orient:a,refX:"0",refY:"0"},N.createElement(l,{color:i,strokeWidth:o})):null},Ax=({defaultColor:e,rfId:t})=>{const i=Rg(h.useCallback((({defaultColor:e,rfId:t})=>i=>{const s=[];return i.edges.reduce((i,r)=>([r.markerStart,r.markerEnd].forEach(r=>{if(r&&"object"==typeof r){const n=Tv(r,t);s.includes(n)||(i.push({id:n,color:r.color||e,...r}),s.push(n))}}),i),[]).sort((e,t)=>e.id.localeCompare(t.id))})({defaultColor:e,rfId:t}),[e,t]),(e,t)=>!(e.length!==t.length||e.some((e,i)=>e.id!==t[i].id)));return N.createElement("defs",null,i.map(e=>N.createElement(Ox,{id:e.id,key:e.id,type:e.type,color:e.color,width:e.width,height:e.height,markerUnits:e.markerUnits,strokeWidth:e.strokeWidth,orient:e.orient})))};Ax.displayName="MarkerDefinitions";var zx=h.memo(Ax);const $x=e=>({nodesConnectable:e.nodesConnectable,edgesFocusable:e.edgesFocusable,edgesUpdatable:e.edgesUpdatable,elementsSelectable:e.elementsSelectable,width:e.width,height:e.height,connectionMode:e.connectionMode,nodeInternals:e.nodeInternals,onError:e.onError}),Hx=({defaultMarkerColor:e,onlyRenderVisibleElements:t,elevateEdgesOnSelect:i,rfId:s,edgeTypes:r,noPanClassName:n,onEdgeContextMenu:o,onEdgeMouseEnter:a,onEdgeMouseMove:l,onEdgeMouseLeave:c,onEdgeClick:h,onEdgeDoubleClick:d,onReconnect:u,onReconnectStart:f,onReconnectEnd:p,reconnectRadius:m,children:_,disableKeyboardA11y:g})=>{const{edgesFocusable:v,edgesUpdatable:y,elementsSelectable:x,width:b,height:w,connectionMode:S,nodeInternals:C,onError:k}=Rg($x,Of),E=Ix(t,C,i);return b?N.createElement(N.Fragment,null,E.map(({level:t,edges:i,isMaxLevel:_})=>N.createElement("svg",{key:t,style:{zIndex:t},width:b,height:w,className:"react-flow__edges react-flow__container"},_&&N.createElement(zx,{defaultColor:e,rfId:s}),N.createElement("g",null,i.map(e=>{const[t,i,_]=Lx(C.get(e.source)),[b,w,E]=Lx(C.get(e.target));if(!_||!E)return null;let M=e.type||"default";r[M]||(null==k||k("011",Mg(M)),M="default");const j=r[M]||r.default,D=S===nv.Strict?w.target:(w.target??[]).concat(w.source??[]),R=Px(i.source,e.sourceHandle),P=Px(D,e.targetHandle),L=(null==R?void 0:R.position)||mv.Bottom,T=(null==P?void 0:P.position)||mv.Top,I=!!(e.focusable||v&&void 0===e.focusable),B=e.reconnectable||e.updatable,O=void 0!==u&&(B||y&&void 0===B);if(!R||!P)return null==k||k("008",Eg(R,e)),null;const{sourceX:A,sourceY:z,targetX:$,targetY:H}=((e,t,i,s,r,n)=>{const o=Rx(i,e,t),a=Rx(n,s,r);return{sourceX:o.x,sourceY:o.y,targetX:a.x,targetY:a.y}})(t,R,L,b,P,T);return N.createElement(j,{key:e.id,id:e.id,className:vf([e.className,n]),type:M,data:e.data,selected:!!e.selected,animated:!!e.animated,hidden:!!e.hidden,label:e.label,labelStyle:e.labelStyle,labelShowBg:e.labelShowBg,labelBgStyle:e.labelBgStyle,labelBgPadding:e.labelBgPadding,labelBgBorderRadius:e.labelBgBorderRadius,style:e.style,source:e.source,target:e.target,sourceHandleId:e.sourceHandle,targetHandleId:e.targetHandle,markerEnd:e.markerEnd,markerStart:e.markerStart,sourceX:A,sourceY:z,targetX:$,targetY:H,sourcePosition:L,targetPosition:T,elementsSelectable:x,onContextMenu:o,onMouseEnter:a,onMouseMove:l,onMouseLeave:c,onClick:h,onEdgeDoubleClick:d,onReconnect:u,onReconnectStart:f,onReconnectEnd:p,reconnectRadius:m,rfId:s,ariaLabel:e.ariaLabel,isFocusable:I,isReconnectable:O,pathOptions:"pathOptions"in e?e.pathOptions:void 0,interactionWidth:e.interactionWidth,disableKeyboardA11y:g})})))),_):null};Hx.displayName="EdgeRenderer";var Wx=h.memo(Hx);const Fx=e=>`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]})`;function Kx({children:e}){const t=Rg(Fx);return N.createElement("div",{className:"react-flow__viewport react-flow__container",style:{transform:t}},e)}const Ux={[mv.Left]:mv.Right,[mv.Right]:mv.Left,[mv.Top]:mv.Bottom,[mv.Bottom]:mv.Top},Vx=({nodeId:e,handleType:t,style:i,type:s=dv.Bezier,CustomComponent:r,connectionStatus:n})=>{var o,a,l;const{fromNode:c,handleId:d,toX:u,toY:f,connectionMode:p}=Rg(h.useCallback(t=>({fromNode:t.nodeInternals.get(e),handleId:t.connectionHandleId,toX:(t.connectionPosition.x-t.transform[0])/t.transform[2],toY:(t.connectionPosition.y-t.transform[1])/t.transform[2],connectionMode:t.connectionMode}),[e]),Of),m=null==(o=null==c?void 0:c[Xg])?void 0:o.handleBounds;let _=null==m?void 0:m[t];if(p===nv.Loose&&(_=_||(null==m?void 0:m["source"===t?"target":"source"])),!c||!_)return null;const g=d?_.find(e=>e.id===d):_[0],v=g?g.x+g.width/2:(c.width??0)/2,y=g?g.y+g.height/2:c.height??0,x=((null==(a=c.positionAbsolute)?void 0:a.x)??0)+v,b=((null==(l=c.positionAbsolute)?void 0:l.y)??0)+y,w=null==g?void 0:g.position,S=w?Ux[w]:null;if(!w||!S)return null;if(r)return N.createElement(r,{connectionLineType:s,connectionLineStyle:i,fromNode:c,fromHandle:g,fromX:x,fromY:b,toX:u,toY:f,fromPosition:w,toPosition:S,connectionStatus:n});let C="";const k={sourceX:x,sourceY:b,sourcePosition:w,targetX:u,targetY:f,targetPosition:S};return s===dv.Bezier?[C]=jv(k):s===dv.Step?[C]=Sv({...k,borderRadius:0}):s===dv.SmoothStep?[C]=Sv(k):s===dv.SimpleBezier?[C]=vv(k):C=`M${x},${b} ${u},${f}`,N.createElement("path",{d:C,fill:"none",className:"react-flow__connection-path",style:i})};Vx.displayName="ConnectionLine";const qx=e=>({nodeId:e.connectionNodeId,handleType:e.connectionHandleType,nodesConnectable:e.nodesConnectable,connectionStatus:e.connectionStatus,width:e.width,height:e.height});function Yx({containerStyle:e,style:t,type:i,component:s}){const{nodeId:r,handleType:n,nodesConnectable:o,width:a,height:l,connectionStatus:c}=Rg(qx,Of);return!!(r&&n&&a&&o)?N.createElement("svg",{style:e,width:a,height:l,className:"react-flow__edges react-flow__connectionline react-flow__container"},N.createElement("g",{className:vf(["react-flow__connection",c])},N.createElement(Vx,{nodeId:r,handleType:n,style:t,type:i,CustomComponent:s,connectionStatus:c}))):null}function Xx(e,t){h.useRef(null),Pg();return h.useMemo(()=>t(e),[e])}const Gx=({nodeTypes:e,edgeTypes:t,onMove:i,onMoveStart:s,onMoveEnd:r,onInit:n,onNodeClick:o,onEdgeClick:a,onNodeDoubleClick:l,onEdgeDoubleClick:c,onNodeMouseEnter:d,onNodeMouseMove:u,onNodeMouseLeave:f,onNodeContextMenu:p,onSelectionContextMenu:m,onSelectionStart:_,onSelectionEnd:g,connectionLineType:v,connectionLineStyle:y,connectionLineComponent:x,connectionLineContainerStyle:b,selectionKeyCode:w,selectionOnDrag:S,selectionMode:C,multiSelectionKeyCode:k,panActivationKeyCode:E,zoomActivationKeyCode:M,deleteKeyCode:j,onlyRenderVisibleElements:D,elementsSelectable:R,selectNodesOnDrag:P,defaultViewport:L,translateExtent:T,minZoom:I,maxZoom:B,preventScrolling:O,defaultMarkerColor:A,zoomOnScroll:z,zoomOnPinch:$,panOnScroll:H,panOnScrollSpeed:W,panOnScrollMode:F,zoomOnDoubleClick:K,panOnDrag:U,onPaneClick:V,onPaneMouseEnter:q,onPaneMouseMove:Y,onPaneMouseLeave:X,onPaneScroll:G,onPaneContextMenu:Z,onEdgeContextMenu:J,onEdgeMouseEnter:Q,onEdgeMouseMove:ee,onEdgeMouseLeave:te,onReconnect:ie,onReconnectStart:se,onReconnectEnd:re,reconnectRadius:ne,noDragClassName:oe,noWheelClassName:ae,noPanClassName:le,elevateEdgesOnSelect:ce,disableKeyboardA11y:he,nodeOrigin:de,nodeExtent:ue,rfId:fe})=>{const pe=Xx(e,xx),me=Xx(t,Dx);return function(e){const t=Ay(),i=h.useRef(!1);h.useEffect(()=>{!i.current&&t.viewportInitialized&&e&&(setTimeout(()=>e(t),1),i.current=!0)},[e,t.viewportInitialized])}(n),N.createElement(yx,{onPaneClick:V,onPaneMouseEnter:q,onPaneMouseMove:Y,onPaneMouseLeave:X,onPaneContextMenu:Z,onPaneScroll:G,deleteKeyCode:j,selectionKeyCode:w,selectionOnDrag:S,selectionMode:C,onSelectionStart:_,onSelectionEnd:g,multiSelectionKeyCode:k,panActivationKeyCode:E,zoomActivationKeyCode:M,elementsSelectable:R,onMove:i,onMoveStart:s,onMoveEnd:r,zoomOnScroll:z,zoomOnPinch:$,zoomOnDoubleClick:K,panOnScroll:H,panOnScrollSpeed:W,panOnScrollMode:F,panOnDrag:U,defaultViewport:L,translateExtent:T,minZoom:I,maxZoom:B,onSelectionContextMenu:m,preventScrolling:O,noDragClassName:oe,noWheelClassName:ae,noPanClassName:le,disableKeyboardA11y:he},N.createElement(Kx,null,N.createElement(Wx,{edgeTypes:me,onEdgeClick:a,onEdgeDoubleClick:c,onlyRenderVisibleElements:D,onEdgeContextMenu:J,onEdgeMouseEnter:Q,onEdgeMouseMove:ee,onEdgeMouseLeave:te,onReconnect:ie,onReconnectStart:se,onReconnectEnd:re,reconnectRadius:ne,defaultMarkerColor:A,noPanClassName:le,elevateEdgesOnSelect:!!ce,disableKeyboardA11y:he,rfId:fe},N.createElement(Yx,{style:y,type:v,component:x,containerStyle:b})),N.createElement("div",{className:"react-flow__edgelabel-renderer"}),N.createElement(Sx,{nodeTypes:pe,onNodeClick:o,onNodeDoubleClick:l,onNodeMouseEnter:d,onNodeMouseMove:u,onNodeMouseLeave:f,onNodeContextMenu:p,selectNodesOnDrag:P,onlyRenderVisibleElements:D,noPanClassName:le,noDragClassName:oe,disableKeyboardA11y:he,nodeOrigin:de,nodeExtent:ue,rfId:fe})))};Gx.displayName="GraphView";var Zx=h.memo(Gx);const Jx=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],Qx={rfId:"1",width:0,height:0,transform:[0,0,1],nodeInternals:new Map,edges:[],onNodesChange:null,onEdgesChange:null,hasDefaultNodes:!1,hasDefaultEdges:!1,d3Zoom:null,d3Selection:null,d3ZoomHandler:void 0,minZoom:.5,maxZoom:2,translateExtent:Jx,nodeExtent:Jx,nodesSelectionActive:!1,userSelectionActive:!1,userSelectionRect:null,connectionNodeId:null,connectionHandleId:null,connectionHandleType:"source",connectionPosition:{x:0,y:0},connectionStatus:null,connectionMode:nv.Strict,domNode:null,paneDragging:!1,noPanClassName:"nopan",nodeOrigin:[0,0],nodeDragThreshold:0,snapGrid:[15,15],snapToGrid:!1,nodesDraggable:!0,nodesConnectable:!0,nodesFocusable:!0,edgesFocusable:!0,edgesUpdatable:!0,elementsSelectable:!0,elevateNodesOnSelect:!0,fitViewOnInit:!1,fitViewOnInitDone:!1,fitViewOnInitOptions:void 0,onSelectionChange:[],multiSelectionActive:!1,connectionStartHandle:null,connectionEndHandle:null,connectionClickStartHandle:null,connectOnClick:!0,ariaLiveMessage:"",autoPanOnConnect:!0,autoPanOnNodeDrag:!0,connectionRadius:20,onError:(e,t)=>{},isValidConnection:void 0},eb=()=>{return e=(e,t)=>({...Qx,setNodes:i=>{const{nodeInternals:s,nodeOrigin:r,elevateNodesOnSelect:n}=t();e({nodeInternals:Dy(i,s,r,n)})},getNodes:()=>Array.from(t().nodeInternals.values()),setEdges:i=>{const{defaultEdgeOptions:s={}}=t();e({edges:i.map(e=>({...s,...e}))})},setDefaultNodesAndEdges:(i,s)=>{const r=void 0!==i,n=void 0!==s,o=r?Dy(i,new Map,t().nodeOrigin,t().elevateNodesOnSelect):new Map;e({nodeInternals:o,edges:n?s:[],hasDefaultNodes:r,hasDefaultEdges:n})},updateNodeDimensions:i=>{const{onNodesChange:s,nodeInternals:r,fitViewOnInit:n,fitViewOnInitDone:o,fitViewOnInitOptions:a,domNode:l,nodeOrigin:c}=t(),h=null==l?void 0:l.querySelector(".react-flow__viewport");if(!h)return;const d=window.getComputedStyle(h),{m22:u}=new window.DOMMatrixReadOnly(d.transform),f=i.reduce((e,t)=>{const i=r.get(t.id);if(null==i?void 0:i.hidden)r.set(i.id,{...i,[Xg]:{...i[Xg],handleBounds:void 0}});else if(i){const s=Og(t.nodeElement);s.width&&s.height&&(i.width!==s.width||i.height!==s.height||t.forceUpdate)&&(r.set(i.id,{...i,[Xg]:{...i[Xg],handleBounds:{source:ax(".source",t.nodeElement,u,c),target:ax(".target",t.nodeElement,u,c)}},...s}),e.push({id:i.id,type:"dimensions",dimensions:s}))}return e},[]);jy(r,c);const p=o||n&&!o&&Ry(t,{initial:!0,...a});e({nodeInternals:new Map(r),fitViewOnInitDone:p}),(null==f?void 0:f.length)>0&&(null==s||s(f))},updateNodePositions:(e,i=!0,s=!1)=>{const{triggerNodeChanges:r}=t();r(e.map(e=>{const t={id:e.id,type:"position",dragging:s};return i&&(t.positionAbsolute=e.positionAbsolute,t.position=e.position),t}))},triggerNodeChanges:i=>{const{onNodesChange:s,nodeInternals:r,hasDefaultNodes:n,nodeOrigin:o,getNodes:a,elevateNodesOnSelect:l}=t();if(null==i?void 0:i.length){if(n){const t=Dy(Gy(i,a()),r,o,l);e({nodeInternals:t})}null==s||s(i)}},addSelectedNodes:i=>{const{multiSelectionActive:s,edges:r,getNodes:n}=t();let o,a=null;s?o=i.map(e=>Zy(e,!0)):(o=Jy(n(),i),a=Jy(r,[])),Ty({changedNodes:o,changedEdges:a,get:t,set:e})},addSelectedEdges:i=>{const{multiSelectionActive:s,edges:r,getNodes:n}=t();let o,a=null;s?o=i.map(e=>Zy(e,!0)):(o=Jy(r,i),a=Jy(n(),[])),Ty({changedNodes:a,changedEdges:o,get:t,set:e})},unselectNodesAndEdges:({nodes:i,edges:s}={})=>{const{edges:r,getNodes:n}=t(),o=s||r,a=(i||n()).map(e=>(e.selected=!1,Zy(e.id,!1)));Ty({changedNodes:a,changedEdges:o.map(e=>Zy(e.id,!1)),get:t,set:e})},setMinZoom:i=>{const{d3Zoom:s,maxZoom:r}=t();null==s||s.scaleExtent([i,r]),e({minZoom:i})},setMaxZoom:i=>{const{d3Zoom:s,minZoom:r}=t();null==s||s.scaleExtent([r,i]),e({maxZoom:i})},setTranslateExtent:i=>{var s;null==(s=t().d3Zoom)||s.translateExtent(i),e({translateExtent:i})},resetSelectedElements:()=>{const{edges:i,getNodes:s}=t(),r=s().filter(e=>e.selected).map(e=>Zy(e.id,!1)),n=i.filter(e=>e.selected).map(e=>Zy(e.id,!1));Ty({changedNodes:r,changedEdges:n,get:t,set:e})},setNodeExtent:i=>{const{nodeInternals:s}=t();s.forEach(e=>{e.positionAbsolute=zg(e.position,i)}),e({nodeExtent:i,nodeInternals:new Map(s)})},panBy:e=>{const{transform:i,width:s,height:r,d3Zoom:n,d3Selection:o,translateExtent:a}=t();if(!n||!o||!e.x&&!e.y)return!1;const l=hg.translate(i[0]+e.x,i[1]+e.y).scale(i[2]),c=[[0,0],[s,r]],h=null==n?void 0:n.constrain()(l,c,a);return n.transform(o,h),i[0]!==h.x||i[1]!==h.y||i[2]!==h.k},cancelConnection:()=>e({connectionNodeId:Qx.connectionNodeId,connectionHandleId:Qx.connectionHandleId,connectionHandleType:Qx.connectionHandleType,connectionStatus:Qx.connectionStatus,connectionStartHandle:Qx.connectionStartHandle,connectionEndHandle:Qx.connectionEndHandle}),reset:()=>e({...Qx})}),t=Object.is,e?Bf(e,t):Bf;var e,t},tb=({children:e})=>{const t=h.useRef(null);return t.current||(t.current=eb()),N.createElement(bg,{value:t.current},e)};tb.displayName="ReactFlowProvider";const ib=({children:e})=>h.useContext(xg)?N.createElement(N.Fragment,null,e):N.createElement(tb,null,e);ib.displayName="ReactFlowWrapper";const sb={input:ry,default:iy,output:oy,group:ay},rb={default:Dv,straight:Ev,step:kv,smoothstep:Cv,simplebezier:yv},nb=[0,0],ob=[15,15],ab={x:0,y:0,zoom:1},lb={width:"100%",height:"100%",overflow:"hidden",position:"relative",zIndex:0},cb=h.forwardRef(({nodes:e,edges:t,defaultNodes:i,defaultEdges:s,className:r,nodeTypes:n=sb,edgeTypes:o=rb,onNodeClick:a,onEdgeClick:l,onInit:c,onMove:h,onMoveStart:d,onMoveEnd:u,onConnect:f,onConnectStart:p,onConnectEnd:m,onClickConnectStart:_,onClickConnectEnd:g,onNodeMouseEnter:v,onNodeMouseMove:y,onNodeMouseLeave:x,onNodeContextMenu:b,onNodeDoubleClick:w,onNodeDragStart:S,onNodeDrag:C,onNodeDragStop:k,onNodesDelete:E,onEdgesDelete:M,onSelectionChange:j,onSelectionDragStart:D,onSelectionDrag:R,onSelectionDragStop:P,onSelectionContextMenu:L,onSelectionStart:T,onSelectionEnd:I,connectionMode:B=nv.Strict,connectionLineType:O=dv.Bezier,connectionLineStyle:A,connectionLineComponent:z,connectionLineContainerStyle:$,deleteKeyCode:H="Backspace",selectionKeyCode:W="Shift",selectionOnDrag:F=!1,selectionMode:K=cv.Full,panActivationKeyCode:U="Space",multiSelectionKeyCode:V=(ev()?"Meta":"Control"),zoomActivationKeyCode:q=(ev()?"Meta":"Control"),snapToGrid:Y=!1,snapGrid:X=ob,onlyRenderVisibleElements:G=!1,selectNodesOnDrag:Z=!0,nodesDraggable:J,nodesConnectable:Q,nodesFocusable:ee,nodeOrigin:te=nb,edgesFocusable:ie,edgesUpdatable:se,elementsSelectable:re,defaultViewport:ne=ab,minZoom:oe=.5,maxZoom:ae=2,translateExtent:le=Jx,preventScrolling:ce=!0,nodeExtent:he,defaultMarkerColor:de="#b1b1b7",zoomOnScroll:ue=!0,zoomOnPinch:fe=!0,panOnScroll:pe=!1,panOnScrollSpeed:me=.5,panOnScrollMode:_e=av.Free,zoomOnDoubleClick:ge=!0,panOnDrag:ve=!0,onPaneClick:ye,onPaneMouseEnter:xe,onPaneMouseMove:be,onPaneMouseLeave:we,onPaneScroll:Se,onPaneContextMenu:Ce,children:ke,onEdgeContextMenu:Ee,onEdgeDoubleClick:Ne,onEdgeMouseEnter:Me,onEdgeMouseMove:je,onEdgeMouseLeave:De,onEdgeUpdate:Re,onEdgeUpdateStart:Pe,onEdgeUpdateEnd:Le,onReconnect:Te,onReconnectStart:Ie,onReconnectEnd:Be,reconnectRadius:Oe=10,edgeUpdaterRadius:Ae=10,onNodesChange:ze,onEdgesChange:$e,noDragClassName:He="nodrag",noWheelClassName:We="nowheel",noPanClassName:Fe="nopan",fitView:Ke=!1,fitViewOptions:Ue,connectOnClick:Ve=!0,attributionPosition:qe,proOptions:Ye,defaultEdgeOptions:Xe,elevateNodesOnSelect:Ge=!0,elevateEdgesOnSelect:Ze=!1,disableKeyboardA11y:Je=!1,autoPanOnConnect:Qe=!0,autoPanOnNodeDrag:et=!0,connectionRadius:tt=20,isValidConnection:it,onError:st,style:rt,id:nt,nodeDragThreshold:ot,...at},lt)=>{const ct=nt||"1";return N.createElement("div",{...at,style:{...rt,...lb},ref:lt,className:vf(["react-flow",r]),"data-testid":"rf__wrapper",id:nt},N.createElement(ib,null,N.createElement(Zx,{onInit:c,onMove:h,onMoveStart:d,onMoveEnd:u,onNodeClick:a,onEdgeClick:l,onNodeMouseEnter:v,onNodeMouseMove:y,onNodeMouseLeave:x,onNodeContextMenu:b,onNodeDoubleClick:w,nodeTypes:n,edgeTypes:o,connectionLineType:O,connectionLineStyle:A,connectionLineComponent:z,connectionLineContainerStyle:$,selectionKeyCode:W,selectionOnDrag:F,selectionMode:K,deleteKeyCode:H,multiSelectionKeyCode:V,panActivationKeyCode:U,zoomActivationKeyCode:q,onlyRenderVisibleElements:G,selectNodesOnDrag:Z,defaultViewport:ne,translateExtent:le,minZoom:oe,maxZoom:ae,preventScrolling:ce,zoomOnScroll:ue,zoomOnPinch:fe,zoomOnDoubleClick:ge,panOnScroll:pe,panOnScrollSpeed:me,panOnScrollMode:_e,panOnDrag:ve,onPaneClick:ye,onPaneMouseEnter:xe,onPaneMouseMove:be,onPaneMouseLeave:we,onPaneScroll:Se,onPaneContextMenu:Ce,onSelectionContextMenu:L,onSelectionStart:T,onSelectionEnd:I,onEdgeContextMenu:Ee,onEdgeDoubleClick:Ne,onEdgeMouseEnter:Me,onEdgeMouseMove:je,onEdgeMouseLeave:De,onReconnect:Te??Re,onReconnectStart:Ie??Pe,onReconnectEnd:Be??Le,reconnectRadius:Oe??Ae,defaultMarkerColor:de,noDragClassName:He,noWheelClassName:We,noPanClassName:Fe,elevateEdgesOnSelect:Ze,rfId:ct,disableKeyboardA11y:Je,nodeOrigin:te,nodeExtent:he}),N.createElement(gy,{nodes:e,edges:t,defaultNodes:i,defaultEdges:s,onConnect:f,onConnectStart:p,onConnectEnd:m,onClickConnectStart:_,onClickConnectEnd:g,nodesDraggable:J,nodesConnectable:Q,nodesFocusable:ee,edgesFocusable:ie,edgesUpdatable:se,elementsSelectable:re,elevateNodesOnSelect:Ge,minZoom:oe,maxZoom:ae,nodeExtent:he,onNodesChange:ze,onEdgesChange:$e,snapToGrid:Y,snapGrid:X,connectionMode:B,translateExtent:le,connectOnClick:Ve,defaultEdgeOptions:Xe,fitView:Ke,fitViewOptions:Ue,onNodesDelete:E,onEdgesDelete:M,onNodeDragStart:S,onNodeDrag:C,onNodeDragStop:k,onSelectionDrag:R,onSelectionDragStart:D,onSelectionDragStop:P,noPanClassName:Fe,nodeOrigin:te,rfId:ct,autoPanOnConnect:Qe,autoPanOnNodeDrag:et,onError:st,connectionRadius:tt,isValidConnection:it,nodeDragThreshold:ot}),N.createElement(fy,{onSelectionChange:j}),ke,N.createElement(Ig,{proOptions:Ye,position:qe}),N.createElement(Cy,{rfId:ct,disableKeyboardA11y:Je})))});cb.displayName="ReactFlow";const hb=e=>{var t;return null==(t=e.domNode)?void 0:t.querySelector(".react-flow__edgelabel-renderer")};function db({children:e}){const t=Rg(hb);return t?pt.createPortal(e,t):null}function ub(e,t){if(Object.is(e,t))return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(const[i,s]of e)if(!Object.is(s,t.get(i)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(const i of e)if(!t.has(i))return!1;return!0}const i=Object.keys(e);if(i.length!==Object.keys(t).length)return!1;for(const s of i)if(!Object.prototype.hasOwnProperty.call(t,s)||!Object.is(e[s],t[s]))return!1;return!0}const fb=({id:e,x:t,y:i,width:s,height:r,style:n,color:o,strokeColor:a,strokeWidth:l,className:c,borderRadius:h,shapeRendering:d,onClick:u,selected:f})=>{const{background:p,backgroundColor:m}=n||{},_=o||p||m;return N.createElement("rect",{className:vf(["react-flow__minimap-node",{selected:f},c]),x:t,y:i,rx:h,ry:h,width:s,height:r,fill:_,stroke:a,strokeWidth:l,shapeRendering:d,onClick:u?t=>u(t,e):void 0})};fb.displayName="MiniMapNode";var pb=h.memo(fb);const mb=e=>e.nodeOrigin,_b=e=>e.getNodes().filter(e=>!e.hidden&&e.width&&e.height),gb=e=>e instanceof Function?e:()=>e;var vb=h.memo(function({nodeStrokeColor:e="transparent",nodeColor:t="#e2e2e2",nodeClassName:i="",nodeBorderRadius:s=5,nodeStrokeWidth:r=2,nodeComponent:n=pb,onClick:o}){const a=Rg(_b,ub),l=Rg(mb),c=gb(t),h=gb(e),d=gb(i),u="undefined"==typeof window||window.chrome?"crispEdges":"geometricPrecision";return N.createElement(N.Fragment,null,a.map(e=>{const{x:t,y:i}=Ov(e,l).positionAbsolute;return N.createElement(n,{key:e.id,x:t,y:i,width:e.width,height:e.height,style:e.style,selected:e.selected,className:d(e),color:c(e),borderRadius:s,strokeColor:h(e),strokeWidth:r,shapeRendering:u,onClick:o,id:e.id})}))});const yb=e=>{const t=e.getNodes(),i={x:-e.transform[0]/e.transform[2],y:-e.transform[1]/e.transform[2],width:e.width/e.transform[2],height:e.height/e.transform[2]};return{viewBB:i,boundingRect:t.length>0?(s=Av(t,e.nodeOrigin),r=i,Ug(Fg(Kg(s),Kg(r)))):i,rfId:e.rfId};var s,r};function xb({style:e,className:t,nodeStrokeColor:i="transparent",nodeColor:s="#e2e2e2",nodeClassName:r="",nodeBorderRadius:n=5,nodeStrokeWidth:o=2,nodeComponent:a,maskColor:l="rgb(240, 240, 240, 0.6)",maskStrokeColor:c="none",maskStrokeWidth:d=1,position:u="bottom-right",onClick:f,onNodeClick:p,pannable:m=!1,zoomable:_=!1,ariaLabel:g="React Flow mini map",inversePan:v=!1,zoomStep:y=10,offsetScale:x=5}){const b=Pg(),w=h.useRef(null),{boundingRect:S,viewBB:C,rfId:k}=Rg(yb,ub),E=(null==e?void 0:e.width)??200,M=(null==e?void 0:e.height)??150,j=S.width/E,D=S.height/M,R=Math.max(j,D),P=R*E,L=R*M,T=x*R,I=S.x-(P-S.width)/2-T,B=S.y-(L-S.height)/2-T,O=P+2*T,A=L+2*T,z=`react-flow__minimap-desc-${k}`,$=h.useRef(0);$.current=R,h.useEffect(()=>{if(w.current){const e=tm(w.current),t=e=>{const{transform:t,d3Selection:i,d3Zoom:s}=b.getState();if("wheel"!==e.sourceEvent.type||!i||!s)return;const r=-e.sourceEvent.deltaY*(1===e.sourceEvent.deltaMode?.05:e.sourceEvent.deltaMode?1:.002)*y,n=t[2]*Math.pow(2,r);s.scaleTo(i,n)},i=e=>{const{transform:t,d3Selection:i,d3Zoom:s,translateExtent:r,width:n,height:o}=b.getState();if("mousemove"!==e.sourceEvent.type||!i||!s)return;const a=$.current*Math.max(1,t[2])*(v?-1:1),l={x:t[0]-e.sourceEvent.movementX*a,y:t[1]-e.sourceEvent.movementY*a},c=[[0,0],[n,o]],h=hg.translate(l.x,l.y).scale(t[2]),d=s.constrain()(h,c,r);s.transform(i,d)},s=yg().on("zoom",m?i:null).on("zoom.wheel",_?t:null);return e.call(s),()=>{e.on("zoom",null)}}},[m,_,v,y]);const H=f?e=>{const t=im(e);f(e,{x:t[0],y:t[1]})}:void 0,W=p?(e,t)=>{const i=b.getState().nodeInternals.get(t);p(e,i)}:void 0;return N.createElement(Tg,{position:u,style:e,className:vf(["react-flow__minimap",t]),"data-testid":"rf__minimap"},N.createElement("svg",{width:E,height:M,viewBox:`${I} ${B} ${O} ${A}`,role:"img","aria-labelledby":z,ref:w,onClick:H},g&&N.createElement("title",{id:z},g),N.createElement(vb,{onClick:W,nodeColor:s,nodeStrokeColor:i,nodeBorderRadius:n,nodeClassName:r,nodeStrokeWidth:o,nodeComponent:a}),N.createElement("path",{className:"react-flow__minimap-mask",d:`M${I-T},${B-T}h${O+2*T}v${A+2*T}h${-O-2*T}z\n M${C.x},${C.y}h${C.width}v${C.height}h${-C.width}z`,fill:l,fillRule:"evenodd",stroke:c,strokeWidth:d,pointerEvents:"none"})))}xb.displayName="MiniMap";var bb=h.memo(xb);function wb(e,t){if(Object.is(e,t))return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(const[i,s]of e)if(!Object.is(s,t.get(i)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(const i of e)if(!t.has(i))return!1;return!0}const i=Object.keys(e);if(i.length!==Object.keys(t).length)return!1;for(const s of i)if(!Object.prototype.hasOwnProperty.call(t,s)||!Object.is(e[s],t[s]))return!1;return!0}function Sb(){return N.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 32"},N.createElement("path",{d:"M32 18.133H18.133V32h-4.266V18.133H0v-4.266h13.867V0h4.266v13.867H32z"}))}function Cb(){return N.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 5"},N.createElement("path",{d:"M0 0h32v4.2H0z"}))}function kb(){return N.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 30"},N.createElement("path",{d:"M3.692 4.63c0-.53.4-.938.939-.938h5.215V0H4.708C2.13 0 0 2.054 0 4.63v5.216h3.692V4.631zM27.354 0h-5.2v3.692h5.17c.53 0 .984.4.984.939v5.215H32V4.631A4.624 4.624 0 0027.354 0zm.954 24.83c0 .532-.4.94-.939.94h-5.215v3.768h5.215c2.577 0 4.631-2.13 4.631-4.707v-5.139h-3.692v5.139zm-23.677.94c-.531 0-.939-.4-.939-.94v-5.138H0v5.139c0 2.577 2.13 4.707 4.708 4.707h5.138V25.77H4.631z"}))}function Eb(){return N.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 25 32"},N.createElement("path",{d:"M21.333 10.667H19.81V7.619C19.81 3.429 16.38 0 12.19 0 8 0 4.571 3.429 4.571 7.619v3.048H3.048A3.056 3.056 0 000 13.714v15.238A3.056 3.056 0 003.048 32h18.285a3.056 3.056 0 003.048-3.048V13.714a3.056 3.056 0 00-3.048-3.047zM12.19 24.533a3.056 3.056 0 01-3.047-3.047 3.056 3.056 0 013.047-3.048 3.056 3.056 0 013.048 3.048 3.056 3.056 0 01-3.048 3.047zm4.724-13.866H7.467V7.619c0-2.59 2.133-4.724 4.723-4.724 2.591 0 4.724 2.133 4.724 4.724v3.048z"}))}function Nb(){return N.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 25 32"},N.createElement("path",{d:"M21.333 10.667H19.81V7.619C19.81 3.429 16.38 0 12.19 0c-4.114 1.828-1.37 2.133.305 2.438 1.676.305 4.42 2.59 4.42 5.181v3.048H3.047A3.056 3.056 0 000 13.714v15.238A3.056 3.056 0 003.048 32h18.285a3.056 3.056 0 003.048-3.048V13.714a3.056 3.056 0 00-3.048-3.047zM12.19 24.533a3.056 3.056 0 01-3.047-3.047 3.056 3.056 0 013.047-3.048 3.056 3.056 0 013.048 3.048 3.056 3.056 0 01-3.048 3.047z"}))}const Mb=({children:e,className:t,...i})=>N.createElement("button",{type:"button",className:vf(["react-flow__controls-button",t]),...i},e);Mb.displayName="ControlButton";const jb=e=>({isInteractive:e.nodesDraggable||e.nodesConnectable||e.elementsSelectable,minZoomReached:e.transform[2]<=e.minZoom,maxZoomReached:e.transform[2]>=e.maxZoom}),Db=({style:e,showZoom:t=!0,showFitView:i=!0,showInteractive:s=!0,fitViewOptions:r,onZoomIn:n,onZoomOut:o,onFitView:a,onInteractiveChange:l,className:c,children:d,position:u="bottom-left"})=>{const f=Pg(),[p,m]=h.useState(!1),{isInteractive:_,minZoomReached:g,maxZoomReached:v}=Rg(jb,wb),{zoomIn:y,zoomOut:x,fitView:b}=Ay();if(h.useEffect(()=>{m(!0)},[]),!p)return null;return N.createElement(Tg,{className:vf(["react-flow__controls",c]),position:u,style:e,"data-testid":"rf__controls"},t&&N.createElement(N.Fragment,null,N.createElement(Mb,{onClick:()=>{y(),null==n||n()},className:"react-flow__controls-zoomin",title:"zoom in","aria-label":"zoom in",disabled:v},N.createElement(Sb,null)),N.createElement(Mb,{onClick:()=>{x(),null==o||o()},className:"react-flow__controls-zoomout",title:"zoom out","aria-label":"zoom out",disabled:g},N.createElement(Cb,null))),i&&N.createElement(Mb,{className:"react-flow__controls-fitview",onClick:()=>{b(r),null==a||a()},title:"fit view","aria-label":"fit view"},N.createElement(kb,null)),s&&N.createElement(Mb,{className:"react-flow__controls-interactive",onClick:()=>{f.setState({nodesDraggable:!_,nodesConnectable:!_,elementsSelectable:!_}),null==l||l(!_)},title:"toggle interactivity","aria-label":"toggle interactivity"},_?N.createElement(Nb,null):N.createElement(Eb,null)),d)};Db.displayName="Controls";var Rb,Pb,Lb=h.memo(Db);function Tb(e,t){if(Object.is(e,t))return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(const[i,s]of e)if(!Object.is(s,t.get(i)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(const i of e)if(!t.has(i))return!1;return!0}const i=Object.keys(e);if(i.length!==Object.keys(t).length)return!1;for(const s of i)if(!Object.prototype.hasOwnProperty.call(t,s)||!Object.is(e[s],t[s]))return!1;return!0}function Ib({color:e,dimensions:t,lineWidth:i}){return N.createElement("path",{stroke:e,strokeWidth:i,d:`M${t[0]/2} 0 V${t[1]} M0 ${t[1]/2} H${t[0]}`})}function Bb({color:e,radius:t}){return N.createElement("circle",{cx:t,cy:t,r:t,fill:e})}(Pb=Rb||(Rb={})).Lines="lines",Pb.Dots="dots",Pb.Cross="cross";const Ob={[Rb.Dots]:"#91919a",[Rb.Lines]:"#eee",[Rb.Cross]:"#e2e2e2"},Ab={[Rb.Dots]:1,[Rb.Lines]:1,[Rb.Cross]:6},zb=e=>({transform:e.transform,patternId:`pattern-${e.rfId}`});function $b({id:e,variant:t=Rb.Dots,gap:i=20,size:s,lineWidth:r=1,offset:n=2,color:o,style:a,className:l}){const c=h.useRef(null),{transform:d,patternId:u}=Rg(zb,Tb),f=o||Ob[t],p=s||Ab[t],m=t===Rb.Dots,_=t===Rb.Cross,g=Array.isArray(i)?i:[i,i],v=[g[0]*d[2]||1,g[1]*d[2]||1],y=p*d[2],x=_?[y,y]:v,b=m?[y/n,y/n]:[x[0]/n,x[1]/n];return N.createElement("svg",{className:vf(["react-flow__background",l]),style:{...a,position:"absolute",width:"100%",height:"100%",top:0,left:0},ref:c,"data-testid":"rf__background"},N.createElement("pattern",{id:u+e,x:d[0]%v[0],y:d[1]%v[1],width:v[0],height:v[1],patternUnits:"userSpaceOnUse",patternTransform:`translate(-${b[0]},-${b[1]})`},m?N.createElement(Bb,{color:f,radius:y/n}):N.createElement(Ib,{dimensions:x,color:f,lineWidth:r})),N.createElement("rect",{x:"0",y:"0",width:"100%",height:"100%",fill:`url(#${u+e})`}))}$b.displayName="Background";var Hb=h.memo($b);function Wb(e,t){switch(t.type){case"add_variable":return e.variables.some(e=>e.key===t.variable.key)?e:{...e,variables:[...e.variables,t.variable]};case"remove_variable":return{...e,variables:e.variables.filter(e=>e.key!==t.key)};case"update_variable":return void 0!==t.patch.key&&t.patch.key!==t.key&&e.variables.some(e=>e.key===t.patch.key)?e:{...e,variables:e.variables.map(e=>e.key===t.key?{...e,...t.patch}:e)};case"add_node":return{...e,nodes:[...e.nodes,t.node]};case"remove_node":return{...e,nodes:e.nodes.filter(e=>e.id!==t.nodeId),edges:e.edges.filter(e=>e.source!==t.nodeId&&e.target!==t.nodeId)};case"update_node":{const{type:i,...s}=t.patch;return{...e,nodes:e.nodes.map(e=>e.id===t.nodeId?{...e,...s}:e)}}case"move_node":return{...e,nodes:e.nodes.map(e=>e.id===t.nodeId?{...e,position:t.position}:e)};case"add_edge":{const i=t.sourceHandle??"default",s=e.edges.some(e=>e.source===t.source&&(e.sourceHandle??"default")===i&&e.target===t.target);if(s)return e;const r={id:cs("e"),source:t.source,sourceHandle:i,target:t.target};return{...e,edges:[...e.edges,r]}}case"remove_edge":return{...e,edges:e.edges.filter(e=>e.id!==t.edgeId)};case"set_track_name":return{...e,trackName:t.name};case"set_adapter":return{...e,adapter:t.adapter};case"replace":return t.flow;default:return e}}const Fb=h.createContext(null);function Kb({value:e,children:t}){return _.jsx(Fb.Provider,{value:e,children:t})}function Ub(){const e=h.useContext(Fb);if(!e)throw new Error("useGraphDispatch outside GraphProvider");return e.dispatch}function Vb(e){const t=h.useContext(Fb);return(null==t?void 0:t.nodeStates)?t.nodeStates.get(e)??null:null}const qb=[{type:"user_input",Icon:xi,label:"用户输入",iconClass:"text-pink-600 dark:text-pink-400"},{type:"llm",Icon:ci,label:"LLM 调用",iconClass:"text-orange-600 dark:text-orange-400"},{type:"if",Icon:_i,label:"逻辑判断",iconClass:"text-sky-600 dark:text-sky-400"}];function Yb(e,t){const i=cs("n");switch(e){case"user_input":return{id:i,type:"user_input",position:t,fields:[]};case"llm":return{id:i,type:"llm",position:t,promptTemplate:"",inputs:[],outputs:[]};case"if":return{id:i,type:"if",position:t,conditionExpr:""};default:throw new Error(`unknown node type: ${e}`)}}function Xb(){const e=Ub();return _.jsxs("aside",{className:"w-32 border-r border-border bg-background p-2 flex flex-col gap-2",children:[_.jsx("div",{className:"text-xs text-muted-foreground px-1",children:"拖入画布"}),qb.map(({type:t,Icon:i,label:s,iconClass:r})=>_.jsxs("div",{draggable:!0,role:"button",tabIndex:0,onDragStart:e=>{e.dataTransfer.setData("application/x-ccweb-flow-node",t),e.dataTransfer.effectAllowed="move"},onClick:()=>{const i=Yb(t,{x:200,y:200});e({type:"add_node",node:i})},onKeyDown:i=>{if("Enter"===i.key||" "===i.key){i.preventDefault();const s=Yb(t,{x:200,y:200});e({type:"add_node",node:s})}},className:"cursor-grab rounded-md border border-border bg-muted/40 hover:bg-accent px-2 py-2 text-sm flex items-center gap-1.5 transition-colors",children:[_.jsx(i,{className:`h-3.5 w-3.5 shrink-0 ${r}`}),_.jsx("span",{className:"text-foreground truncate",children:s})]},t))]})}function Gb({nodeId:e,icon:t,label:i}){const s=Ub();return _.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[_.jsx("span",{className:"text-base shrink-0 [&_svg]:h-4 [&_svg]:w-4",children:t}),_.jsx("span",{className:"font-medium flex-1 text-foreground truncate",children:i}),_.jsx("button",{type:"button",className:"nodrag inline-flex items-center justify-center h-5 w-5 rounded text-muted-foreground hover:text-destructive hover:bg-accent transition-colors",onClick:t=>{t.stopPropagation(),s({type:"remove_node",nodeId:e})},onPointerDown:e=>{e.stopPropagation()},title:"删除节点",children:_.jsx(S,{className:"h-3 w-3"})})]})}const Zb={user_input:function({id:e,data:t,selected:i}){var s;const r=Vb(e);return _.jsxs("div",{className:["rounded-lg border-2 px-3 py-2 min-w-[240px]","bg-pink-50 dark:bg-pink-950/40",i?"border-primary shadow":"border-pink-300 dark:border-pink-800",(n=r,"active"===n?"border-amber-500 ring-2 ring-amber-200 dark:ring-amber-900 animate-pulse":"completed"===n?"border-emerald-600 ring-1 ring-emerald-200 dark:ring-emerald-900":"failed"===n?"border-destructive ring-2 ring-red-200 dark:ring-red-900":"skipped"===n?"opacity-50 line-through":"")].join(" "),children:[_.jsx(ey,{type:"target",position:mv.Top}),_.jsx(Gb,{nodeId:e,icon:_.jsx(xi,{className:"text-pink-600 dark:text-pink-400"}),label:(null==(s=t.label)?void 0:s.trim())||"用户输入"}),_.jsx("div",{className:"font-mono text-sm text-foreground/80",children:0===t.fields.length?_.jsx("div",{className:"text-muted-foreground",children:"(无字段)"}):t.fields.map((e,t)=>_.jsxs("div",{className:"pl-1",children:[e.varKey," ",_.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",e.uiHint??"text",")"]})]},t))}),_.jsx(ey,{type:"source",position:mv.Bottom})]});var n},llm:function({id:e,data:t,selected:i}){var s;const r=Vb(e);return _.jsxs("div",{className:["rounded-lg border-2 px-3 py-2 min-w-[280px] max-w-[360px]","bg-orange-50 dark:bg-orange-950/40",i?"border-primary shadow":"border-orange-300 dark:border-orange-800",(n=r,"active"===n?"border-amber-500 ring-2 ring-amber-200 dark:ring-amber-900 animate-pulse":"completed"===n?"border-emerald-600 ring-1 ring-emerald-200 dark:ring-emerald-900":"failed"===n?"border-destructive ring-2 ring-red-200 dark:ring-red-900":"skipped"===n?"opacity-50 line-through":"")].join(" "),children:[_.jsx(ey,{type:"target",position:mv.Top}),_.jsx(Gb,{nodeId:e,icon:_.jsx(ci,{className:"text-orange-600 dark:text-orange-400"}),label:(null==(s=t.label)?void 0:s.trim())||"LLM 调用"}),_.jsxs("div",{className:"font-mono text-xs text-foreground/80",children:[_.jsxs("div",{className:"truncate",children:["prompt: ",t.promptTemplate.slice(0,60),t.promptTemplate.length>60?"…":""]}),_.jsxs("div",{className:"text-xs text-muted-foreground mt-1",children:[t.inputs.length," 输入 → ",t.outputs.length," 输出"]})]}),_.jsx(ey,{type:"source",position:mv.Bottom})]});var n},if:function({id:e,data:t,selected:i}){var s;const r=Vb(e);return _.jsxs("div",{className:["rounded-lg border-2 px-3 py-2 min-w-[240px]","bg-sky-50 dark:bg-sky-950/40",i?"border-primary shadow":"border-sky-300 dark:border-sky-800",(n=r,"active"===n?"border-amber-500 ring-2 ring-amber-200 dark:ring-amber-900 animate-pulse":"completed"===n?"border-emerald-600 ring-1 ring-emerald-200 dark:ring-emerald-900":"failed"===n?"border-destructive ring-2 ring-red-200 dark:ring-red-900":"skipped"===n?"opacity-50 line-through":"")].join(" "),children:[_.jsx(ey,{type:"target",position:mv.Top}),_.jsx(Gb,{nodeId:e,icon:_.jsx(_i,{className:"text-sky-600 dark:text-sky-400"}),label:(null==(s=t.label)?void 0:s.trim())||"逻辑判断"}),_.jsxs("div",{className:"font-mono text-sm text-foreground/80",children:["if (",t.conditionExpr||"<空条件>",")"]}),_.jsx(ey,{type:"source",position:mv.Bottom,id:"true",style:{left:"30%",background:"#10b981"}}),_.jsx(ey,{type:"source",position:mv.Bottom,id:"false",style:{left:"70%",background:"#ef4444"}}),_.jsxs("div",{className:"flex justify-between text-xs mt-1 px-2",children:[_.jsx("span",{className:"text-emerald-600 dark:text-emerald-400",children:"true"}),_.jsx("span",{className:"text-red-600 dark:text-red-400",children:"false"})]})]});var n}},Jb={deletable:function(e){const{id:t,sourceX:i,sourceY:s,targetX:r,targetY:n,sourcePosition:o,targetPosition:a,selected:l,style:c,markerEnd:d}=e,u=Ub(),[f,p]=h.useState(!1),[m,g,v]=jv({sourceX:i,sourceY:s,sourcePosition:o,targetX:r,targetY:n,targetPosition:a});return _.jsxs(_.Fragment,{children:[_.jsx(tv,{id:t,path:m,markerEnd:d,style:c}),_.jsx("path",{d:m,fill:"none",stroke:"transparent",strokeWidth:20,onMouseEnter:()=>p(!0),onMouseLeave:()=>p(!1),style:{cursor:"pointer"}}),_.jsx(db,{children:(f||l)&&_.jsx("div",{style:{position:"absolute",transform:`translate(-50%, -50%) translate(${g}px, ${v}px)`,pointerEvents:"all"},className:"nodrag nopan",onMouseEnter:()=>p(!0),onMouseLeave:()=>p(!1),children:_.jsx("button",{type:"button",onClick:e=>{e.stopPropagation(),u({type:"remove_edge",edgeId:t})},className:"inline-flex items-center justify-center rounded-full bg-background border border-border text-muted-foreground hover:text-destructive hover:border-destructive/60 w-5 h-5 shadow transition-colors",title:"删除连线",children:_.jsx(S,{className:"h-3 w-3"})})})})]})}},Qb={type:"deletable"};function ew({flow:e,dispatch:t,selectedNodeId:i,onSelect:s}){const r=h.useRef(null),n=Ay(),o=h.useMemo(()=>function(e){const t=new Map;if(0===e.nodes.length)return t;const i=new Map;for(const a of e.nodes)i.set(a.id,0);for(const a of e.edges)null!==a.target&&i.set(a.target,(i.get(a.target)??0)+1);const s=e.nodes.filter(e=>0===(i.get(e.id)??0)),r=new Set,n=s.map(e=>e.id);let o=1;for(;n.length>0;){const i=n.shift();if(r.has(i))continue;r.add(i),t.set(i,o++);const s=e.edges.filter(e=>e.source===i&&null!==e.target);for(const e of s)e.target&&!r.has(e.target)&&n.push(e.target)}for(const a of e.nodes)r.has(a.id)||t.set(a.id,o++);return t}(e),[e]),a=h.useMemo(()=>e.nodes.map(e=>({id:e.id,type:e.type,position:e.position,data:e,selected:e.id===i})),[e.nodes,i]),l=h.useMemo(()=>e.edges.filter(e=>null!==e.target).map(e=>({id:e.id,source:e.source,target:e.target,sourceHandle:"default"===e.sourceHandle?null:e.sourceHandle??null,type:"deletable"})),[e.edges]),c=h.useCallback(e=>{for(const r of e)"position"===r.type&&r.position?t({type:"move_node",nodeId:r.id,position:r.position}):"remove"===r.type?t({type:"remove_node",nodeId:r.id}):"select"===r.type&&(r.selected?s(r.id):i===r.id&&s(null))},[t,s,i]),d=h.useCallback(e=>{for(const i of e)"remove"===i.type&&t({type:"remove_edge",edgeId:i.id})},[t]),u=h.useCallback(e=>{if(!e.source||!e.target)return;const i="true"===e.sourceHandle||"false"===e.sourceHandle?e.sourceHandle:"default";t({type:"add_edge",source:e.source,sourceHandle:i,target:e.target})},[t]);return _.jsxs("div",{ref:r,className:"flex-1 h-full relative",onDragOver:e=>{e.preventDefault(),e.dataTransfer.dropEffect="move"},onDrop:e=>{e.preventDefault();const i=e.dataTransfer.getData("application/x-ccweb-flow-node");if(!i)return;const s=Yb(i,n.screenToFlowPosition({x:e.clientX,y:e.clientY}));t({type:"add_node",node:s})},children:[_.jsxs(cb,{nodes:a,edges:l,onNodesChange:c,onEdgesChange:d,onConnect:u,nodeTypes:Zb,edgeTypes:Jb,defaultEdgeOptions:Qb,deleteKeyCode:["Delete","Backspace"],fitView:!0,children:[_.jsx(Hb,{}),_.jsx(Lb,{}),_.jsx(bb,{})]}),_.jsx("div",{className:"absolute inset-0 pointer-events-none",children:e.nodes.map(e=>{const t=o.get(e.id);if(void 0===t)return null;const i=n.flowToScreenPosition({x:e.position.x,y:e.position.y});return i?_.jsxs("div",{className:"absolute text-xs text-muted-foreground font-mono bg-background/80 px-1 rounded",style:{left:i.x-4,top:i.y-16},children:["#",t]},`label-${e.id}`):null})})]})}const tw=/^[a-zA-Z_][a-zA-Z0-9_]*$/;function iw(e,t){const i="@"===t?/@\{([^}]*)\}/g:/\$\{([^}]*)\}/g,s=new Set,r=[];let n;for(;null!==(n=i.exec(e));){const e=n[1]??"";tw.test(e)&&!s.has(e)&&(s.add(e),r.push(e))}return r}function sw(e){return iw(e,"@")}function rw(e){return iw(e,"$")}class nw{constructor(e){a(this,"pos",0),this.tokens=e}parseExpr(){let e=this.parseTerm();for(;this.peek("op","&&")||this.peek("op","||");){const t=this.tokens[this.pos].value;this.pos++;const i=this.parseTerm();e="&&"===t?{kind:"and",left:e,right:i}:{kind:"or",left:e,right:i}}return e}parseTerm(){const e=this.parseAtom(),t=this.peekOp(["==","!=",">","<",">=","<="]);if(t){this.pos++;return{kind:"compare",op:t,left:e,right:this.parseAtom()}}return e}parseAtom(){const e=this.tokens[this.pos];if(!e)throw new Error("unexpected end of input");if("num"===e.kind)return this.pos++,{kind:"literal",value:e.value};if("str"===e.kind)return this.pos++,{kind:"literal",value:e.value};if("kw"===e.kind){this.pos++;return{kind:"literal",value:"true"===e.value||"false"!==e.value&&null}}if("ident"===e.kind)return this.pos++,{kind:"var",name:e.value};if("punc"===e.kind&&"("===e.value){this.pos++;const e=this.parseExpr(),t=this.tokens[this.pos];if(!t||"punc"!==t.kind||")"!==t.value)throw new Error("missing closing paren");return this.pos++,e}throw new Error(`unexpected token ${JSON.stringify(e)}`)}peek(e,t){const i=this.tokens[this.pos];return!!i&&(i.kind===e&&(void 0===t||i.value===t))}peekOp(e){const t=this.tokens[this.pos];return t&&"op"===t.kind&&e.includes(t.value)?t.value:null}ensureFullyConsumed(){if(this.pos<this.tokens.length)throw new Error(`extra tokens after parse: ${JSON.stringify(this.tokens[this.pos])}`)}}function ow(e){const t=function(e){const t=[];let i=0;for(;i<e.length;){const s=e[i];if(/\s/.test(s)){i++;continue}if('"'===s){const s=e.indexOf('"',i+1);if(-1===s)throw new Error(`unterminated string at position ${i}`);t.push({kind:"str",value:e.slice(i+1,s)}),i=s+1;continue}if(/[0-9]/.test(s)||"-"===s&&/[0-9]/.test(e[i+1]??"")){let r=i+("-"===s?1:0);for(;r<e.length&&/[0-9.]/.test(e[r]);)r++;const n=e.slice(i,r),o=Number(n);if(Number.isNaN(o))throw new Error(`invalid number "${n}"`);t.push({kind:"num",value:o}),i=r;continue}if(/[a-zA-Z_]/.test(s)){let s=i;for(;s<e.length&&/[a-zA-Z0-9_]/.test(e[s]);)s++;const r=e.slice(i,s);"true"===r||"false"===r||"null"===r?t.push({kind:"kw",value:r}):t.push({kind:"ident",value:r}),i=s;continue}const r=e.slice(i,i+2);if(["==","!=",">=","<=","&&","||"].includes(r))t.push({kind:"op",value:r}),i+=2;else if(">"!==s&&"<"!==s){if("("!==s&&")"!==s)throw new Error(`unexpected character '${s}' at position ${i}`);t.push({kind:"punc",value:s}),i+=1}else t.push({kind:"op",value:s}),i+=1}return t}(e);if(0===t.length)throw new Error("empty expression");const i=new nw(t),s=i.parseExpr();return i.ensureFullyConsumed(),s}const aw=/^[a-zA-Z_][a-zA-Z0-9_]*$/,lw=new Set(["claude-code","codex","qwen","gemini"]);function cw(e){const t=new Set,i=new Set(["true","false","null"]);let s=0;for(;s<e.length;){const r=e[s];if('"'===r){const t=e.indexOf('"',s+1);if(-1===t)break;s=t+1;continue}if(/[a-zA-Z_]/.test(r)){let r=s;for(;r<e.length&&/[a-zA-Z0-9_]/.test(e[r]);)r++;const n=e.slice(s,r);i.has(n)||t.add(n),s=r;continue}s++}return[...t]}function hw({flow:e,projectId:t,filename:i,dirty:s,runStatus:r,onSaved:n,onClose:o}){const[a,l]=h.useState(!1),[c,d]=h.useState(null),u="idle"===r||"completed"===r||"failed"===r||"cancelled"===r;return _.jsxs("header",{className:"border-b border-border bg-background px-3 py-2 flex items-center gap-2",children:[_.jsx(K,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7",onClick:o,title:"关闭编辑器",children:_.jsx(hi,{className:"h-4 w-4"})}),_.jsx("div",{className:"font-mono text-sm text-foreground truncate",children:i}),s&&_.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-amber-500 dark:bg-amber-400",title:"未保存的修改"}),_.jsx("div",{className:"flex-1"}),_.jsxs(K,{type:"button",size:"sm",onClick:async()=>{d(null);const s=function(e){const t=[];lw.has(e.adapter)||t.push({level:"error",message:`非法 adapter: ${e.adapter}`});const i=new Set;for(const s of e.variables)aw.test(s.key)||t.push({level:"error",message:`变量 key "${s.key}" 不是合法 identifier`,variableKey:s.key}),i.has(s.key)?t.push({level:"error",message:`变量 key "${s.key}" 重名(duplicate)`,variableKey:s.key}):i.add(s.key);for(const s of e.nodes)if("llm"===s.type){const e=sw(s.promptTemplate),r=rw(s.promptTemplate);for(const n of[...e,...r])i.has(n)||t.push({level:"error",message:`LLM 节点 ${s.id} 引用未声明变量 "${n}"`,nodeId:s.id})}else if("user_input"===s.type){0===s.fields.length&&t.push({level:"error",message:`用户输入节点 ${s.id} 至少需要 1 个字段(空列表会让运行时弹一个没字段的 dialog)`,nodeId:s.id});const e=new Set;for(const r of s.fields)i.has(r.varKey)||t.push({level:"error",message:`用户输入节点 ${s.id} 字段引用未声明变量 "${r.varKey}"`,nodeId:s.id}),e.has(r.varKey)?t.push({level:"error",message:`用户输入节点 ${s.id} 字段 "${r.varKey}" 重复(dialog 会渲染两个同 key 输入,后者覆盖前者)`,nodeId:s.id}):e.add(r.varKey)}else if("if"===s.type){let e=!0;try{ow(s.conditionExpr)}catch(ll){e=!1,t.push({level:"error",message:`if 节点 ${s.id} 条件表达式语法错误:${ll.message}`,nodeId:s.id})}if(e||!1===e)for(const r of cw(s.conditionExpr))i.has(r)||t.push({level:"error",message:`if 节点 ${s.id} 条件引用未声明变量 "${r}"`,nodeId:s.id})}{const i=new Set;for(const s of e.nodes)i.has(s.id)?t.push({level:"error",message:`节点 id 重复:"${s.id}"(运行时只会执行其中一个)`,nodeId:s.id}):i.add(s.id)}for(const s of e.nodes)"llm"===s.type&&s.promptTemplate.length>65536&&t.push({level:"warning",message:`LLM 节点 ${s.id} promptTemplate 较长(${(s.promptTemplate.length/1024).toFixed(1)}KB),Ink TUI 大段 paste 行为不可预测`,nodeId:s.id});{const i=new Map;for(const t of e.edges){const e=t.sourceHandle??"default",s=`${t.source}::${e}`,r=i.get(s)??[];r.push(t.target??"(end)"),i.set(s,r)}for(const[e,s]of i)if(s.length>1){const[i,r]=e.split("::");t.push({level:"error",message:`节点 ${i} 的 ${r} 出口连了 ${s.length} 条边(${s.join(", ")}),运行时只会走第一条`,nodeId:i})}}if(0===e.nodes.length)t.push({level:"error",message:"空 flow(无任何节点 / 缺入口)"});else{const i=new Map;for(const t of e.nodes)i.set(t.id,0);for(const t of e.edges)null!==t.target&&i.set(t.target,(i.get(t.target)??0)+1);const s=e.nodes.filter(e=>0===(i.get(e.id)??0));0===s.length?t.push({level:"error",message:"无入口节点(图中存在环且无 in-degree=0 节点)"}):s.length>1&&t.push({level:"error",message:`多入口节点(不允许):${s.map(e=>e.id).join(", ")}`})}return{ok:0===t.filter(e=>"error"===e.level).length,errors:t}}(e);if(s.ok){l(!0);try{const s=us(e.variables);await os(t,i,e,s),n()}catch(ll){d(`保存失败:${ll.message}`)}finally{l(!1)}}else d(`无法保存:${s.errors.map(e=>e.message).join("; ")}`)},disabled:a,children:[_.jsx(Bt,{className:"h-3.5 w-3.5 mr-1"}),a?"保存中…":"保存"]}),u?_.jsxs(K,{type:"button",size:"sm",onClick:()=>{s?m.error("请先保存"):window.dispatchEvent(new CustomEvent("ccweb:flow-run-request",{detail:{filename:i}}))},disabled:s,title:s?"请先保存":"运行工作轨",className:"bg-emerald-600 text-white hover:bg-emerald-700 dark:bg-emerald-600 dark:hover:bg-emerald-500",children:[_.jsx(ki,{className:"h-3.5 w-3.5 mr-1 fill-current"}),"运行"]}):_.jsxs(K,{type:"button",variant:"destructive",size:"sm",onClick:()=>{window.dispatchEvent(new CustomEvent("ccweb:flow-cancel-request"))},children:[_.jsx(ji,{className:"h-3.5 w-3.5 mr-1 fill-current"}),"取消"]}),c&&_.jsx("div",{className:"text-xs text-destructive ml-2 max-w-md truncate",title:c,children:c})]})}const dw=/^[a-zA-Z_][a-zA-Z0-9_]*$/;function uw({value:e,onChange:t,placeholder:i}){const[s,r]=h.useState(!1),n=dw.test(e)||""===e;return _.jsxs("div",{children:[_.jsx(q,{type:"text",value:e,placeholder:i,onChange:e=>t(e.target.value),onBlur:()=>r(!0),className:g("h-8 text-sm font-mono",s&&!n&&"border-destructive focus-visible:ring-destructive")}),s&&!n&&_.jsx("div",{className:"text-xs text-destructive mt-1",children:"仅允许字母/数字/下划线,不能以数字开头"})]})}function fw({flow:e}){const t=Ub();return _.jsxs("aside",{className:"w-72 border-r border-border bg-background p-3 overflow-y-auto",children:[_.jsxs("div",{className:"flex items-center justify-between mb-2",children:[_.jsx("div",{className:"text-sm font-medium text-foreground",children:"变量声明"}),_.jsxs(K,{type:"button",variant:"outline",size:"sm",onClick:()=>{const i=`var${e.variables.length+1}`;t({type:"add_variable",variable:{key:i,description:"",initialValue:null}})},className:"h-7 px-2 text-xs",children:[_.jsx(V,{className:"h-3 w-3 mr-1"}),"新增"]})]}),0===e.variables.length&&_.jsx("div",{className:"text-xs text-muted-foreground",children:"(无变量)"}),_.jsx("div",{className:"space-y-2",children:e.variables.map((e,i)=>_.jsx(pw,{variable:e,dispatch:t},i))})]})}function pw({variable:e,dispatch:t}){const i=c(),s=i=>{t({type:"update_variable",key:e.key,patch:i})},r=e=>{if(""===e||"null"===e)return null;if("true"===e)return!0;if("false"===e)return!1;const t=Number(e);return!Number.isNaN(t)&&/^[0-9.+-]+$/.test(e)?t:e};return _.jsxs("div",{className:"border border-border rounded-md p-2 bg-muted/40 space-y-1",children:[_.jsxs("div",{className:"flex gap-1 items-start",children:[_.jsx("div",{className:"flex-1",children:_.jsx(uw,{value:e.key,onChange:i=>{i!==e.key&&t({type:"update_variable",key:e.key,patch:{key:i}})},placeholder:"变量名"})}),_.jsx(K,{type:"button",variant:"ghost",size:"icon",onClick:()=>{(async()=>{await i({description:`删除变量 "${e.key}"?`,confirmLabel:"删除",destructive:!0})&&t({type:"remove_variable",key:e.key})})()},title:"删除",className:"h-6 w-6 text-muted-foreground hover:text-destructive",children:_.jsx(S,{className:"h-3 w-3"})})]}),_.jsx(q,{type:"text",value:e.description,onChange:e=>s({description:e.target.value}),placeholder:"变量描述(含义)",className:"h-8 text-sm"}),_.jsx(q,{type:"text",value:(n=e.initialValue,null==n?"":"string"==typeof n?n:JSON.stringify(n)),onChange:e=>s({initialValue:r(e.target.value)}),placeholder:"初始值(可空)",className:"h-8 text-sm font-mono"})]});var n}const mw=h.forwardRef(({className:e,...t},i)=>_.jsx("textarea",{className:g("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",e),ref:i,...t}));mw.displayName="Textarea";const _w=/^[a-zA-Z_][a-zA-Z0-9_]*$/;function gw({value:e,variables:t,onChange:i,onCreateVariable:s,rows:r=5,placeholder:n}){const o=h.useRef(null),[a,l]=h.useState(null),[c,d]=h.useState(!1),[u,f]=h.useState(""),[p,m]=h.useState(null),v=a?t.filter(e=>e.key.toLowerCase().includes(a.filter.toLowerCase())):[],y=!!s,x=v.length+(y?1:0),b=()=>l(null),w=t=>{var s,r;if(!o.current)return;const n=(null==(s=S.current)?void 0:s.startPos)??(null==a?void 0:a.startPos),l=(null==(r=S.current)?void 0:r.trigger)??(null==a?void 0:a.trigger);if(void 0===n||void 0===l)return;const c=e.slice(0,n),h=e.slice(o.current.selectionStart),d=`${l}{${t}}`;i(c+d+h);const u=c.length+d.length;setTimeout(()=>{o.current&&(o.current.focus(),o.current.setSelectionRange(u,u))},0),b(),S.current=null},S=h.useRef(null),C=()=>{a&&(S.current={startPos:a.startPos,trigger:a.trigger},f(a.filter||""),m(null),d(!0),b())},k=()=>{const e=u.trim();_w.test(e)?t.some(t=>t.key===e)?m(`变量 "${e}" 已存在`):(s&&s(e),d(!1),w(e)):m("变量名只允许字母/数字/下划线,且不能以数字开头")};return h.useEffect(()=>{if(!a)return;const e=e=>{o.current&&!o.current.contains(e.target)&&b()};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[a]),_.jsxs("div",{className:"relative",children:[_.jsx(mw,{ref:o,value:e,onChange:e=>{const t=e.target.value,s=e.target.selectionStart;i(t);const r=t[s-1];if("@"!==r&&"$"!==r||a){if(a){const e=t.slice(a.startPos+1,s);if(!/^[a-zA-Z0-9_]*$/.test(e))return void b();l({...a,filter:e,selectedIndex:0})}}else l({trigger:r,startPos:s-1,filter:"",selectedIndex:0})},onKeyDown:e=>{if(a)if("Escape"===e.key)e.preventDefault(),b();else if("ArrowDown"===e.key)e.preventDefault(),l({...a,selectedIndex:Math.min(a.selectedIndex+1,x-1)});else if("ArrowUp"===e.key)e.preventDefault(),l({...a,selectedIndex:Math.max(a.selectedIndex-1,0)});else if("Enter"===e.key||"Tab"===e.key){if(0===x)return;e.preventDefault();const t=a.selectedIndex;t<v.length?(S.current={startPos:a.startPos,trigger:a.trigger},w(v[t].key)):y&&C()}},rows:r,placeholder:n,className:"font-mono text-sm"}),a&&x>0&&_.jsxs("div",{className:"absolute left-0 right-0 top-full mt-1 max-h-60 overflow-y-auto rounded-md border border-border bg-popover text-popover-foreground shadow-md z-50",children:[v.map((e,t)=>_.jsxs("div",{className:g("px-2 py-1 cursor-pointer text-sm",t===a.selectedIndex?"bg-accent text-accent-foreground":"hover:bg-accent/50"),onMouseDown:t=>{t.preventDefault(),S.current={startPos:a.startPos,trigger:a.trigger},w(e.key)},onMouseEnter:()=>l({...a,selectedIndex:t}),children:[_.jsxs("span",{className:"font-mono",children:[a.trigger,e.key]}),e.description&&_.jsx("span",{className:"text-xs text-muted-foreground ml-2",children:e.description})]},e.key)),y&&_.jsx("div",{className:g("px-2 py-1 cursor-pointer text-sm border-t border-border text-primary",a.selectedIndex===v.length?"bg-accent":"hover:bg-accent/50"),onMouseDown:e=>{e.preventDefault(),C()},onMouseEnter:()=>l({...a,selectedIndex:v.length}),children:"+ 新建变量"})]}),_.jsx(se,{open:c,onOpenChange:e=>{e||(S.current=null,d(!1))},children:_.jsxs(re,{className:"max-w-sm",children:[_.jsxs(ne,{children:[_.jsx(oe,{children:"新建变量"}),_.jsx(ae,{children:"变量名只允许字母/数字/下划线,且不能以数字开头。"})]}),_.jsxs("div",{className:"space-y-2",children:[_.jsx(le,{htmlFor:"new-var-name",className:"text-xs text-muted-foreground",children:"变量名"}),_.jsx(q,{id:"new-var-name",autoFocus:!0,value:u,onChange:e=>{f(e.target.value),m(null)},onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),k())},placeholder:"例:query_topic",className:"font-mono"}),p&&_.jsx("div",{className:"text-xs text-destructive",children:p})]}),_.jsxs(ce,{children:[_.jsx(K,{variant:"outline",size:"sm",onClick:()=>{S.current=null,d(!1)},children:"取消"}),_.jsx(K,{size:"sm",onClick:k,children:"创建"})]})]})})]})}function vw({flow:e,selectedNodeId:t}){const i=Ub(),s=c(),r=e.nodes.find(e=>e.id===t)??null;return r?_.jsxs("aside",{className:"w-96 border-l border-border bg-background p-4 overflow-y-auto",children:[_.jsxs("div",{className:"text-xs text-muted-foreground mb-2",children:["节点 ID: ",_.jsx("span",{className:"font-mono",children:r.id})]}),_.jsxs("div",{className:"text-xs text-muted-foreground mb-3",children:["类型: ",yw(r.type)]}),_.jsxs("div",{className:"mb-3 space-y-1.5",children:[_.jsx(le,{className:"text-xs text-muted-foreground",children:"显示名(运行可视化用)"}),_.jsx(q,{type:"text",value:r.label??"",onChange:e=>{const t=e.target.value.trim();i({type:"update_node",nodeId:r.id,patch:{label:""===t?void 0:e.target.value}})},placeholder:`默认: ${yw(r.type)}`,className:"h-8 text-sm"})]}),"user_input"===r.type&&_.jsx(bw,{node:r,variables:e.variables,dispatch:i}),"llm"===r.type&&_.jsx(ww,{node:r,variables:e.variables,dispatch:i}),"if"===r.type&&_.jsx(Sw,{node:r,dispatch:i}),_.jsx("div",{className:"mt-6 pt-3 border-t border-border",children:_.jsxs(K,{type:"button",variant:"outline",size:"sm",onClick:async()=>{await s({description:`确定删除节点 "${r.id}"?相关连线一起删除。`,confirmLabel:"删除",destructive:!0})&&i({type:"remove_node",nodeId:r.id})},className:"w-full text-destructive hover:text-destructive hover:bg-destructive/10 border-destructive/40",children:[_.jsx(L,{className:"h-3.5 w-3.5 mr-1"}),"删除节点"]})})]}):_.jsx("aside",{className:"w-96 border-l border-border bg-background p-4 text-sm text-muted-foreground",children:"选中节点编辑字段"})}function yw(e){return"user_input"===e?"用户输入":"llm"===e?"LLM 调用":"逻辑判断"}const xw=["text","textarea","number","bool","enum"];function bw({node:e,variables:t,dispatch:i}){const s=t=>i({type:"update_node",nodeId:e.id,patch:t}),r=(t,i)=>s({fields:e.fields.map((e,s)=>s===t?{...e,...i}:e)});return _.jsxs("div",{className:"space-y-3",children:[_.jsx(le,{className:"text-xs text-muted-foreground",children:"绑定变量"}),0===e.fields.length&&_.jsx("div",{className:"text-xs text-muted-foreground",children:"(无字段)"}),e.fields.map((i,n)=>_.jsxs("div",{className:"border border-border rounded-md p-2 bg-muted/40 space-y-1.5",children:[_.jsxs("div",{className:"flex gap-1 items-center",children:[_.jsx("div",{className:"flex-1",children:_.jsxs(Zt,{value:i.varKey,onValueChange:e=>r(n,{varKey:e}),children:[_.jsx(Jt,{className:"h-8 text-sm",children:_.jsx(Qt,{})}),_.jsx(ei,{children:t.map(e=>_.jsxs(ti,{value:e.key,children:[_.jsx("span",{className:"font-mono",children:e.key}),e.description&&_.jsxs("span",{className:"text-muted-foreground",children:[" — ",e.description]})]},e.key))})]})}),_.jsx(K,{type:"button",variant:"ghost",size:"icon",onClick:()=>{return t=n,s({fields:e.fields.filter((e,i)=>i!==t)});var t},title:"移除字段",className:"h-7 w-7 text-muted-foreground hover:text-destructive",children:_.jsx(S,{className:"h-3 w-3"})})]}),_.jsxs(Zt,{value:i.uiHint??"text",onValueChange:e=>r(n,{uiHint:e}),children:[_.jsx(Jt,{className:"h-8 text-sm",children:_.jsx(Qt,{})}),_.jsx(ei,{children:xw.map(e=>_.jsx(ti,{value:e??"text",children:e},e))})]})]},n)),_.jsxs(K,{type:"button",variant:"outline",size:"sm",onClick:()=>{if(0===t.length)return void m.error("请先在左侧变量声明面板中添加变量");const i={varKey:t[0].key,uiHint:"text"};s({fields:[...e.fields,i]})},className:"h-7 text-xs",children:[_.jsx(V,{className:"h-3 w-3 mr-1"}),"添加字段"]})]})}function ww({node:e,variables:t,dispatch:i}){return _.jsxs("div",{className:"space-y-3",children:[_.jsxs("div",{className:"space-y-1.5",children:[_.jsx(le,{className:"text-xs text-muted-foreground",children:"Prompt 模板"}),_.jsx(gw,{value:e.promptTemplate,variables:t,onChange:t=>{var s;s={promptTemplate:t,inputs:sw(t),outputs:rw(t)},i({type:"update_node",nodeId:e.id,patch:s})},onCreateVariable:e=>{i({type:"add_variable",variable:{key:e,description:"",initialValue:null}})},rows:6,placeholder:"@{var} 引用输入,${var} 标记输出"})]}),_.jsxs("div",{className:"text-xs text-muted-foreground",children:["自动推导:",e.inputs.length," 输入(",e.inputs.join(", ")||"—",")/ ",e.outputs.length," 输出(",e.outputs.join(", ")||"—",")"]})]})}function Sw({node:e,dispatch:t}){return _.jsxs("div",{className:"space-y-3",children:[_.jsx(le,{className:"text-xs text-muted-foreground",children:"条件表达式"}),_.jsx(q,{type:"text",value:e.conditionExpr,onChange:i=>t({type:"update_node",nodeId:e.id,patch:{conditionExpr:i.target.value}}),placeholder:"例:has_error == true",className:"h-8 text-sm font-mono"}),_.jsx("div",{className:"text-xs text-muted-foreground",children:"支持:变量名、字面量(null/true/false/数字/字符串)、比较运算(==、!=、>、<、>=、<=)、逻辑(&& ||)。求值在 M2b 实现。"})]})}function Cw({flow:e,run:t}){return"idle"===t.status?null:_.jsxs("div",{className:"border-t border-border bg-muted/40 px-3 py-2 text-xs space-y-1 max-h-64 overflow-y-auto",children:[_.jsxs("div",{className:"flex items-center gap-2",children:[_.jsx("span",{className:"font-medium text-foreground",children:"运行状态:"}),_.jsx("span",{className:Ew(t.status),children:kw(t.status)}),t.runId&&_.jsx("span",{className:"text-muted-foreground font-mono",children:t.runId}),t.currentNodeId&&_.jsxs("span",{className:"text-foreground",children:["当前: ",t.currentNodeId]})]}),t.quota&&_.jsxs("div",{className:"flex gap-4 text-muted-foreground",children:[void 0!==t.quota.iterRemaining&&_.jsxs("span",{children:["节点剩余迭代: ",t.quota.iterRemaining]}),_.jsxs("span",{children:["LLM 调用剩余: ",t.quota.llmCallsRemaining]}),_.jsxs("span",{children:["运行剩余: ",Math.floor(t.quota.durationRemainingMs/1e3),"s"]})]}),t.error&&_.jsxs("div",{className:"text-destructive",children:["错误: ",t.error]}),_.jsxs("div",{className:"mt-2",children:[_.jsx("div",{className:"text-muted-foreground mb-1",children:"变量值实时:"}),_.jsx("div",{className:"font-mono space-y-0.5",children:e.variables.map(e=>_.jsxs("div",{className:"flex gap-2",children:[_.jsx("span",{className:"text-sky-700 dark:text-sky-300",children:e.key}),_.jsxs("span",{className:"text-muted-foreground",children:["(",e.description,")"]}),_.jsxs("span",{className:"text-foreground",children:["= ",Nw(t.vars[e.key]??null)]})]},e.key))})]})]})}function kw(e){switch(e){case"running":return"运行中";case"waiting_user_input":return"等待用户输入";case"completed":return"完成";case"failed":return"失败";case"cancelled":return"已取消";default:return e}}function Ew(e){switch(e){case"running":return"text-sky-600 dark:text-sky-400";case"waiting_user_input":return"text-amber-600 dark:text-amber-400";case"completed":return"text-emerald-600 dark:text-emerald-400";case"failed":return"text-destructive";default:return"text-muted-foreground"}}function Nw(e){return null==e?"null":"string"==typeof e?JSON.stringify(e):"number"==typeof e||"boolean"==typeof e?String(e):JSON.stringify(e)}const Mw={runId:null,status:"idle",nodeStates:new Map,vars:{},error:null,currentNodeId:null,pendingUserInput:null,quota:null};function jw({projectId:e,filename:t,isNew:i,runState:s,onClose:r,onDirtyChange:n}){const[o,a]=h.useReducer(Wb,function(e,t="claude-code"){return hs(e,t)}(t.replace(/\.flow$/,""))),[l,c]=h.useState(i?{kind:"ready"}:{kind:"loading"}),[d,u]=h.useState(null),[f,p]=h.useState(!1),m=s??Mw;h.useEffect(()=>{if(i)return;let s=!1;return(async()=>{try{const i=await ns(e,t);if(s)return;const r=ds(i.flow);if(!r.ok||!r.flow)return void c({kind:"error",message:`flow 解析失败:${r.reason}`});const n=i.trainJson?function(e,t){const i=new Set(e.variables.map(e=>e.key)),s=new Set(Object.keys(t)),r=[...i].filter(e=>!s.has(e)),n=[...s].filter(e=>!i.has(e));return{ok:0===r.length&&0===n.length,missingKeys:r,extraKeys:n}}(r.flow,i.trainJson):{ok:!0,missingKeys:[],extraKeys:[]};n.ok||c({kind:"desync",message:`train.json 与 variables 失同步(缺 ${n.missingKeys.length} / 多 ${n.extraKeys.length})`}),a({type:"replace",flow:r.flow}),n.ok&&c({kind:"ready"})}catch(ll){s||c({kind:"error",message:ll.message})}})(),()=>{s=!0}},[e,t,i]);const g=h.useRef(!1);h.useEffect(()=>{g.current?"ready"!==l.kind&&"desync"!==l.kind||p(!0):g.current=!0},[o]),h.useEffect(()=>{null==n||n(f)},[f,n]);if("loading"===l.kind)return _.jsx("div",{className:"flex items-center justify-center h-full bg-background text-muted-foreground",children:"加载中…"});const v="running"===m.status||"waiting_user_input"===m.status;return"error"===l.kind?_.jsxs("div",{className:"flex flex-col items-center justify-center h-full bg-background text-destructive gap-2 max-w-md mx-auto p-6",children:[_.jsx("div",{className:"font-medium",children:"加载失败"}),_.jsx("div",{className:"text-sm",children:l.message}),_.jsx(K,{onClick:r,variant:"outline",size:"sm",className:"mt-2",children:"关闭"})]}):_.jsx(tb,{children:_.jsx(Kb,{value:{dispatch:a,nodeStates:m.nodeStates},children:_.jsxs("div",{className:"flex flex-col h-full bg-background text-foreground",children:[_.jsx(hw,{flow:o,projectId:e,filename:t,dirty:f,runStatus:m.status,onSaved:()=>p(!1),onClose:()=>r()}),"desync"===l.kind&&_.jsxs("div",{className:"bg-amber-50 dark:bg-amber-950/40 border-b border-amber-200 dark:border-amber-900 px-3 py-1 text-xs text-amber-800 dark:text-amber-200",children:["⚠ ",l.message,"(保存时将以当前 variables 重新派生 train.json)"]}),_.jsxs("div",{className:"flex-1 flex overflow-hidden",children:[!v&&_.jsx(Xb,{}),!v&&_.jsx(fw,{flow:o}),_.jsx(ew,{flow:o,dispatch:a,selectedNodeId:d,onSelect:u}),!v&&_.jsx(vw,{flow:o,selectedNodeId:d})]}),_.jsx(Cw,{flow:o,run:m})]})})})}function Dw({projectId:e,filename:t,open:i,runState:s,onClose:r}){const n=c(),[o,a]=h.useState(!1),l=async()=>{if(o){if(!(await n({description:"未保存的修改将丢失。确认关闭吗?",confirmLabel:"关闭",destructive:!0})))return}window.dispatchEvent(new CustomEvent("ccweb:track-editor-closed")),r()};return _.jsx(se,{open:i,onOpenChange:e=>{e||l()},children:_.jsxs(re,{className:"max-w-[90vw] w-[90vw] h-[85vh] p-0 gap-0 flex flex-col overflow-hidden sm:rounded-lg [&>button.absolute]:hidden",onEscapeKeyDown:e=>{e.preventDefault(),l()},onPointerDownOutside:e=>{e.preventDefault(),l()},onInteractOutside:e=>{e.preventDefault()},children:[_.jsx(ne,{className:"sr-only",children:_.jsxs(oe,{children:["工作轨编辑器:",t]})}),_.jsx(jw,{projectId:e,filename:t,isNew:!1,runState:s,onClose:()=>{l()},onDirtyChange:a})]})})}function Rw({open:e,flow:t,pending:i,onSubmit:s,onCancel:r}){const[n,o]=h.useState({});h.useEffect(()=>{e&&o({})},[e,i.nodeId]);const a=(e,t)=>o(i=>({...i,[e]:t}));return _.jsx(se,{open:e,onOpenChange:e=>{e||r()},children:_.jsxs(mt,{children:[_.jsx(_t,{className:"z-[70]"}),_.jsxs(gt,{className:g("fixed left-[50%] top-[50%] z-[70] grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200","data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95","sm:rounded-xl"),children:[_.jsx(ne,{children:_.jsx(oe,{children:"需要您输入"})}),_.jsx("div",{className:"space-y-3",children:i.fields.map(e=>{const i=t.variables.find(t=>t.key===e.varKey),s=i?`${e.varKey}(${i.description})`:e.varKey,r=n[e.varKey]??"";return _.jsxs("div",{className:"space-y-1.5",children:[_.jsx(le,{className:"text-xs text-muted-foreground",children:s}),"textarea"===e.uiHint?_.jsx(mw,{value:r,onChange:t=>a(e.varKey,t.target.value),rows:4,className:"font-mono"}):"enum"===e.uiHint&&e.variants?_.jsxs(Zt,{value:r,onValueChange:t=>a(e.varKey,t),children:[_.jsx(Jt,{children:_.jsx(Qt,{placeholder:"(请选择)"})}),_.jsx(ei,{children:e.variants.map(e=>_.jsx(ti,{value:e,children:e},e))})]}):"number"===e.uiHint?_.jsx(q,{type:"number",value:r,onChange:t=>{const i=t.target.value;if(""===i)a(e.varKey,"");else{const t=Number(i);a(e.varKey,Number.isNaN(t)?i:t)}},className:"font-mono"}):"bool"===e.uiHint?_.jsxs("div",{className:"flex items-center gap-2",children:[_.jsx("input",{id:`flow-input-${e.varKey}`,type:"checkbox",checked:!!n[e.varKey],onChange:t=>a(e.varKey,t.target.checked),className:"h-4 w-4 accent-primary"}),_.jsx(le,{htmlFor:`flow-input-${e.varKey}`,className:"text-sm font-normal",children:n[e.varKey]?"是":"否"})]}):_.jsx(q,{type:"text",value:r,onChange:t=>a(e.varKey,t.target.value),className:"font-mono"})]},e.varKey)})}),_.jsxs(ce,{children:[_.jsx(K,{variant:"outline",size:"sm",onClick:r,children:"取消运行"}),_.jsx(K,{size:"sm",onClick:()=>{s(n)},children:"提交"})]})]})]})})}const Pw={runId:null,status:"idle",nodeStates:new Map,vars:{},error:null,currentNodeId:null,pendingUserInput:null,quota:null};function Lw(){const[e,t]=h.useState(Pw),i=h.useRef(null),s=h.useCallback(()=>{i.current=null,t(Pw)},[]),r=h.useCallback(e=>{i.current=e,t(t=>({...t,runId:e,status:"running",nodeStates:new Map,vars:{},error:null}))},[]),n=h.useCallback(e=>{var s;i.current=e.runId,t({runId:e.runId,status:e.status,nodeStates:new Map(Object.entries(e.nodeStates)),vars:e.snapshot,error:(null==(s=e.error)?void 0:s.message)??null,currentNodeId:e.currentNodeId,pendingUserInput:e.pendingUserInput??null,quota:e.quota??null})},[]);return h.useEffect(()=>{const e=e=>{const s=e.detail;(null==s?void 0:s.type)&&s.type.startsWith("flow_")&&i.current&&(s.runId&&s.runId!==i.current||t(e=>function(e,t){var i;const s=t.type;if("flow_started"===s)return{...e,status:"running",vars:t.initialVars??{}};if("flow_node_active"===s){const i=new Map(e.nodeStates);return i.set(t.nodeId,"active"),{...e,currentNodeId:t.nodeId,nodeStates:i,quota:t.quota??e.quota}}if("flow_node_completed"===s){const s=new Map(e.nodeStates);s.set(t.nodeId,"completed");const r=(null==(i=e.pendingUserInput)?void 0:i.nodeId)===t.nodeId;return{...e,nodeStates:s,pendingUserInput:r?null:e.pendingUserInput,status:r&&"waiting_user_input"===e.status?"running":e.status}}if("flow_node_failed"===s){const i=new Map(e.nodeStates);return t.nodeId&&i.set(t.nodeId,"failed"),{...e,status:"failed",nodeStates:i,error:t.reason??null,pendingUserInput:null}}if("flow_var_changed"===s)return{...e,vars:{...e.vars,[t.key]:t.value}};if("flow_user_input_required"===s)return{...e,status:"waiting_user_input",pendingUserInput:{nodeId:t.nodeId,fields:t.fields}};if("flow_done"===s)return{...e,status:"completed",currentNodeId:null,pendingUserInput:null};if("flow_cancelled"===s)return{...e,status:"cancelled",pendingUserInput:null};if("flow_error"===s)return{...e,status:"failed",error:t.message??"unknown",pendingUserInput:null};return e}(e,s)))};return window.addEventListener("ccweb:flow-msg",e),()=>window.removeEventListener("ccweb:flow-msg",e)},[]),{state:e,attachRunId:r,reset:s,hydrateFromBackend:n}}const Tw=200,Iw=520;const Bw=Object.freeze(Object.defineProperty({__proto__:null,ProjectPage:function(){const{id:e}=vt(),t=Je(),[i,s]=h.useState(null),[r,n]=h.useState(!0),[o,a]=h.useState(!1),[l,c]=h.useState(null),d=h.useCallback(e=>{c({filename:e})},[]),{state:u,attachRunId:f,reset:p,hydrateFromBackend:m}=Lw(),[v,y]=h.useState(null);h.useEffect(()=>{const e=e=>{const t=e.detail;(null==t?void 0:t.type)&&(t.type.startsWith("flow_")&&!t.runId||("flow_started"===t.type||"flow_user_input_required"===t.type?a(!0):"flow_done"!==t.type&&"flow_cancelled"!==t.type&&"flow_error"!==t.type&&"flow_node_failed"!==t.type||a(!1)))};return window.addEventListener("ccweb:flow-msg",e),()=>window.removeEventListener("ccweb:flow-msg",e)},[]),h.useEffect(()=>{if(!e)return;const t=e,i=e=>{const{filename:i}=e.detail??{};i&&(async()=>{var e;try{const e=ds((await ns(t,i)).flow);if(!e.ok||!e.flow)return void alert(`加载 flow 失败:${e.reason??"unknown"}`);y({filename:i,flow:e.flow});const{runId:s}=await function(e,t){return rs("POST",`/api/projects/${e}/track-flows/file/${encodeURIComponent(t)}/run`,{})}(t,i);f(s)}catch(ll){const s=ll;if(409===s.status&&"FLOW_ALREADY_RUNNING"===(null==(e=s.detail)?void 0:e.code)&&s.detail.runId){try{const e=await ls(t,s.detail.runId),i="pending"===e.status?"running":e.status;m({...e,status:i})}catch{f(s.detail.runId)}return}alert(`运行失败:${s.message}`),y(null)}})()},s=()=>{const e=null==v?void 0:v.filename;e&&as(t,e,u.runId??void 0).catch(()=>{})};return window.addEventListener("ccweb:flow-run-request",i),window.addEventListener("ccweb:flow-cancel-request",s),()=>{window.removeEventListener("ccweb:flow-run-request",i),window.removeEventListener("ccweb:flow-cancel-request",s)}},[e,f,m,u.runId,null==v?void 0:v.filename]),h.useEffect(()=>{if("completed"===u.status||"failed"===u.status||"cancelled"===u.status){const e=setTimeout(()=>{p(),y(null)},100);return()=>clearTimeout(e)}},[u.status,p]);const x=async t=>{if(e&&u.runId&&v)try{await function(e,t,i,s){return rs("POST",`/api/projects/${e}/track-flows/file/${encodeURIComponent(t)}/user_input`,{runId:i,values:s})}(e,v.filename,u.runId,t)}catch(ll){alert(`提交失败:${ll.message}`)}},[b,w]=he(E.panelFileTree,"true"),[S,C]=he(E.panelShortcuts,"true"),[k,N]=he(E.chatOverlay(e??""),"true"),M=h.useCallback(()=>N(e=>"true"===e?"false":"true"),[N]),[j,D]=h.useState([]),[R,P]=h.useState(!1),[L,T]=h.useState([]),B=h.useRef(0),O=h.useCallback(e=>{B.current+=1;const t={...e,seq:B.current};T(e=>{const i=[...e,t];return i.length>500?i.slice(-500):i})},[]),[A,z]=h.useState(null),W=h.useCallback(e=>O(e),[O]),F=h.useCallback(e=>O(e),[O]),U=h.useCallback(e=>{D(t=>{const i=[...t,e];return i.length>200?i.slice(-200):i})},[]),V=h.useCallback(()=>{D([]),z(null),P(!0)},[]),q=h.useCallback(()=>{P(!1)},[]),Y=h.useCallback(async e=>{var t,i;if(e.endsWith("\r")){const i=e.slice(0,-1);if(re.current){if("failed"===await re.current.sendCommand(i))throw new Error("chat send failed");return}const s=i.trimStart().startsWith("/")?i.replace(/\n/g,"\r")+"\r":yt(i);return void(null==(t=se.current)||t.sendTerminalInput(s))}null==(i=se.current)||i.sendTerminalInput(e)},[]),[X,G]=he(E.panelLeftWidth,String(224)),[Z,J]=he(E.panelRightWidth,String(208)),Q=parseInt(X,10)||224,ee=parseInt(Z,10)||208,te=h.useRef(null),ie=h.useRef(null),se=h.useRef(null),re=h.useRef(null);h.useEffect(()=>{const e=e=>{(e.ctrlKey||e.metaKey)&&"i"===e.key&&"terminal"!==(null==i?void 0:i.cliTool)&&(e.preventDefault(),M())};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[M,null==i?void 0:i.cliTool]);const ne=h.useRef(null);h.useEffect(()=>{const e=(null==i?void 0:i.cliTool)??null;e&&ne.current&&e!==ne.current&&(D([]),T([]),B.current=0,z(null)),ne.current=e},[null==i?void 0:i.cliTool]);const[oe,ae]=h.useState("terminal"),[le,ce]=h.useState(()=>window.innerWidth<768);h.useEffect(()=>{const e=()=>ce(window.innerWidth<768);return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]);const{fetchProjects:de,hasFetched:ue}=et();return h.useEffect(()=>{if(!e)return;(async()=>{ue||await de();const t=et.getState().projects.find(t=>t.id===e)??null;s(t),n(!1)})()},[e,ue,de]),r?_.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:_.jsx("span",{className:"text-muted-foreground text-sm",children:"Loading…"})}):i&&e?_.jsxs("div",{className:"h-screen flex flex-col bg-background",children:[_.jsx(zn,{project:i,projectId:e,showFileTree:"true"===b,showShortcuts:"true"===S,showChatOverlay:"true"===k,onToggleFileTree:()=>w(e=>"true"===e?"false":"true"),onToggleShortcuts:()=>C(e=>"true"===e?"false":"true"),onToggleChatOverlay:M,onProjectUpdate:s}),le?_.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col min-h-0",children:[_.jsxs("div",{className:"flex-1 overflow-hidden min-h-0",children:["files"===oe&&_.jsx(ys,{projectPath:i.folderPath,projectId:e,cliTool:i.cliTool,onSend:Y,onOpenTrackEditor:d}),"terminal"===oe&&_.jsx(pf,{ref:se,projectId:e,project:i,onStatusChange:e=>s(t=>t?{...t,status:e}:t)}),"panel"===oe&&_.jsx(Cn,{projectId:e,onSend:Y})]}),_.jsx("div",{className:"flex-shrink-0 flex border-t border-border bg-background pb-[env(safe-area-inset-bottom)]",children:[{id:"files",icon:I,label:"文件"},{id:"terminal",icon:xt,label:"终端"},{id:"panel",icon:Ci,label:"快捷"}].map(({id:e,icon:t,label:i})=>_.jsxs("button",{onClick:()=>ae(e),className:g("flex-1 flex flex-col items-center gap-0.5 py-2 text-[10px] transition-colors",oe===e?"text-blue-400":"text-muted-foreground hover:text-foreground"),children:[_.jsx(t,{className:"h-4 w-4"}),i]},e))})]}):_.jsxs("div",{className:"flex-1 overflow-hidden flex min-h-0",children:[_.jsx($,{initial:!1,children:"true"===b&&_.jsx(H.div,{ref:te,initial:{width:0,opacity:0},animate:{width:Q,opacity:1},exit:{width:0,opacity:0},transition:{duration:.2,ease:"easeInOut"},className:"flex-shrink-0 overflow-hidden",children:_.jsx(ys,{projectPath:i.folderPath,projectId:e,cliTool:i.cliTool,onSend:Y,onOpenTrackEditor:d})})}),"true"===b&&_.jsx("div",{onMouseDown:e=>{var t;e.preventDefault();const i=e.clientX,s=(null==(t=te.current)?void 0:t.offsetWidth)??Q;document.body.style.cursor="col-resize",document.body.style.userSelect="none";const r=e=>{const t=Math.max(Tw,Math.min(Iw,s+(e.clientX-i)));te.current&&(te.current.style.width=t+"px")},n=e=>{const t=Math.max(Tw,Math.min(Iw,s+(e.clientX-i)));G(String(t)),document.body.style.cursor="",document.body.style.userSelect="",window.removeEventListener("mousemove",r),window.removeEventListener("mouseup",n)};window.addEventListener("mousemove",r),window.addEventListener("mouseup",n)},className:"w-1 flex-shrink-0 bg-border hover:bg-blue-500/60 active:bg-blue-500/80 cursor-col-resize transition-colors"}),_.jsxs("div",{className:"flex-1 overflow-hidden min-w-0 relative flex flex-col",children:[_.jsx(gf,{projectId:e}),_.jsx(pf,{ref:se,projectId:e,project:i,onStatusChange:e=>s(t=>t?{...t,status:e}:t),onChatMessage:U,onWsConnected:V,onWsDisconnected:q,onApprovalRequest:W,onApprovalResolved:F,onSemanticUpdate:z}),_.jsx($,{children:"true"===k&&"terminal"!==i.cliTool&&_.jsx(It,{ref:re,projectId:e,project:i,liveMessages:j,approvalEvents:L,semanticUpdate:A,wsConnected:R,onSend:e=>{var t;return null==(t=se.current)?void 0:t.sendTerminalInput(e)},onClose:M,flowActive:o},"chat-overlay")})]}),"true"===S&&_.jsx("div",{onMouseDown:e=>{var t;e.preventDefault();const i=e.clientX,s=(null==(t=ie.current)?void 0:t.offsetWidth)??ee;document.body.style.cursor="col-resize",document.body.style.userSelect="none";const r=e=>{const t=Math.max(Tw,Math.min(Iw,s-(e.clientX-i)));ie.current&&(ie.current.style.width=t+"px")},n=e=>{const t=Math.max(Tw,Math.min(Iw,s-(e.clientX-i)));J(String(t)),document.body.style.cursor="",document.body.style.userSelect="",window.removeEventListener("mousemove",r),window.removeEventListener("mouseup",n)};window.addEventListener("mousemove",r),window.addEventListener("mouseup",n)},className:"w-1 flex-shrink-0 bg-border hover:bg-blue-500/60 active:bg-blue-500/80 cursor-col-resize transition-colors"}),_.jsx($,{initial:!1,children:"true"===S&&_.jsx(H.div,{ref:ie,initial:{width:0,opacity:0},animate:{width:ee,opacity:1},exit:{width:0,opacity:0},transition:{duration:.2,ease:"easeInOut"},className:"flex-shrink-0 overflow-hidden",children:_.jsx(Cn,{projectId:e,onSend:Y})})})]}),l&&_.jsx(Dw,{projectId:e,filename:l.filename,runState:(null==v?void 0:v.filename)===l.filename?u:null,open:!0,onClose:()=>c(null)}),u.pendingUserInput&&(null==v?void 0:v.flow)&&_.jsx(Rw,{open:!0,flow:v.flow,pending:u.pendingUserInput,onSubmit:e=>{x(e)},onCancel:()=>{(async()=>{if(e&&u.runId&&v){try{await as(e,v.filename,u.runId)}catch{}p(),y(null)}})()}})]}):_.jsxs("div",{className:"min-h-screen flex flex-col items-center justify-center gap-4 bg-background",children:[_.jsx("p",{className:"text-muted-foreground",children:"Project not found."}),_.jsxs(K,{variant:"outline",onClick:()=>t("/"),children:[_.jsx(qe,{className:"h-4 w-4 mr-2"}),"Back to Dashboard"]})]})}},Symbol.toStringTag,{value:"Module"}));export{Bw as P,Pi as Z,Li as a};