@oxbit/cli 0.3.4 → 0.4.0

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.
@@ -198,7 +198,7 @@ window.addEventListener("message", event => {
198
198
  window.addEventListener("load", () => send("oxbit.preview.ready"));
199
199
  `,w0t="sha256-baG6zrI9qQ7n/0Uu0tcqeYXQC5vQ8ZWJY9nJ2PK7KPs=",$Y=t=>/\.html?$/i.test(t);async function k0t(t){const{path:e,signal:r,trust:i="local"}=t,{text:s,resource:o,warnings:n}=SY(t),a=await s(e),l=DE.sanitize(a,{WHOLE_DOCUMENT:!0,ADD_TAGS:["link"],FORBID_TAGS:["script","iframe","frame","frameset","object","embed","base","meta"],FORBID_ATTR:["srcdoc","ping","action","formaction","target","autofocus","data-preview-href"]}),c=new DOMParser().parseFromString(l,"text/html");for(const b of c.querySelectorAll("style"))b.textContent=await ub(b.textContent??"",(v,_)=>o(e,v,_));for(const b of c.querySelectorAll("link")){if(b.rel.toLowerCase()==="stylesheet"){const v=c.createElement("style"),_=b.getAttribute("href")??"",$=kY(_,i);if($){b.setAttribute("href",$),b.setAttribute("referrerpolicy","no-referrer");continue}const A=Lk(e,_);if(A.kind==="file")try{v.textContent=await ub(await s(A.path),(y,E)=>o(A.path,y,E,[A.path])),b.media&&(v.media=b.media),b.replaceWith(v);continue}catch(y){r.throwIfAborted(),n.add(`Could not load ${A.path}: ${y instanceof Error?y.message:String(y)}`)}else n.add("External resources are blocked. Use the External resources control to allow them for this preview.")}b.remove()}for(const b of c.querySelectorAll("[style]"))b.setAttribute("style",await ub(b.getAttribute("style"),(v,_)=>o(e,v,_)));for(const b of c.querySelectorAll("[src], [poster], image[href], image[xlink\\:href]"))for(const v of["src","poster","href","xlink:href"]){const _=b.getAttribute(v);_!==null&&b.setAttribute(v,await o(e,_))}for(const b of c.querySelectorAll("[srcset]")){const v=b.getAttribute("srcset");if(!v.trim().startsWith("data:")){const _=[];for(const $ of v.split(",")){const[A,...y]=$.trim().split(/\s+/);_.push(`${await o(e,A??"")} ${y.join(" ")}`.trim())}b.setAttribute("srcset",_.join(", "))}}for(const b of c.querySelectorAll("a[href], area[href]"))b.setAttribute("data-preview-href",b.getAttribute("href")),b.setAttribute("href","#"),b.removeAttribute("download");const h=c.createElement("meta");h.httpEquiv="Content-Security-Policy",h.content=`default-src 'none'; script-src '${w0t}'; ${m0t(i)}; base-uri 'none'; form-action 'none'`;const d=c.createElement("meta");d.name="viewport",d.content="width=device-width, initial-scale=1";const p=c.createElement("meta");p.name="referrer",p.content="no-referrer",c.head.prepend(h,d,p);const g=c.createElement("script");return g.textContent=b0t,g.dataset.path=e,c.head.append(g),r.throwIfAborted(),{html:`<!doctype html>
200
200
  `+c.documentElement.outerHTML,warnings:[...n],trust:i,scripts:/<script\b|\son\w+\s*=/i.test(a)}}function v0t(t){return function({path:r}){const[i,s]=j.useState([r]),o=i[i.length-1],[n,a]=j.useState(0),[l,c]=j.useState("local"),[h,d]=j.useState(),[p,g]=j.useState(""),[b,v]=j.useState(!0),[_,$]=j.useState(!1),A=j.useRef(new Set([o])),y=j.useRef({path:o,top:0}),E=j.useRef(null),C=j.useRef(void 0);j.useEffect(()=>{let m;const w=()=>{clearTimeout(m),m=setTimeout(()=>a(F=>F+1),200)},P=t.kernel.events.on("document.change",({id:F})=>{[...A.current].some(X=>t.documents.get(X)?.id===F)&&w()}),R=t.filesystem.watch(F=>{A.current.has(F.path)&&w()});return()=>{clearTimeout(m),P.dispose(),R.dispose()}},[]),j.useEffect(()=>{const m=new AbortController;return A.current=new Set([o]),y.current.path!==o&&(y.current={path:o,top:0}),v(!0),g(""),k0t({path:o,trust:l,filesystem:t.filesystem,signal:m.signal,dependencies:A.current,readText:async w=>{const P=t.documents.get(w);if(P?.state==="missing")throw new Error(D("File no longer exists"));return P?P.text.toString():(await t.filesystem.read(w)).text}}).then(w=>{m.signal.aborted||(d(w),v(!1))}).catch(w=>{m.signal.aborted||(g(w instanceof Error?w.message:String(w)),v(!1))}),()=>m.abort()},[o,n,l]),j.useEffect(()=>{const m=()=>{E.current?.contentWindow?.postMessage({type:"oxbit.preview.restore",top:y.current.top,anchor:C.current},"*"),C.current=void 0},w=P=>{if(P.source!==E.current?.contentWindow||P.origin!=="null"||P.data?.path!==o||(P.data.type==="oxbit.preview.ready"&&m(),P.data.type==="oxbit.preview.scroll"&&Number.isFinite(P.data.top)&&(y.current.top=Math.max(0,P.data.top)),P.data.type!=="oxbit.preview.link"||typeof P.data.href!="string"))return;const R=Lk(o,P.data.href);R.kind==="anchor"||R.kind==="file"&&R.path===o&&R.anchor?(C.current=R.kind==="anchor"?R.id:R.anchor,m()):R.kind==="file"&&$Y(R.path)?(C.current=R.anchor,s(F=>[...F,R.path])):R.kind==="file"?Promise.resolve(t.workbench.openFile(R.path)).catch(F=>t.workbench.notify(String(F),"error")):R.kind==="external"?window.open(R.url,"_blank","noopener,noreferrer"):t.workbench.notify(R.reason,"warning")};return window.addEventListener("message",w),()=>window.removeEventListener("message",w)},[o]);const k=()=>{Promise.resolve(t.workbench.openFile(o,{preview:!1})).catch(m=>t.workbench.notify(String(m),"error"))};return x.jsxs("div",{className:"html-document","aria-busy":b,children:[x.jsxs("div",{className:"preview-toolbar html-preview-toolbar",children:[i.length>1&&x.jsx(Xe,{icon:"chevR",className:"icon-button html-preview-back",label:D("Back in HTML preview"),onClick:()=>s(m=>m.slice(0,-1))}),x.jsx("span",{className:"truncate",title:o,role:"status",children:b?D("Loading preview…"):o.split("/").pop()}),x.jsx(Xe,{icon:"refresh",label:D("Refresh HTML preview"),onClick:()=>a(m=>m+1)}),x.jsx(Xe,{icon:"pencil",label:D("Open source"),onClick:k}),x.jsx(Xe,{icon:"gear",className:"icon-button html-preview-options-trigger",label:D("Preview options"),"data-warning":!!h?.warnings.length,"aria-haspopup":"dialog","aria-expanded":_,onClick:m=>{m.currentTarget.focus({preventScroll:!0}),$(!0)}})]}),p&&x.jsx("div",{className:"html-preview-message error-text",role:"alert",children:p}),_&&x.jsxs(Mo,{title:D("Preview options"),className:"html-preview-options",onClose:()=>$(!1),children:[x.jsx(xY,{trust:l,onChange:c}),h?.scripts&&x.jsx("p",{className:"muted",children:D("HTML & CSS preview · JavaScript is disabled")}),!!h?.warnings.length&&x.jsxs("details",{className:"html-preview-warnings",children:[x.jsx("summary",{children:D("Some preview resources could not be loaded")}),h.warnings.map(m=>x.jsx("p",{children:D(m)},m))]})]}),h&&h.trust===l&&!p&&x.jsx("iframe",{ref:E,className:"html-preview-frame",title:D("HTML preview"),sandbox:"allow-scripts",referrerPolicy:"no-referrer",srcDoc:h.html})]})}}const _Y={mp3:"audio/mpeg",wav:"audio/wav",wave:"audio/wav",m4a:"audio/mp4",aac:"audio/aac",flac:"audio/flac",ogg:"audio/ogg",oga:"audio/ogg",opus:"audio/ogg; codecs=opus",aif:"audio/aiff",aiff:"audio/aiff",weba:"audio/webm"};function AM(t,e){return function({path:i}){const[s,o]=j.useState(),[n,a]=j.useState(""),[l,c]=j.useState(0),h=i.split("/").pop()||i,d=e==="pdf"?"application/pdf":_Y[h.split(".").pop().toLowerCase()],p=t.kernel.commands.list().find(b=>b.id==="desktop.reveal"),g=p&&t.kernel.contributions.list("menu").some(b=>b.id==="desktop.reveal.explorer");return j.useEffect(()=>{const b=new AbortController;let v="";return o(void 0),a(""),(async()=>{if(!t.filesystem.readBytes)throw new Error(D("This workspace cannot read media files"));const _=await t.filesystem.readBytes(i,b.signal);if(!b.signal.aborted){if(e==="pdf"&&!new TextDecoder().decode(_.subarray(0,1024)).includes("%PDF-"))throw new Error(D("This file is not a PDF document."));v=URL.createObjectURL(new Blob([_],{type:d})),o({url:v,bytes:_.byteLength})}})().catch(_=>{b.signal.aborted||a(_ instanceof Error?_.message:String(_))}),()=>{b.abort(),v&&URL.revokeObjectURL(v)}},[i,d,l]),j.useEffect(()=>{const b=t.filesystem.watch(v=>{v.path===i&&c(_=>_+1)});return()=>b.dispose()},[i]),x.jsxs("div",{className:"media-document",children:[x.jsxs("div",{className:"preview-toolbar",children:[x.jsx("span",{className:"truncate",title:i,children:h}),x.jsx("span",{className:"push"}),g&&x.jsx("button",{className:"button",onClick:()=>{t.kernel.commands.execute("desktop.reveal",{path:i}).catch(b=>t.workbench.notify(String(b),"error"))},children:D(p.title)}),s&&!p&&x.jsx("a",{className:"button",href:s.url,download:h,children:D("Download")}),x.jsx(Xe,{icon:"refresh",label:"Reload preview",onClick:()=>c(b=>b+1)})]}),n?x.jsxs(qd,{title:D(e==="pdf"?"PDF unavailable":"Audio unavailable"),children:[x.jsx("p",{role:"alert",children:n}),x.jsx("button",{className:"button",onClick:()=>c(b=>b+1),children:D("Retry")})]}):s?e==="pdf"?x.jsxs(x.Fragment,{children:[x.jsx("iframe",{className:"pdf-preview",title:D("PDF preview"),src:s.url}),!p&&x.jsx("p",{className:"media-hint",children:D("If the PDF does not display, download it to open in your PDF reader.")})]}):x.jsxs("div",{className:"audio-preview",children:[x.jsx(Fe,{name:"play",size:48}),x.jsx("h2",{children:h}),x.jsx("p",{className:"muted",children:`${(s.bytes/1024/1024).toFixed(2)} MB`}),x.jsx("audio",{controls:!0,preload:"metadata",src:s.url,"aria-label":h,onError:()=>a(D("This audio file is damaged or its codec is not supported by this device."))},s.url)]}):x.jsx("p",{className:"muted",role:"status",children:D("Loading preview…")})]})}}const AY=new PE({html:!1,linkify:!0,typographer:!1});AY.renderer.rules.heading_open=(t,e,r,i,s)=>{const o=t[e+1]?.content||"",n=vY(o),a=i.headings,l=a.get(n)||0;return a.set(n,l+1),t[e].attrSet("id",n+(l?"-"+l:"")),t[e].map&&t[e].attrSet("data-source-line",String(t[e].map[0])),s.renderToken(t,e,r)};function S0t(t,e=!1){return DE.sanitize(AY.render(t,{headings:new Map}),{FORBID_TAGS:["style","script","iframe","object","embed","form","input","video","audio",...e?[]:["img"]],FORBID_ATTR:["style","srcset","target"],ALLOW_DATA_ATTR:!1,ADD_ATTR:["data-source-line"]})}async function x0t(t){const{text:e,resource:r,warnings:i}=SY(t),s=document.createElement("template");s.innerHTML=S0t(await e(t.path),!0);for(const o of s.content.querySelectorAll("img"))o.setAttribute("src",await r(t.path,o.getAttribute("src")??"")),o.setAttribute("referrerpolicy","no-referrer");return t.signal.throwIfAborted(),{html:s.innerHTML,warnings:[...i]}}function $0t(t){const e=new Set,r=v0t(t),i=AM(t,"pdf"),s=AM(t,"audio");function o({path:l}){const[c,h]=j.useState("local"),[d,p]=j.useState({html:"",warnings:[],trust:c}),[g,b]=j.useState(""),v=j.useRef(null),_=j.useRef(new Set([l]));return j.useEffect(()=>{let $=!1,A=0,y=0,E,C=!1;const k=v.current;let m;const w=()=>{m?.abort(),cancelAnimationFrame(A),A=requestAnimationFrame(()=>{if($)return;const N=new AbortController;m=N,_.current=new Set([l]),x0t({path:l,trust:c,signal:N.signal,filesystem:t.filesystem,dependencies:_.current,readText:async U=>{const K=t.documents.get(U);if(K?.state==="missing")throw new Error(D("File no longer exists"));return K?K.text.toString():(await t.filesystem.read(U)).text}}).then(U=>{N.signal.aborted||(p({...U,trust:c}),b(""))}).catch(U=>{N.signal.aborted||b(String(U))})})};t.documents.open(l).then(w).catch(N=>{$||b(String(N))});const P=t.kernel.events.on("document.change",({id:N})=>{[..._.current].some(U=>t.documents.get(U)?.id===N)&&w()}),R=t.filesystem.watch(N=>{_.current.has(N.path)&&w()}),F=(N,U)=>{C||(C=!0,U.scrollTop=g0t(N)*Math.max(0,U.scrollHeight-U.clientHeight),cancelAnimationFrame(y),y=requestAnimationFrame(()=>{C=!1}))},X=()=>{E&&k&&F(E,k)},te=()=>{E&&k&&F(k,E)},H=()=>{const N=t.workbench.editorForPath(l)?.scrollDOM;E!==N&&(E?.removeEventListener("scroll",X),E=N,E?.addEventListener("scroll",X,{passive:!0}))},W=t.kernel.events.on("editor.active",()=>requestAnimationFrame(H));return requestAnimationFrame(H),k?.addEventListener("scroll",te,{passive:!0}),()=>{$=!0,m?.abort(),cancelAnimationFrame(A),cancelAnimationFrame(y),P.dispose(),R.dispose(),W.dispose(),E?.removeEventListener("scroll",X),k?.removeEventListener("scroll",te)}},[l,c]),Ae.createElement("div",{className:"markdown-document"},Ae.createElement("div",{className:"preview-toolbar"},Ae.createElement("span",null,l),Ae.createElement("button",{className:"button",onClick:()=>{t.workbench.openFile(l,{preview:!1})}},D("Open source"))),Ae.createElement(xY,{trust:c,onChange:h}),d.trust===c&&d.warnings.length>0&&Ae.createElement("details",{className:"html-preview-message"},Ae.createElement("summary",null,D("Some preview resources could not be loaded")),...d.warnings.map($=>Ae.createElement("p",{key:$},D($)))),g&&Ae.createElement("p",{role:"alert",className:"error-text"},g),Ae.createElement("article",{ref:v,className:"markdown-preview",tabIndex:0,"aria-label":D("Markdown preview"),onClick:$=>{const A=$.target.closest("a");if(!A)return;$.preventDefault();const y=Lk(l,A.getAttribute("href")||"");if(y.kind==="blocked"){t.workbench.notify(y.reason,"warning");return}if(y.kind==="external"){window.open(y.url,"_blank","noopener,noreferrer");return}if(y.kind==="anchor"){v.current?.querySelector("#"+CSS.escape(y.id))?.scrollIntoView();return}(async()=>{let E;y.anchor&&(E=(await t.documents.open(y.path)).text.toString().split(`
201
- `).findIndex(k=>/^#{1,6}\s/.test(k)&&vY(k.replace(/^#{1,6}\s+/,""))===y.anchor)+1,E||(E=void 0)),await t.workbench.openFile(y.path,{line:E})})().catch(E=>t.workbench.notify(String(E),"error"))},dangerouslySetInnerHTML:{__html:d.trust===c&&!g?d.html:""}}))}const n=async(l=!1)=>{const c=t.workbench.activePath();if(!c||!/\.md$/i.test(c))throw new Error("Open a Markdown document first");let h;if(l&&(h=t.workbench.split("row"),!h))return;const d="preview:"+c;e.add(d),t.workbench.openView(d,D("{0} Preview",{0:c.split("/").pop()}),o,{path:c},{groupId:h,path:c,contributionId:"markdown.preview"})},a=(l=!1)=>{const c=t.workbench.activePath();if(!c||!$Y(c))throw new Error("Open an HTML document first");const h=l?t.workbench.split("row"):void 0;if(l&&!h)return;const d="html-preview:"+c;e.add(d),t.workbench.openView(d,D("{0} Preview",{0:c.split("/").pop()}),r,{path:c},{groupId:h,path:c,contributionId:"html.preview"})};return{manifest:{manifestVersion:1,id:"oxbit.previews",name:"Document & Media Previews",description:"Markdown and HTML/CSS previews, PDF viewing, and audio playback for MP3, WAV, M4A, FLAC, Ogg, and more.",version:"1.0.0",sdk:"^1.0.0",environments:["browser","embedded"],activation:["*"],capabilities:["filesystem.read"]},activate(l){l.own(l.contributions.register({id:"pdf.preview",kind:"documentView",title:"PDF Viewer",component:i,data:{binary:!0,extensions:["pdf"]}})),l.own(l.contributions.register({id:"audio.preview",kind:"documentView",title:"Audio Player",component:s,data:{binary:!0,extensions:Object.keys(_Y)}})),l.own(l.contributions.register({id:"html.preview",kind:"documentView",title:"HTML preview",component:r})),l.own(l.commands.register({id:"preview.html",title:"Open HTML Preview",when:"html",shortcut:"Ctrl+Shift+V",run:()=>a()})),l.own(l.commands.register({id:"preview.htmlSide",title:"Open HTML Preview to the Side",when:"html",shortcut:"Ctrl+K V",run:()=>a(!0)})),l.own(l.contributions.register({id:"markdown.preview",kind:"documentView",title:"Markdown preview",component:o})),l.own(l.commands.register({id:"preview.markdown",title:"Open Markdown Preview",when:"markdown",shortcut:"Ctrl+Shift+V",run:()=>n()})),l.own(l.commands.register({id:"preview.markdownSide",title:"Open Markdown Preview to the Side",when:"markdown",shortcut:"Ctrl+K V",run:()=>n(!0)})),l.own(l.commands.register({id:"preview.toggle",title:"Toggle Markdown Preview",when:"markdown",run:()=>{const c=t.workbench.activePath();return c&&!t.workbench.activeEditor()?(t.workbench.closeView("preview:"+c),t.workbench.openFile(c,{preview:!1})):n()}})),l.subscribe(()=>{for(const c of e)t.workbench.closeView(c);e.clear()})}}}const CY={apng:"image/apng",avif:"image/avif",bmp:"image/bmp",gif:"image/gif",ico:"image/x-icon",jfif:"image/jpeg",jpe:"image/jpeg",jpeg:"image/jpeg",jpg:"image/jpeg",png:"image/png",svg:"image/svg+xml",webp:"image/webp"},_0t=Object.keys(CY);function TY(t){const e=t.toLowerCase().split("/").pop()??"",r=e.lastIndexOf(".");return r>0?CY[e.slice(r+1)]:void 0}function CM(t){return TY(t)==="image/svg+xml"}const om=[.1,.25,.5,.75,1,1.5,2,3,4,6,8,12,16];function A0t(t,e){const r=om[0],i=om[om.length-1];return e>0?om.find(s=>s>t+1e-6)??Math.max(t,i):[...om].reverse().find(s=>s<t-1e-6)??Math.min(t,r)}function C0t(t,e){return t.width<=0||t.height<=0||e.width<=0||e.height<=0?1:Math.min(1,e.width/t.width,e.height/t.height)}function T0t(t){const e=["B","KB","MB"];let r=t,i=0;for(;r>=1024&&i<e.length-1;)r/=1024,i++;return`${i===0?r:r.toFixed(r<10?1:0)} ${e[i]}`}function P0t(t){const e=t*100;return`${e<10?e.toFixed(1):Math.round(e)}%`}const E0t="oxbit.images.view";function Q0t(t){const e=async i=>{t.workbench.closeView(i),await t.workbench.openFile(i,{text:!0,preview:!1})};function r({path:i}){const[s,o]=j.useState(),[n,a]=j.useState(""),[l,c]=j.useState(),[h,d]=j.useState("fit"),[p,g]=j.useState({width:0,height:0}),[b,v]=j.useState(0),_=j.useRef(null);j.useEffect(()=>{const E=new AbortController;let C="";return o(void 0),a(""),c(void 0),(async()=>{if(!t.filesystem.readBytes)throw new Error(D("This workspace cannot read image files"));const k=await t.filesystem.readBytes(i,E.signal);E.signal.aborted||(C=URL.createObjectURL(new Blob([k],{type:TY(i)})),o({url:C,bytes:k.byteLength}))})().catch(k=>{E.signal.aborted||a(k instanceof Error?k.message:String(k))}),()=>{E.abort(),C&&URL.revokeObjectURL(C)}},[i,b]),j.useEffect(()=>{const E=t.filesystem.watch(C=>{C.path===i&&C.kind==="changed"&&v(k=>k+1)});return()=>E.dispose()},[i]),j.useEffect(()=>{const E=_.current;if(!E||typeof ResizeObserver>"u")return;const C=new ResizeObserver(([k])=>g({width:k.contentRect.width,height:k.contentRect.height}));return C.observe(E),()=>C.disconnect()},[]);const $=l?h==="fit"?C0t(l,p):h:1,A=j.useCallback(E=>d(A0t($,E)),[$]),y=[l&&`${l.width} × ${l.height}`,s&&T0t(s.bytes)].filter(Boolean);return x.jsxs("div",{className:"image-document",children:[x.jsxs("div",{className:"preview-toolbar",children:[x.jsxs("span",{className:"image-meta",children:[x.jsx("span",{className:"truncate",children:i}),y.length>0&&x.jsx("span",{children:y.join(" · ")})]}),x.jsxs("span",{className:"image-actions",children:[x.jsx(Xe,{icon:"minus",label:"Zoom out",disabled:!l,onClick:()=>A(-1)}),x.jsx("button",{className:"text-button",disabled:!l,onClick:()=>d(h===1?"fit":1),children:l?P0t($):"—"}),x.jsx(Xe,{icon:"plus",label:"Zoom in",disabled:!l,onClick:()=>A(1)}),x.jsx(Xe,{icon:"focus",label:"Fit to window",disabled:!l,"aria-pressed":h==="fit",onClick:()=>d("fit")}),x.jsx(Xe,{icon:"refresh",label:"Reload image",onClick:()=>v(E=>E+1)}),CM(i)&&x.jsx("button",{className:"button",onClick:()=>{e(i)},children:D("Open source")})]})]}),x.jsx("div",{ref:_,className:`image-canvas${$>=2&&!CM(i)?" pixelated":""}`,tabIndex:0,role:"group","aria-label":D("Image preview"),onKeyDown:E=>{if(!(E.metaKey||E.ctrlKey||E.altKey)){if(E.key==="+"||E.key==="=")A(1);else if(E.key==="-")A(-1);else if(E.key==="0")d(1);else if(E.key==="9")d("fit");else return;E.preventDefault()}},children:n?x.jsxs(qd,{title:D("Image unavailable"),children:[x.jsx("p",{children:i}),x.jsx("p",{role:"alert",children:n}),x.jsx("button",{className:"button",onClick:()=>v(E=>E+1),children:D("Retry")}),x.jsx("button",{className:"button",onClick:()=>{e(i)},children:D("Open source")})]}):s&&x.jsx("img",{className:"image-frame",src:s.url,alt:i.split("/").pop(),decoding:"async",draggable:!1,onLoad:E=>{const C=E.currentTarget;C.naturalWidth>0&&C.naturalHeight>0&&c({width:C.naturalWidth,height:C.naturalHeight})},onError:()=>a(D("This file is not a supported image")),...l?{width:Math.max(1,Math.round(l.width*$)),height:Math.max(1,Math.round(l.height*$))}:{}})})]})}return{manifest:{manifestVersion:1,id:"oxbit.images",name:"Image Viewer",version:"1.0.0",sdk:"^1.0.0",environments:["browser","embedded"],activation:["*"],capabilities:["filesystem.read"],description:"Opens PNG, JPEG, GIF, WebP, AVIF, BMP, ICO and SVG files without decoding them as text."},activate(i){i.own(i.contributions.register({id:E0t,kind:"documentView",title:"Image Viewer",component:r,data:{binary:!0,extensions:_0t}})),i.own(i.commands.register({id:"image.openSource",title:"Open Image as Text",category:"Image",when:"binaryDocument",run:()=>{const s=t.workbench.activePath();if(!s)throw new Error("Open an image first");return e(s)}}))}}}const R0t=async(t,e,r)=>{r.signal?.throwIfAborted();const i=await Cn(()=>import("./standalone-Cayz_KD-.js"),[]),s=r.language??Zg(e).id;let o,n;if(["typescript","typescriptreact","javascript","javascriptreact","json","jsonc"].includes(s))o=s==="json"||s==="jsonc"?s:["javascript","javascriptreact"].includes(s)?"babel":"typescript",n=[await Cn(()=>import("./typescript-cMir0TZb.js"),[]),await Cn(()=>import("./babel-BktJt1uC.js"),[]),await Cn(()=>import("./estree-DFfjoHvx.js"),[])];else if(s==="css")o="css",n=[await Cn(()=>import("./postcss-BGfBeQpW.js"),[])];else if(["html"].includes(s))o="html",n=[await Cn(()=>import("./html-DwgzGnwN.js"),[])];else if(["markdown","mdx"].includes(s))o=s,n=[await Cn(()=>import("./markdown-Bd15IfY5.js"),[]),await Cn(()=>import("./babel-BktJt1uC.js"),[]),await Cn(()=>import("./estree-DFfjoHvx.js"),[])];else throw new Error(`Prettier does not support ${e}`);const a=await i.format(t,{parser:o,plugins:n,tabWidth:r.tabSize,useTabs:!r.insertSpaces});return r.signal?.throwIfAborted(),a},D0t=async(t,e,r)=>{r.signal?.throwIfAborted();const i=r.language??Zg(e).id;if(!["typescript","typescriptreact","javascript","javascriptreact","json"].includes(i))throw new Error(`TypeScript formatter does not support ${e}`);const s=await Cn(()=>import("./typescript-e-g8-Q0v.js").then(n=>n.t),[]),o=s.createLanguageService({getScriptFileNames:()=>[e],getScriptVersion:()=>"1",getScriptKind:()=>({typescript:s.ScriptKind.TS,typescriptreact:s.ScriptKind.TSX,javascript:s.ScriptKind.JS,javascriptreact:s.ScriptKind.JSX,json:s.ScriptKind.JSON})[i]??s.ScriptKind.Unknown,getScriptSnapshot:n=>n===e?s.ScriptSnapshot.fromString(t):void 0,getCurrentDirectory:()=>"",getCompilationSettings:()=>({allowJs:!0,jsx:s.JsxEmit.Preserve,target:s.ScriptTarget.Latest,resolveJsonModule:!0}),getDefaultLibFileName:()=>"lib.d.ts",fileExists:n=>n===e,readFile:n=>n===e?t:void 0,readDirectory:()=>[]});try{const n=o.getFormattingEditsForDocument(e,{indentSize:r.tabSize,tabSize:r.tabSize,convertTabsToSpaces:r.insertSpaces,newLineCharacter:`
201
+ `).findIndex(k=>/^#{1,6}\s/.test(k)&&vY(k.replace(/^#{1,6}\s+/,""))===y.anchor)+1,E||(E=void 0)),await t.workbench.openFile(y.path,{line:E})})().catch(E=>t.workbench.notify(String(E),"error"))},dangerouslySetInnerHTML:{__html:d.trust===c&&!g?d.html:""}}))}const n=async(l=!1)=>{const c=t.workbench.activePath();if(!c||!/\.md$/i.test(c))throw new Error("Open a Markdown document first");let h;if(l&&(h=t.workbench.split("row"),!h))return;const d="preview:"+c;e.add(d),t.workbench.openView(d,D("{0} Preview",{0:c.split("/").pop()}),o,{path:c},{groupId:h,path:c,contributionId:"markdown.preview"})},a=(l=!1)=>{const c=t.workbench.activePath();if(!c||!$Y(c))throw new Error("Open an HTML document first");const h=l?t.workbench.split("row"):void 0;if(l&&!h)return;const d="html-preview:"+c;e.add(d),t.workbench.openView(d,D("{0} Preview",{0:c.split("/").pop()}),r,{path:c},{groupId:h,path:c,contributionId:"html.preview"})};return{manifest:{manifestVersion:1,id:"oxbit.previews",name:"Document & Media Previews",description:"Markdown and HTML/CSS previews, PDF viewing, and audio playback for MP3, WAV, M4A, FLAC, Ogg, and more.",version:"1.0.0",sdk:"^1.0.0",environments:["browser","embedded"],activation:["*"],capabilities:["filesystem.read"]},activate(l){l.own(l.contributions.register({id:"pdf.preview",kind:"documentView",title:"PDF Viewer",component:i,data:{binary:!0,extensions:["pdf"]}})),l.own(l.contributions.register({id:"audio.preview",kind:"documentView",title:"Audio Player",component:s,data:{binary:!0,extensions:Object.keys(_Y)}})),l.own(l.contributions.register({id:"html.preview",kind:"documentView",title:"HTML preview",component:r})),l.own(l.commands.register({id:"preview.html",title:"Open HTML Preview",when:"html",shortcut:"Ctrl+Shift+V",run:()=>a()})),l.own(l.commands.register({id:"preview.htmlSide",title:"Open HTML Preview to the Side",when:"html",shortcut:"Ctrl+K V",run:()=>a(!0)})),l.own(l.contributions.register({id:"markdown.preview",kind:"documentView",title:"Markdown preview",component:o})),l.own(l.commands.register({id:"preview.markdown",title:"Open Markdown Preview",when:"markdown",shortcut:"Ctrl+Shift+V",run:()=>n()})),l.own(l.commands.register({id:"preview.markdownSide",title:"Open Markdown Preview to the Side",when:"markdown",shortcut:"Ctrl+K V",run:()=>n(!0)})),l.own(l.commands.register({id:"preview.toggle",title:"Toggle Markdown Preview",when:"markdown",run:()=>{const c=t.workbench.activePath();return c&&!t.workbench.activeEditor()?(t.workbench.closeView("preview:"+c),t.workbench.openFile(c,{preview:!1})):n()}})),l.subscribe(()=>{for(const c of e)t.workbench.closeView(c);e.clear()})}}}const CY={apng:"image/apng",avif:"image/avif",bmp:"image/bmp",gif:"image/gif",ico:"image/x-icon",jfif:"image/jpeg",jpe:"image/jpeg",jpeg:"image/jpeg",jpg:"image/jpeg",png:"image/png",svg:"image/svg+xml",webp:"image/webp"},_0t=Object.keys(CY);function TY(t){const e=t.toLowerCase().split("/").pop()??"",r=e.lastIndexOf(".");return r>0?CY[e.slice(r+1)]:void 0}function CM(t){return TY(t)==="image/svg+xml"}const om=[.1,.25,.5,.75,1,1.5,2,3,4,6,8,12,16];function A0t(t,e){const r=om[0],i=om[om.length-1];return e>0?om.find(s=>s>t+1e-6)??Math.max(t,i):[...om].reverse().find(s=>s<t-1e-6)??Math.min(t,r)}function C0t(t,e){return t.width<=0||t.height<=0||e.width<=0||e.height<=0?1:Math.min(1,e.width/t.width,e.height/t.height)}function T0t(t){const e=["B","KB","MB"];let r=t,i=0;for(;r>=1024&&i<e.length-1;)r/=1024,i++;return`${i===0?r:r.toFixed(r<10?1:0)} ${e[i]}`}function P0t(t){const e=t*100;return`${e<10?e.toFixed(1):Math.round(e)}%`}const E0t="oxbit.images.view";function Q0t(t){const e=async i=>{t.workbench.closeView(i),await t.workbench.openFile(i,{text:!0,preview:!1})};function r({path:i}){const[s,o]=j.useState(),[n,a]=j.useState(""),[l,c]=j.useState(),[h,d]=j.useState("fit"),[p,g]=j.useState({width:0,height:0}),[b,v]=j.useState(0),_=j.useRef(null);j.useEffect(()=>{const E=new AbortController;let C="";return o(void 0),a(""),c(void 0),(async()=>{if(!t.filesystem.readBytes)throw new Error(D("This workspace cannot read image files"));const k=await t.filesystem.readBytes(i,E.signal);E.signal.aborted||(C=URL.createObjectURL(new Blob([k],{type:TY(i)})),o({url:C,bytes:k.byteLength}))})().catch(k=>{E.signal.aborted||a(k instanceof Error?k.message:String(k))}),()=>{E.abort(),C&&URL.revokeObjectURL(C)}},[i,b]),j.useEffect(()=>{const E=t.filesystem.watch(C=>{C.path===i&&C.kind==="changed"&&v(k=>k+1)});return()=>E.dispose()},[i]),j.useEffect(()=>{const E=_.current;if(!E||typeof ResizeObserver>"u")return;const C=new ResizeObserver(([k])=>g({width:k.contentRect.width,height:k.contentRect.height}));return C.observe(E),()=>C.disconnect()},[]);const $=l?h==="fit"?C0t(l,p):h:1,A=j.useCallback(E=>d(A0t($,E)),[$]),y=[l&&`${l.width} × ${l.height}`,s&&T0t(s.bytes)].filter(Boolean);return x.jsxs("div",{className:"image-document",children:[x.jsxs("div",{className:"preview-toolbar",children:[x.jsxs("span",{className:"image-meta",children:[x.jsx("span",{className:"truncate",children:i}),y.length>0&&x.jsx("span",{children:y.join(" · ")})]}),x.jsxs("span",{className:"image-actions",children:[x.jsx(Xe,{icon:"minus",label:"Zoom out",disabled:!l,onClick:()=>A(-1)}),x.jsx("button",{className:"text-button",disabled:!l,onClick:()=>d(h===1?"fit":1),children:l?P0t($):"—"}),x.jsx(Xe,{icon:"plus",label:"Zoom in",disabled:!l,onClick:()=>A(1)}),x.jsx(Xe,{icon:"focus",label:"Fit to window",disabled:!l,"aria-pressed":h==="fit",onClick:()=>d("fit")}),x.jsx(Xe,{icon:"refresh",label:"Reload image",onClick:()=>v(E=>E+1)}),CM(i)&&x.jsx("button",{className:"button",onClick:()=>{e(i)},children:D("Open source")})]})]}),x.jsx("div",{ref:_,className:`image-canvas${$>=2&&!CM(i)?" pixelated":""}`,tabIndex:0,role:"group","aria-label":D("Image preview"),onKeyDown:E=>{if(!(E.metaKey||E.ctrlKey||E.altKey)){if(E.key==="+"||E.key==="=")A(1);else if(E.key==="-")A(-1);else if(E.key==="0")d(1);else if(E.key==="9")d("fit");else return;E.preventDefault()}},children:n?x.jsxs(qd,{title:D("Image unavailable"),children:[x.jsx("p",{children:i}),x.jsx("p",{role:"alert",children:n}),x.jsx("button",{className:"button",onClick:()=>v(E=>E+1),children:D("Retry")}),x.jsx("button",{className:"button",onClick:()=>{e(i)},children:D("Open source")})]}):s&&x.jsx("img",{className:"image-frame",src:s.url,alt:i.split("/").pop(),decoding:"async",draggable:!1,onLoad:E=>{const C=E.currentTarget;C.naturalWidth>0&&C.naturalHeight>0&&c({width:C.naturalWidth,height:C.naturalHeight})},onError:()=>a(D("This file is not a supported image")),...l?{width:Math.max(1,Math.round(l.width*$)),height:Math.max(1,Math.round(l.height*$))}:{}})})]})}return{manifest:{manifestVersion:1,id:"oxbit.images",name:"Image Viewer",version:"1.0.0",sdk:"^1.0.0",environments:["browser","embedded"],activation:["*"],capabilities:["filesystem.read"],description:"Opens PNG, JPEG, GIF, WebP, AVIF, BMP, ICO and SVG files without decoding them as text."},activate(i){i.own(i.contributions.register({id:E0t,kind:"documentView",title:"Image Viewer",component:r,data:{binary:!0,extensions:_0t}})),i.own(i.commands.register({id:"image.openSource",title:"Open Image as Text",category:"Image",when:"binaryDocument",run:()=>{const s=t.workbench.activePath();if(!s)throw new Error("Open an image first");return e(s)}}))}}}const R0t=async(t,e,r)=>{r.signal?.throwIfAborted();const i=await Cn(()=>import("./standalone-Cayz_KD-.js"),[]),s=r.language??Zg(e).id;let o,n;if(["typescript","typescriptreact","javascript","javascriptreact","json","jsonc"].includes(s))o=s==="json"||s==="jsonc"?s:["javascript","javascriptreact"].includes(s)?"babel":"typescript",n=[await Cn(()=>import("./typescript-cMir0TZb.js"),[]),await Cn(()=>import("./babel-BktJt1uC.js"),[]),await Cn(()=>import("./estree-DFfjoHvx.js"),[])];else if(s==="css")o="css",n=[await Cn(()=>import("./postcss-BGfBeQpW.js"),[])];else if(["html"].includes(s))o="html",n=[await Cn(()=>import("./html-DwgzGnwN.js"),[])];else if(["markdown","mdx"].includes(s))o=s,n=[await Cn(()=>import("./markdown-Bd15IfY5.js"),[]),await Cn(()=>import("./babel-BktJt1uC.js"),[]),await Cn(()=>import("./estree-DFfjoHvx.js"),[])];else throw new Error(`Prettier does not support ${e}`);const a=await i.format(t,{parser:o,plugins:n,tabWidth:r.tabSize,useTabs:!r.insertSpaces});return r.signal?.throwIfAborted(),a},D0t=async(t,e,r)=>{r.signal?.throwIfAborted();const i=r.language??Zg(e).id;if(!["typescript","typescriptreact","javascript","javascriptreact","json"].includes(i))throw new Error(`TypeScript formatter does not support ${e}`);const s=await Cn(()=>import("./typescript-JybYWk0M.js").then(n=>n.t),[]),o=s.createLanguageService({getScriptFileNames:()=>[e],getScriptVersion:()=>"1",getScriptKind:()=>({typescript:s.ScriptKind.TS,typescriptreact:s.ScriptKind.TSX,javascript:s.ScriptKind.JS,javascriptreact:s.ScriptKind.JSX,json:s.ScriptKind.JSON})[i]??s.ScriptKind.Unknown,getScriptSnapshot:n=>n===e?s.ScriptSnapshot.fromString(t):void 0,getCurrentDirectory:()=>"",getCompilationSettings:()=>({allowJs:!0,jsx:s.JsxEmit.Preserve,target:s.ScriptTarget.Latest,resolveJsonModule:!0}),getDefaultLibFileName:()=>"lib.d.ts",fileExists:n=>n===e,readFile:n=>n===e?t:void 0,readDirectory:()=>[]});try{const n=o.getFormattingEditsForDocument(e,{indentSize:r.tabSize,tabSize:r.tabSize,convertTabsToSpaces:r.insertSpaces,newLineCharacter:`
202
202
  `,indentStyle:s.IndentStyle.Smart,insertSpaceAfterCommaDelimiter:!0,insertSpaceBeforeAndAfterBinaryOperators:!0,insertSpaceAfterKeywordsInControlFlowStatements:!0,insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces:!0});let a=t;for(const l of n.sort((c,h)=>h.span.start-c.span.start))a=a.slice(0,l.span.start)+l.newText+a.slice(l.span.start+l.span.length);return r.signal?.throwIfAborted(),a}finally{o.dispose()}};function PY(t,e,r,i){return{manifest:{manifestVersion:1,id:t,name:e,version:"1.0.0",sdk:"^1.0.0",environments:["browser","embedded"],dependencies:{"oxbit.formatters":"^1.0.0"},activation:["*"],capabilities:[]},activate(s){const o={id:t,languages:i,async format(n,a,l){const c=l.signal?AbortSignal.any([l.signal,s.signal]):s.signal;return c.throwIfAborted(),typeof Worker>"u"?(r==="typescript"?D0t:R0t)(n,a,{...l,signal:c}):new Promise((h,d)=>{const p=new Worker(new URL("/assets/format.worker-BOByM0b_.js",import.meta.url),{type:"module"}),g=()=>{clearTimeout(v),c.removeEventListener("abort",b),p.terminate()},b=()=>{g(),d(new DOMException("Formatting cancelled","AbortError"))},v=setTimeout(()=>{g(),d(new Error("Formatting exceeded 15 seconds"))},15e3);c.addEventListener("abort",b,{once:!0}),p.onmessage=_=>{g(),_.data.error?d(new Error(_.data.error)):h(_.data.text)},p.onerror=_=>{g(),d(new Error(_.message))},p.postMessage({provider:r,text:n,path:a,language:l.language,tabSize:l.tabSize,insertSpaces:l.insertSpaces})})}};s.contributions.register({id:t,kind:"formatter",title:e,data:o})}}}const F0t=()=>PY("oxbit.prettier","Prettier","prettier",["typescript","tsx","javascript","json","jsonc","html","css","markdown","mdx"]),N0t=()=>PY("oxbit.builtin-ts","TypeScript formatter","typescript",["typescript","tsx","javascript","json"]);class L0t{constructor(e){this.options=e}options;providers=new Map;register(e){if(this.providers.has(e.id))throw new Error(`Duplicate formatter ${e.id}`);this.providers.set(e.id,e);let r=!1;return{dispose:()=>{r||(r=!0,this.providers.delete(e.id))}}}list(e){const r=new Map(this.providers);for(const s of this.options.kernel.contributions.list("formatter")){const o=s.data;if(!(!o||typeof o.id!="string"||typeof o.format!="function"||!Array.isArray(o.languages))){if(r.has(o.id)&&r.get(o.id)!==o)throw new Error(`Duplicate formatter ${o.id}`);r.set(o.id,o)}}const i=e?Zr(this.options.kernel,e).id:void 0;return[...r.values()].filter(s=>!i||s.languages.some(o=>Bd(o)===i||o==="javascript"&&i==="javascriptreact"))}selected(e){const r=Zr(this.options.kernel,e).id,i=this.options.kernel.configuration.get("editor.defaultFormatter",r)||"oxbit.prettier",s=this.list(e).find(o=>o.id===i);if(!s)throw new Error(`Formatter ${i} is unavailable for ${r}`);return s}title(e){const r=this.selected(e);return this.options.kernel.contributions.list("formatter").find(i=>i.data?.id===r.id)?.title??r.id}async format(e,r,i){i?.throwIfAborted();const s=Zr(this.options.kernel,r).id,n=await this.selected(r).format(e,r,{language:s,tabSize:this.options.kernel.configuration.get("editor.tabSize",s)??2,insertSpaces:this.options.kernel.configuration.get("editor.insertSpaces",s)??!0,signal:i});return i?.throwIfAborted(),n}}function M0t(t){return{manifest:{manifestVersion:1,id:"oxbit.formatters",name:"Formatter coordination",version:"1.0.0",sdk:"^1.0.0",environments:["browser","embedded"],activation:["*"],capabilities:[]},activate(e){const r=new L0t(t);e.services.register("formatters",r);const i=()=>{const s=t.workbench.activePath();let o=!1;if(s&&e.context.get("editor"))try{r.selected(s),o=!0}catch{}e.context.get("formattable")!==o&&e.context.set("formattable",o)};e.configuration.subscribe(i),e.contributions.subscribe(i),e.events.on("editor.active",i),i(),e.commands.register({id:"editor.format",title:"Format Document",shortcut:"Mod+Shift+I",when:"editor && formattable",run:async()=>{const s=t.workbench.activePath();if(!s)throw new Error("Open a document to format");const o=await t.documents.open(s),n=o.version,a=performance.now(),l=r.title(s),c=await r.format(o.text.toString(),s,e.signal);if(o.version!==n)throw new Error("Document changed during formatting");o.replace(c),t.workbench.notify(`Formatted with ${l} · ${Math.round(performance.now()-a)} ms`)}}),e.hooks.beforeSave("formatters.save",async({path:s,text:o,signal:n})=>{const a=Zr(t.kernel,s).id;return e.configuration.get("editor.formatOnSave",a)&&(o=await r.format(o,s,n)),n.throwIfAborted(),e.configuration.get("files.trimTrailingWhitespace",a)&&(o=o.replace(/[\t ]+$/gm,"")),o},10),e.subscribe(()=>e.context.set("formattable",!1))}}}var EY=Object.defineProperty,j0t=Object.getOwnPropertyDescriptor,z0t=(t,e)=>{for(var r in e)EY(t,r,{get:e[r],enumerable:!0})},Rr=(t,e,r,i)=>{for(var s=i>1?void 0:i?j0t(e,r):e,o=t.length-1,n;o>=0;o--)(n=t[o])&&(s=(i?n(e,r,s):n(s))||s);return i&&s&&EY(e,r,s),s},je=(t,e)=>(r,i)=>e(r,i,t),TM="Terminal input",E2={get:()=>TM,set:t=>TM=t},PM="Too much output to announce, navigate to rows manually to read",Nw={get:()=>PM,set:t=>PM=t};function I0t(t){return t.replace(/\r?\n/g,"\r")}function B0t(t,e){return e?`\x1B[200~${t.replace(/\x1b/g,"␛")}\x1B[201~`:t}function X0t(t,e){t.clipboardData&&t.clipboardData.setData("text/plain",e.selectionText),t.preventDefault()}function U0t(t,e,r,i){if(t.stopPropagation(),t.clipboardData){let s=t.clipboardData.getData("text/plain");QY(s,e,r,i)}}function QY(t,e,r,i){t=I0t(t),t=B0t(t,r.decPrivateModes.bracketedPasteMode&&i.rawOptions.ignoreBracketedPasteMode!==!0),r.triggerDataEvent(t,!0),e.value=""}function RY(t,e,r){let i=r.getBoundingClientRect(),s=t.clientX-i.left-10,o=t.clientY-i.top-10;e.style.width="20px",e.style.height="20px",e.style.left=`${s}px`,e.style.top=`${o}px`,e.style.zIndex="1000",e.focus()}function EM(t,e,r,i,s){RY(t,e,r),s&&i.rightClickSelect(t),e.value=i.selectionText,e.select()}function kc(t){return t>65535?(t-=65536,String.fromCharCode((t>>10)+55296)+String.fromCharCode(t%1024+56320)):String.fromCharCode(t)}function Qf(t,e=0,r=t.length){let i="";for(let s=e;s<r;++s){let o=t[s];o>65535?(o-=65536,i+=String.fromCharCode((o>>10)+55296)+String.fromCharCode(o%1024+56320)):i+=String.fromCharCode(o)}return i}var q0t=class{constructor(){this._interim=0}clear(){this._interim=0}decode(t,e){let r=t.length;if(!r)return 0;let i=0,s=0;if(this._interim){let o=t.charCodeAt(s++);56320<=o&&o<=57343?e[i++]=(this._interim-55296)*1024+o-56320+65536:(e[i++]=this._interim,e[i++]=o),this._interim=0}for(let o=s;o<r;++o){let n=t.charCodeAt(o);if(55296<=n&&n<=56319){if(++o>=r)return this._interim=n,i;let a=t.charCodeAt(o);56320<=a&&a<=57343?e[i++]=(n-55296)*1024+a-56320+65536:(e[i++]=n,e[i++]=a);continue}n!==65279&&(e[i++]=n)}return i}},V0t=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(t,e){let r=t.length;if(!r)return 0;let i=0,s,o,n,a,l,c=0;if(this.interim[0]){let p=!1,g=this.interim[0];g&=(g&224)===192?31:(g&240)===224?15:7;let b=0,v;for(;(v=this.interim[++b])&&b<4;)g<<=6,g|=v&63;let _=(this.interim[0]&224)===192?2:(this.interim[0]&240)===224?3:4,$=_-b;for(;c<$;){if(c>=r)return 0;if(v=t[c++],(v&192)!==128){c--,p=!0;break}else this.interim[b++]=v,g<<=6,g|=v&63}p||(_===2?g<128?c--:e[i++]=g:_===3?g<2048||g>=55296&&g<=57343||g===65279||(e[i++]=g):g<65536||g>1114111||(e[i++]=g)),this.interim.fill(0)}let h=r-4,d=c;for(;d<r;){for(;d<h&&!((s=t[d])&128)&&!((o=t[d+1])&128)&&!((n=t[d+2])&128)&&!((a=t[d+3])&128);)e[i++]=s,e[i++]=o,e[i++]=n,e[i++]=a,d+=4;if(s=t[d++],s<128)e[i++]=s;else if((s&224)===192){if(d>=r)return this.interim[0]=s,i;if(o=t[d++],(o&192)!==128){d--;continue}if(l=(s&31)<<6|o&63,l<128){d--;continue}e[i++]=l}else if((s&240)===224){if(d>=r)return this.interim[0]=s,i;if(o=t[d++],(o&192)!==128){d--;continue}if(d>=r)return this.interim[0]=s,this.interim[1]=o,i;if(n=t[d++],(n&192)!==128){d--;continue}if(l=(s&15)<<12|(o&63)<<6|n&63,l<2048||l>=55296&&l<=57343||l===65279)continue;e[i++]=l}else if((s&248)===240){if(d>=r)return this.interim[0]=s,i;if(o=t[d++],(o&192)!==128){d--;continue}if(d>=r)return this.interim[0]=s,this.interim[1]=o,i;if(n=t[d++],(n&192)!==128){d--;continue}if(d>=r)return this.interim[0]=s,this.interim[1]=o,this.interim[2]=n,i;if(a=t[d++],(a&192)!==128){d--;continue}if(l=(s&7)<<18|(o&63)<<12|(n&63)<<6|a&63,l<65536||l>1114111)continue;e[i++]=l}}return i}},wO=class DY{constructor(){this.fg=0,this.bg=0,this.extended=new Lw}static toColorRGB(e){return[e>>>16&255,e>>>8&255,e&255]}static fromColorRGB(e){return(e[0]&255)<<16|(e[1]&255)<<8|e[2]&255}clone(){let e=new DY;return e.fg=this.fg,e.bg=this.bg,e.extended=this.extended.clone(),e}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)===50331648}isBgRGB(){return(this.bg&50331648)===50331648}isFgPalette(){return(this.fg&50331648)===16777216||(this.fg&50331648)===33554432}isBgPalette(){return(this.bg&50331648)===16777216||(this.bg&50331648)===33554432}isFgDefault(){return(this.fg&50331648)===0}isBgDefault(){return(this.bg&50331648)===0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:case 33554432:return this.fg&255;case 50331648:return this.fg&16777215;default:return-1}}getBgColor(){switch(this.bg&50331648){case 16777216:case 33554432:return this.bg&255;case 50331648:return this.bg&16777215;default:return-1}}hasExtendedAttrs(){return this.bg&268435456}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(this.bg&268435456&&~this.extended.underlineColor)switch(this.extended.underlineColor&50331648){case 16777216:case 33554432:return this.extended.underlineColor&255;case 50331648:return this.extended.underlineColor&16777215;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return this.bg&268435456&&~this.extended.underlineColor?this.extended.underlineColor&50331648:this.getFgColorMode()}isUnderlineColorRGB(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===50331648:this.isFgRGB()}isUnderlineColorPalette(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===16777216||(this.extended.underlineColor&50331648)===33554432:this.isFgPalette()}isUnderlineColorDefault(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===0:this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},Lw=class FY{constructor(e=0,r=0){this._ext=0,this._urlId=0,this._ext=e,this._urlId=r}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(e){this._ext=e}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(e){this._ext&=-469762049,this._ext|=e<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(e){this._ext&=-67108864,this._ext|=e&67108863}get urlId(){return this._urlId}set urlId(e){this._urlId=e}get underlineVariantOffset(){let e=(this._ext&3758096384)>>29;return e<0?e^4294967288:e}set underlineVariantOffset(e){this._ext&=536870911,this._ext|=e<<29&3758096384}clone(){return new FY(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0&&this.payload===void 0}},Xo=class NY extends wO{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new Lw,this.combinedData=""}static fromCharData(e){let r=new NY;return r.setFromCharData(e),r}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?kc(this.content&2097151):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(e){this.fg=e[0],this.bg=0;let r=!1;if(e[1].length>2)r=!0;else if(e[1].length===2){let i=e[1].charCodeAt(0);if(55296<=i&&i<=56319){let s=e[1].charCodeAt(1);56320<=s&&s<=57343?this.content=(i-55296)*1024+s-56320+65536|e[2]<<22:r=!0}else r=!0}else this.content=e[1].charCodeAt(0)|e[2]<<22;r&&(this.combinedData=e[1],this.content=2097152|e[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}attributesEquals(e){if(this.getFgColorMode()!==e.getFgColorMode()||this.getFgColor()!==e.getFgColor()||this.getBgColorMode()!==e.getBgColorMode()||this.getBgColor()!==e.getBgColor()||this.isInverse()!==e.isInverse()||this.isBold()!==e.isBold()||this.isUnderline()!==e.isUnderline())return!1;if(this.isUnderline()){if(this.getUnderlineStyle()!==e.getUnderlineStyle())return!1;let r=this.isUnderlineColorDefault(),i=e.isUnderlineColorDefault();if(!(r&&i)&&(r!==i||this.getUnderlineColor()!==e.getUnderlineColor()||this.getUnderlineColorMode()!==e.getUnderlineColorMode()))return!1}return!(this.isOverline()!==e.isOverline()||this.isBlink()!==e.isBlink()||this.isInvisible()!==e.isInvisible()||this.isItalic()!==e.isItalic()||this.isDim()!==e.isDim()||this.isStrikethrough()!==e.isStrikethrough())}},z_=new Map;function Y0t(t){return t.di$dependencies||[]}function yi(t){if(z_.has(t))return z_.get(t);let e=function(r,i,s){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");Z0t(e,r,s)};return e._id=t,z_.set(t,e),e}function Z0t(t,e,r){e.di$target===e?e.di$dependencies.push({id:t,index:r}):(e.di$dependencies=[{id:t,index:r}],e.di$target=e)}var As=yi("BufferService"),Mk=yi("MouseStateService"),Fl=yi("CoreService"),W0t=yi("CharsetService"),FE=yi("InstantiationService"),Rf=yi("LogService"),Cs=yi("OptionsService"),LY=yi("OscLinkService"),G0t=yi("UnicodeService"),kO=yi("DecorationService"),Q2=class{constructor(t,e,r){this._bufferService=t,this._optionsService=e,this._oscLinkService=r,this._workCell=new Xo}provideLinks(t,e){let r=this._bufferService.buffer.lines.get(t-1);if(!r){e(void 0);return}let i=[],s=this._optionsService.rawOptions.linkHandler,o=this._workCell,n=r.getTrimmedLength(),a=-1,l=-1,c=!1;for(let h=0;h<n;h++)if(!(l===-1&&!r.hasContent(h))){if(r.loadCell(h,o),o.hasExtendedAttrs()&&o.extended.urlId)if(l===-1){l=h,a=o.extended.urlId;continue}else c=o.extended.urlId!==a;else l!==-1&&(c=!0);if(c||l!==-1&&h===n-1){let d=this._oscLinkService.getLinkData(a)?.uri;if(d){let p=h+(!c&&h===n-1?1:0),g=this._getRangeWithLineWrap(t,l,p,a),b=!1;if(!s?.allowNonHttpProtocols)try{let v=new URL(d);["http:","https:"].includes(v.protocol)||(b=!0)}catch{b=!0}b||i.push({text:d,range:g,activate:(v,_)=>s?s.activate(v,_,g):H0t(v,_),hover:(v,_)=>s?.hover?.(v,_,g),leave:(v,_)=>s?.leave?.(v,_,g)})}c=!1,o.hasExtendedAttrs()&&o.extended.urlId?(l=h,a=o.extended.urlId):(l=-1,a=-1)}}e(i)}_getRangeWithLineWrap(t,e,r,i){let s=t,o=e,n=t,a=r;for(;o===0&&this._bufferService.buffer.lines.get(s-1)?.isWrapped;){let l=this._bufferService.buffer.lines.get(s-2);if(!l)break;let c=l.getTrimmedLength();if(c===0||!this._hasUrlId(l,c-1,i))break;let h=c-1;for(;h>0&&this._hasUrlId(l,h-1,i);)h--;s--,o=h}for(;;){let l=this._bufferService.buffer.lines.get(n-1);if(!l)break;let c=l.getTrimmedLength();if(a!==c)break;let h=this._bufferService.buffer.lines.get(n);if(!h?.isWrapped)break;let d=h.getTrimmedLength();if(d===0||!this._hasUrlId(h,0,i))break;let p=1;for(;p<d&&this._hasUrlId(h,p,i);)p++;n++,a=p}return{start:{x:o+1,y:s},end:{x:a,y:n}}}_hasUrlId(t,e,r){let i=this._workCell;return t.loadCell(e,i),!!i.hasExtendedAttrs()&&i.extended.urlId===r}};Q2=Rr([je(0,As),je(1,Cs),je(2,LY)],Q2);function H0t(t,e){if(confirm(`Do you want to navigate to ${e}?
203
203
 
204
204
  WARNING: This link could potentially be dangerous`)){let r=window.open();if(r){try{r.opener=null}catch{}r.location.href=e}else console.warn("Opening link blocked as opener could not be cleared")}}var jk=yi("CharSizeService"),Xa=yi("CoreBrowserService"),zk=yi("MouseCoordsService"),K0t=yi("MouseService"),Ua=yi("RenderService"),MY=yi("SelectionService"),jY=yi("CharacterJoinerService"),Df=yi("ThemeService"),zY=yi("LinkProviderService"),J0t=yi("KeyboardService");function fr(t){return{dispose:t}}function Bg(t){if(!t)return t;if(Array.isArray(t)){for(let e of t)e.dispose();return[]}return t.dispose(),t}var Ff=class{constructor(){this._disposables=new Set,this._isDisposed=!1}get isDisposed(){return this._isDisposed}add(t){return this._isDisposed?t.dispose():this._disposables.add(t),t}dispose(){if(!this._isDisposed){this._isDisposed=!0;for(let t of this._disposables)t.dispose();this._disposables.clear()}}clear(){for(let t of this._disposables)t.dispose();this._disposables.clear()}},Dt=class{constructor(){this._store=new Ff}dispose(){this._store.dispose()}_register(t){return this._store.add(t)}};Dt.None=Object.freeze({dispose(){}});var In=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(e){this._isDisposed||e===this._value||(this._value?.dispose(),this._value=e)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,this._value?.dispose(),this._value=void 0}},Ik=class{constructor(){this._token=-1,this._isDisposed=!1}dispose(){this.cancel(),this._isDisposed=!0}cancel(){this._token!==-1&&(clearTimeout(this._token),this._token=-1)}cancelAndSet(t,e){if(this._isDisposed)throw new Error("Calling cancelAndSet on a disposed TimeoutTimer");this.cancel(),this._token=setTimeout(()=>{this._token=-1,t()},e)}setIfNotSet(t,e){if(this._isDisposed)throw new Error("Calling setIfNotSet on a disposed TimeoutTimer");this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,t()},e))}},ebt=class{constructor(){this._isScheduled=!1,this._isDisposed=!1}dispose(){this.cancel(),this._isDisposed=!0}cancel(){this._isScheduled=!1}set(t){if(this._isDisposed)throw new Error("Calling set on a disposed MicrotaskTimer");this._isScheduled||(this._isScheduled=!0,queueMicrotask(()=>{this._isScheduled&&(this._isScheduled=!1,t())}))}},tbt=class{constructor(){this._isDisposed=!1}cancel(){this._disposable?.dispose(),this._disposable=void 0}cancelAndSet(t,e,r=globalThis){if(this._isDisposed)throw new Error("Calling cancelAndSet on a disposed IntervalTimer");this.cancel();let i=r.setInterval(()=>{t()},e);this._disposable={dispose:()=>{r.clearInterval(i),this._disposable=void 0}}}dispose(){this.cancel(),this._isDisposed=!0}};function Lo(t){let e=t;if(e?.ownerDocument?.defaultView)return e.ownerDocument.defaultView;let r=t;return r?.view?r.view:window}var rbt=class{constructor(t,e,r,i){this._node=t,this._type=e,this._handler=r,this._options=i,t.addEventListener(e,r,i)}dispose(){!this._node||!this._handler||(this._node.removeEventListener(this._type,this._handler,this._options),this._node=null,this._handler=null)}};function dt(t,e,r,i){return new rbt(t,e,r,i)}function QM(t,e,r,i){return dt(t,e,r,i)}var Ea={CLICK:"click",MOUSE_OVER:"mouseover",MOUSE_LEAVE:"mouseleave",POINTER_DOWN:"pointerdown",POINTER_MOVE:"pointermove",POINTER_UP:"pointerup",MOUSE_WHEEL:"wheel"};function ibt(t){let e=t.getBoundingClientRect(),r=Lo(t);return{left:e.left+r.scrollX,top:e.top+r.scrollY,width:e.width,height:e.height}}var IY=class{constructor(t,e){this._runner=t,this.priority=e,this._canceled=!1}dispose(){this._canceled=!0}execute(){if(!this._canceled)try{this._runner()}catch(t){console.error(t)}}static sort(t,e){return e.priority-t.priority}},RM=new Map;function BY(t){let e=RM.get(t);return e||(e={next:[],current:[],animFrameRequested:!1,inAnimationFrameRunner:!1},RM.set(t,e)),e}function sbt(t){let e=BY(t);for(e.animFrameRequested=!1,e.current=e.next,e.next=[],e.inAnimationFrameRunner=!0;e.current.length>0;)e.current.sort(IY.sort),e.current.shift().execute();e.inAnimationFrameRunner=!1}function NE(t,e,r=0){let i=BY(t),s=new IY(e,r);return i.next.push(s),i.animFrameRequested||(i.animFrameRequested=!0,t.requestAnimationFrame(()=>sbt(t))),s}var nbt=class extends tbt{constructor(t){super(),this._defaultTarget=t?Lo(t):void 0}cancelAndSet(t,e,r){super.cancelAndSet(t,e,r??this._defaultTarget??window)}},qm=class{constructor(t){this.domNode=t,this._width="",this._height="",this._top="",this._left="",this._bottom="",this._right="",this._className="",this._position="",this._layerHint=!1,this._contain="none"}setWidth(t){let e=Gu(t);this._width!==e&&(this._width=e,this.domNode.style.width=this._width)}setHeight(t){let e=Gu(t);this._height!==e&&(this._height=e,this.domNode.style.height=this._height)}setTop(t){let e=Gu(t);this._top!==e&&(this._top=e,this.domNode.style.top=this._top)}setLeft(t){let e=Gu(t);this._left!==e&&(this._left=e,this.domNode.style.left=this._left)}setBottom(t){let e=Gu(t);this._bottom!==e&&(this._bottom=e,this.domNode.style.bottom=this._bottom)}setRight(t){let e=Gu(t);this._right!==e&&(this._right=e,this.domNode.style.right=this._right)}setClassName(t){this._className!==t&&(this._className=t,this.domNode.className=this._className)}toggleClassName(t,e){this.domNode.classList.toggle(t,e),this._className=this.domNode.className}setPosition(t){this._position!==t&&(this._position=t,this.domNode.style.position=this._position)}setLayerHinting(t){this._layerHint!==t&&(this._layerHint=t,t?this.domNode.style.transform="translate3d(0px, 0px, 0px)":this.domNode.style.transform="")}setContain(t){this._contain!==t&&(this._contain=t,this.domNode.style.contain=this._contain)}setAttribute(t,e){this.domNode.setAttribute(t,e)}};function Gu(t){return typeof t=="number"?`${t}px`:t}var XY={};z0t(XY,{getSafariVersion:()=>abt,getZoomFactor:()=>UY,isChrome:()=>jE,isChromeOS:()=>qY,isFirefox:()=>Mw,isLegacyEdge:()=>obt,isLinux:()=>IE,isMac:()=>fo,isNode:()=>LE,isSafari:()=>zE,isWindows:()=>Bk});var LE=!!(typeof process<"u"&&"title"in process&&(typeof navigator>"u"||navigator.userAgent.startsWith("Node.js/"))),Nf=LE?"node":navigator.userAgent,ME=LE?"node":navigator.platform,Mw=Nf.includes("Firefox"),jE=Nf.includes("Chrome"),obt=Nf.includes("Edge"),zE=/^((?!chrome|android).)*safari/i.test(Nf);function UY(t){return 1}function abt(){if(!zE)return 0;let t=Nf.match(/Version\/(\d+)/);return t===null||t.length<2?0:parseInt(t[1],10)}var fo=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(ME),Bk=["Windows","Win16","Win32","WinCE"].includes(ME),IE=ME.indexOf("Linux")>=0,qY=/\bCrOS\b/.test(Nf),DM=new WeakMap;function lbt(t){if(!t.parent||t.parent===t)return null;try{let e=t.location,r=t.parent.location;if(e.origin!=="null"&&r.origin!=="null"&&e.origin!==r.origin)return null}catch{return null}return t.parent}var cbt=class{static _getSameOriginWindowChain(t){let e=DM.get(t);if(!e){e=[],DM.set(t,e);let r=t,i;do i=lbt(r),i?e.push({window:new WeakRef(r),iframeElement:r.frameElement??null}):e.push({window:new WeakRef(r),iframeElement:null}),r=i;while(r)}return e.slice(0)}static getPositionOfChildWindowRelativeToAncestorWindow(t,e){if(!e||t===e)return{top:0,left:0};let r=0,i=0,s=this._getSameOriginWindowChain(t);for(let o of s){let n=o.window.deref();if(r+=n?.scrollY??0,i+=n?.scrollX??0,n===e||!o.iframeElement)break;let a=o.iframeElement.getBoundingClientRect();r+=a.top,i+=a.left}return{top:r,left:i}}},I_=class{constructor(t,e){this.timestamp=Date.now(),this.browserEvent=e,this.leftButton=e.button===0,this.middleButton=e.button===1,this.rightButton=e.button===2,this.buttons=e.buttons,this.target=e.target,this.detail=e.detail??1,e.type==="dblclick"&&(this.detail=2),this.ctrlKey=e.ctrlKey,this.shiftKey=e.shiftKey,this.altKey=e.altKey,this.metaKey=e.metaKey,typeof e.pageX=="number"?(this.posx=e.pageX,this.posy=e.pageY):(this.posx=e.clientX+this.target.ownerDocument.body.scrollLeft+this.target.ownerDocument.documentElement.scrollLeft,this.posy=e.clientY+this.target.ownerDocument.body.scrollTop+this.target.ownerDocument.documentElement.scrollTop);let r=cbt.getPositionOfChildWindowRelativeToAncestorWindow(t,e.view);this.posx-=r.left,this.posy-=r.top}preventDefault(){this.browserEvent.preventDefault()}stopPropagation(){this.browserEvent.stopPropagation()}},FM=class{constructor(t,e=0,r=0){this.browserEvent=t??null,this.target=t?t.target??t.targetNode??t.srcElement??null:null,this.deltaY=r,this.deltaX=e;let i=!1;if(jE){let s=navigator.userAgent.match(/Chrome\/(\d+)/);i=(s?parseInt(s[1],10):123)<=122}if(t){let s=t,o=t,n=t.view?.devicePixelRatio??1;if(typeof s.wheelDeltaY<"u")i?this.deltaY=s.wheelDeltaY/(120*n):this.deltaY=s.wheelDeltaY/120;else if(typeof o.VERTICAL_AXIS<"u"&&o.axis===o.VERTICAL_AXIS)this.deltaY=-o.detail/3;else if(t.type==="wheel"){let a=t;a.deltaMode===a.DOM_DELTA_LINE?Mw&&!fo?this.deltaY=-t.deltaY/3:this.deltaY=-t.deltaY:this.deltaY=-t.deltaY/40}if(typeof s.wheelDeltaX<"u")zE&&Bk?this.deltaX=-(s.wheelDeltaX/120):i?this.deltaX=s.wheelDeltaX/(120*n):this.deltaX=s.wheelDeltaX/120;else if(typeof o.HORIZONTAL_AXIS<"u"&&o.axis===o.HORIZONTAL_AXIS)this.deltaX=-t.detail/3;else if(t.type==="wheel"){let a=t;a.deltaMode===a.DOM_DELTA_LINE?Mw&&!fo?this.deltaX=-t.deltaX/3:this.deltaX=-t.deltaX:this.deltaX=-t.deltaX/40}this.deltaY===0&&this.deltaX===0&&t.wheelDelta&&(i?this.deltaY=t.wheelDelta/(120*n):this.deltaY=t.wheelDelta/120)}}preventDefault(){this.browserEvent?.preventDefault()}stopPropagation(){this.browserEvent?.stopPropagation()}},VY=class{constructor(){this._hooks=new Ff,this._pointerMoveCallback=null,this._onStopCallback=null}dispose(){this.stopMonitoring(!1),this._hooks.dispose()}stopMonitoring(t){if(!this.isMonitoring())return;this._hooks.clear(),this._pointerMoveCallback=null;let e=this._onStopCallback;this._onStopCallback=null,t&&e&&e()}isMonitoring(){return!!this._pointerMoveCallback}startMonitoring(t,e,r,i,s){this.isMonitoring()&&this.stopMonitoring(!1),this._pointerMoveCallback=i,this._onStopCallback=s;let o=t;try{t.setPointerCapture(e),this._hooks.add(fr(()=>{try{t.releasePointerCapture(e)}catch{}}))}catch{o=Lo(t)}this._hooks.add(dt(o,Ea.POINTER_MOVE,n=>{if(n.buttons!==r){this.stopMonitoring(!0);return}n.preventDefault(),this._pointerMoveCallback(n)})),this._hooks.add(dt(o,Ea.POINTER_UP,n=>this.stopMonitoring(!0)))}},BE=class extends Dt{_onclick(t,e){this._register(dt(t,Ea.CLICK,r=>e(new I_(Lo(t),r))))}_onmouseover(t,e){this._register(dt(t,Ea.MOUSE_OVER,r=>e(new I_(Lo(t),r))))}_onmouseleave(t,e){this._register(dt(t,Ea.MOUSE_LEAVE,r=>e(new I_(Lo(t),r))))}},hbt=class extends BE{constructor(t){super(),this._handleActivate=t.handleActivate,this.bgDomNode=document.createElement("div"),this.bgDomNode.className="xterm-arrow-background",this.bgDomNode.style.position="absolute",this.bgDomNode.style.width=t.bgWidth+"px",this.bgDomNode.style.height=t.bgHeight+"px",typeof t.top<"u"&&(this.bgDomNode.style.top="0px"),typeof t.left<"u"&&(this.bgDomNode.style.left="0px"),typeof t.bottom<"u"&&(this.bgDomNode.style.bottom="0px"),typeof t.right<"u"&&(this.bgDomNode.style.right="0px"),this.domNode=document.createElement("div"),this.domNode.className=t.className,this.domNode.style.position="absolute";let e=Math.min(t.bgWidth,t.bgHeight);this.domNode.style.width=e+"px",this.domNode.style.height=e+"px",typeof t.top<"u"&&(this.domNode.style.top=t.top+"px"),typeof t.left<"u"&&(this.domNode.style.left=t.left+"px"),typeof t.bottom<"u"&&(this.domNode.style.bottom=t.bottom+"px"),typeof t.right<"u"&&(this.domNode.style.right=t.right+"px"),this._pointerMoveMonitor=this._register(new VY),this._register(QM(this.bgDomNode,Ea.POINTER_DOWN,r=>this._arrowPointerDown(r))),this._register(QM(this.domNode,Ea.POINTER_DOWN,r=>this._arrowPointerDown(r))),this._pointerdownRepeatTimer=this._register(new nbt),this._pointerdownScheduleRepeatTimer=this._register(new Ik)}_arrowPointerDown(t){if(!t.target||!(t.target instanceof Element))return;let e=()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._handleActivate(),1e3/24,Lo(t))};this._handleActivate(),this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancelAndSet(e,200),this._pointerMoveMonitor.startMonitoring(t.target,t.pointerId,t.buttons,r=>{},()=>{this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancel()}),t.preventDefault()}},He=class{constructor(){this._listeners=[],this._disposed=!1}get event(){return this._event?this._event:(this._event=(e,r,i)=>{if(this._disposed)return fr(()=>{});let s={fn:e,thisArgs:r};this._listeners=this._listeners.slice(),this._listeners.push(s);let o=fr(()=>{let n=this._listeners.indexOf(s);n!==-1&&(this._listeners=this._listeners.slice(),this._listeners.splice(n,1))});return i&&(Array.isArray(i)?i.push(o):i.add(o)),o},this._event)}fire(e){if(this._disposed||!this._listeners.length)return;if(this._listeners.length===1){this._listeners[0].fn.call(this._listeners[0].thisArgs,e);return}let r=this._listeners;for(let i=0,s=r.length;i<s;++i)r[i].fn.call(r[i].thisArgs,e)}dispose(){this._disposed||(this._disposed=!0,this._listeners.length=0)}},tn;(t=>{function e(o,n){return o(a=>n.fire(a))}t.forward=e;function r(o,n){return(a,l,c)=>o(h=>a.call(l,n(h)),void 0,c)}t.map=r;function i(...o){return(n,a,l)=>{let c=new Ff;for(let h of o)c.add(h(d=>n.call(a,d)));return l&&(Array.isArray(l)?l.push(c):l.add(c)),c}}t.any=i;function s(o,n,a){return n(a),o(l=>n(l))}t.runAndSubscribe=s})(tn||={});var ubt=class R2{constructor(e,r,i,s,o,n,a){this._forceIntegerValues=e,this._scrollStateBrand=void 0,this._forceIntegerValues&&(r=r|0,i=i|0,s=s|0,o=o|0,n=n|0,a=a|0),this.rawScrollLeft=s,this.rawScrollTop=a,r<0&&(r=0),s+r>i&&(s=i-r),s<0&&(s=0),o<0&&(o=0),a+o>n&&(a=n-o),a<0&&(a=0),this.width=r,this.scrollWidth=i,this.scrollLeft=s,this.height=o,this.scrollHeight=n,this.scrollTop=a}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(e,r){return new R2(this._forceIntegerValues,typeof e.width<"u"?e.width:this.width,typeof e.scrollWidth<"u"?e.scrollWidth:this.scrollWidth,r?this.rawScrollLeft:this.scrollLeft,typeof e.height<"u"?e.height:this.height,typeof e.scrollHeight<"u"?e.scrollHeight:this.scrollHeight,r?this.rawScrollTop:this.scrollTop)}withScrollPosition(e){return new R2(this._forceIntegerValues,this.width,this.scrollWidth,typeof e.scrollLeft<"u"?e.scrollLeft:this.rawScrollLeft,this.height,this.scrollHeight,typeof e.scrollTop<"u"?e.scrollTop:this.rawScrollTop)}createScrollEvent(e,r){let i=this.width!==e.width,s=this.scrollWidth!==e.scrollWidth,o=this.scrollLeft!==e.scrollLeft,n=this.height!==e.height,a=this.scrollHeight!==e.scrollHeight,l=this.scrollTop!==e.scrollTop;return{inSmoothScrolling:r,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:o,heightChanged:n,scrollHeightChanged:a,scrollTopChanged:l}}},YY=class extends Dt{constructor(t){super(),this._scrollableBrand=void 0,this._onScroll=this._register(new He),this.onScroll=this._onScroll.event,this._smoothScrollDuration=t.smoothScrollDuration,this._scheduleAtNextAnimationFrame=t.scheduleAtNextAnimationFrame,this._state=new ubt(t.forceIntegerValues,0,0,0,0,0,0),this._smoothScrolling=null}dispose(){this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),super.dispose()}setSmoothScrollDuration(t){this._smoothScrollDuration=t}validateScrollPosition(t){return this._state.withScrollPosition(t)}getScrollDimensions(){return this._state}setScrollDimensions(t,e){let r=this._state.withScrollDimensions(t,e);this._setState(r,!!this._smoothScrolling),this._smoothScrolling?.acceptScrollDimensions(this._state)}getFutureScrollPosition(){return this._smoothScrolling?this._smoothScrolling.to:this._state}getCurrentScrollPosition(){return this._state}setScrollPositionNow(t){let e=this._state.withScrollPosition(t);this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),this._setState(e,!1)}setScrollPositionSmooth(t,e){if(this._smoothScrollDuration===0){this.setScrollPositionNow(t);return}if(this._smoothScrolling){t={scrollLeft:typeof t.scrollLeft>"u"?this._smoothScrolling.to.scrollLeft:t.scrollLeft,scrollTop:typeof t.scrollTop>"u"?this._smoothScrolling.to.scrollTop:t.scrollTop};let r=this._state.withScrollPosition(t);if(this._smoothScrolling.to.scrollLeft===r.scrollLeft&&this._smoothScrolling.to.scrollTop===r.scrollTop)return;let i;e?i=new X_(this._smoothScrolling.from,r,this._smoothScrolling.startTime,this._smoothScrolling.duration):i=X_.start(this._state,r,this._smoothScrollDuration),this._smoothScrolling.dispose(),this._smoothScrolling=i}else{let r=this._state.withScrollPosition(t);this._smoothScrolling=X_.start(this._state,r,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 t=this._smoothScrolling.tick(),e=this._state.withScrollPosition(t);if(this._setState(e,!0),!!this._smoothScrolling){if(t.isDone){this._smoothScrolling.dispose(),this._smoothScrolling=null;return}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}}_setState(t,e){let r=this._state;r.equals(t)||(this._state=t,this._onScroll.fire(this._state.createScrollEvent(r,e)))}},NM=class{constructor(t,e,r){this.scrollLeft=t,this.scrollTop=e,this.isDone=r}};function B_(t,e){let r=e-t;return function(i){return t+r*pbt(i)}}function dbt(t,e,r){return function(i){return i<r?t(i/r):e((i-r)/(1-r))}}var X_=class ZY{constructor(e,r,i,s){this.from=e,this.to=r,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,r,i){if(Math.abs(e-r)>2.5*i){let s,o;return e<r?(s=e+.75*i,o=r-.75*i):(s=e-.75*i,o=r+.75*i),dbt(B_(e,s),B_(o,r),.33)}return B_(e,r)}dispose(){this.animationFrameDisposable!==null&&(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 r=(e-this.startTime)/this.duration;if(r<1){let i=this._scrollLeft(r),s=this._scrollTop(r);return new NM(i,s,!1)}return new NM(this.to.scrollLeft,this.to.scrollTop,!0)}static start(e,r,i){i=i+10;let s=Date.now()-10;return new ZY(e,r,s,i)}};function fbt(t){return Math.pow(t,3)}function pbt(t){return 1-fbt(1-t)}var mbt=class extends Dt{constructor(t,e,r){super(),this._visibility=t,this._visibleClassName=e,this._invisibleClassName=r,this._domNode=null,this._isVisible=!1,this._isNeeded=!1,this._rawShouldBeVisible=!1,this._shouldBeVisible=!1,this._revealTimer=this._register(new Ik)}setVisibility(t){this._visibility!==t&&(this._visibility=t,this._updateShouldBeVisible())}setShouldBeVisible(t){this._rawShouldBeVisible=t,this._updateShouldBeVisible()}_applyVisibilitySetting(){return this._visibility===2?!1:this._visibility===3?!0:this._rawShouldBeVisible}_updateShouldBeVisible(){let t=this._applyVisibilitySetting();this._shouldBeVisible!==t&&(this._shouldBeVisible=t,this.ensureVisibility())}setIsNeeded(t){this._isNeeded!==t&&(this._isNeeded=t,this.ensureVisibility())}setDomNode(t){this._domNode=t,this._domNode.setClassName(this._invisibleClassName),this.setShouldBeVisible(!1)}ensureVisibility(){if(!this._isNeeded){this._hide(!1);return}this._shouldBeVisible?this._reveal():this._hide(!0)}_reveal(){this._isVisible||(this._isVisible=!0,this._revealTimer.setIfNotSet(()=>{this._domNode?.setClassName(this._visibleClassName)},0))}_hide(t){this._revealTimer.cancel(),this._isVisible&&(this._isVisible=!1,this._domNode?.setClassName(this._invisibleClassName+(t?" xterm-fade":"")))}},gbt=140,WY=class extends BE{constructor(t){super(),this._lazyRender=t.lazyRender,this._host=t.host,this._scrollable=t.scrollable,this._scrollByPage=t.scrollByPage,this._scrollbarState=t.scrollbarState,this._visibilityController=this._register(new mbt(t.visibility,"xterm-visible xterm-scrollbar "+t.extraScrollbarClassName,"xterm-invisible xterm-scrollbar "+t.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new VY),this._shouldRender=!0,this.domNode=new qm(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(dt(this.domNode.domNode,Ea.POINTER_DOWN,e=>this._domNodePointerDown(e)))}_createArrow(t){let e=this._register(new hbt(t));return this.domNode.domNode.appendChild(e.bgDomNode),this.domNode.domNode.appendChild(e.domNode),e}_createSlider(t,e,r,i){this.slider=new qm(document.createElement("div")),this.slider.setClassName("xterm-slider"),this.slider.setPosition("absolute"),this.slider.setTop(t),this.slider.setLeft(e),typeof r=="number"&&this.slider.setWidth(r),typeof i=="number"&&this.slider.setHeight(i),this.slider.setLayerHinting(!0),this.slider.setContain("strict"),this.domNode.domNode.appendChild(this.slider.domNode),this._register(dt(this.slider.domNode,Ea.POINTER_DOWN,s=>{s.button===0&&(s.preventDefault(),this._sliderPointerDown(s))})),this._onclick(this.slider.domNode,s=>{s.leftButton&&s.stopPropagation()})}_handleElementSize(t){return this._scrollbarState.setVisibleSize(t)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_handleElementScrollSize(t){return this._scrollbarState.setScrollSize(t)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_handleElementScrollPosition(t){return this._scrollbarState.setScrollPosition(t)&&(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(t){t.target===this.domNode.domNode&&this._handlePointerDown(t)}delegatePointerDown(t){let e=this.domNode.domNode.getClientRects()[0].top,r=e+this._scrollbarState.getSliderPosition(),i=e+this._scrollbarState.getSliderPosition()+this._scrollbarState.getSliderSize(),s=this._sliderPointerPosition(t);r<=s&&s<=i?t.button===0&&(t.preventDefault(),this._sliderPointerDown(t)):this._handlePointerDown(t)}_handlePointerDown(t){let e,r;if(t.target===this.domNode.domNode&&typeof t.offsetX=="number"&&typeof t.offsetY=="number")e=t.offsetX,r=t.offsetY;else{let s=ibt(this.domNode.domNode);e=t.pageX-s.left,r=t.pageY-s.top}let i=this._pointerDownRelativePosition(e,r);this._setDesiredScrollPositionNow(this._scrollByPage?this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(i):this._scrollbarState.getDesiredScrollPositionFromOffset(i)),t.button===0&&(t.preventDefault(),this._sliderPointerDown(t))}_sliderPointerDown(t){if(!t.target||!(t.target instanceof Element))return;let e=this._sliderPointerPosition(t),r=this._sliderOrthogonalPointerPosition(t),i=this._scrollbarState.clone();this.slider.toggleClassName("xterm-active",!0),this._pointerMoveMonitor.startMonitoring(t.target,t.pointerId,t.buttons,s=>{let o=this._sliderOrthogonalPointerPosition(s),n=Math.abs(o-r);if(Bk&&n>gbt){this._setDesiredScrollPositionNow(i.getScrollPosition());return}let a=this._sliderPointerPosition(s)-e;this._setDesiredScrollPositionNow(i.getDesiredScrollPositionFromDelta(a))},()=>{this.slider.toggleClassName("xterm-active",!1),this._host.handleDragEnd()}),this._host.handleDragStart()}_setDesiredScrollPositionNow(t){let e={};this.writeScrollPosition(e,t),this._scrollable.setScrollPositionNow(e)}updateScrollbarSize(t){this._updateScrollbarSize(t),this._scrollbarState.setScrollbarSize(t),this._shouldRender=!0,this._lazyRender||this.render()}isNeeded(){return this._scrollbarState.isNeeded()}},GY=class D2{constructor(e,r,i,s,o,n){this._scrollbarSize=Math.round(r),this._oppositeScrollbarSize=Math.round(i),this._arrowSize=Math.round(e),this._visibleSize=s,this._scrollSize=o,this._scrollPosition=n,this._computedAvailableSize=0,this._computedIsNeeded=!1,this._computedSliderSize=0,this._computedSliderRatio=0,this._computedSliderPosition=0,this._refreshComputedValues()}clone(){return new D2(this._arrowSize,this._scrollbarSize,this._oppositeScrollbarSize,this._visibleSize,this._scrollSize,this._scrollPosition)}setVisibleSize(e){let r=Math.round(e);return this._visibleSize!==r?(this._visibleSize=r,this._refreshComputedValues(),!0):!1}setScrollSize(e){let r=Math.round(e);return this._scrollSize!==r?(this._scrollSize=r,this._refreshComputedValues(),!0):!1}setScrollPosition(e){let r=Math.round(e);return this._scrollPosition!==r?(this._scrollPosition=r,this._refreshComputedValues(),!0):!1}setScrollbarSize(e){this._scrollbarSize=Math.round(e)}setArrowSize(e){let r=Math.round(e);this._arrowSize!==r&&(this._arrowSize=r,this._refreshComputedValues())}setOppositeScrollbarSize(e){this._oppositeScrollbarSize=Math.round(e)}static _computeValues(e,r,i,s,o){let n=Math.max(0,i-e),a=Math.max(0,n-2*r),l=s>0&&s>i;if(!l)return{computedAvailableSize:Math.round(n),computedIsNeeded:l,computedSliderSize:Math.round(a),computedSliderRatio:0,computedSliderPosition:0};let c=Math.round(Math.max(20,Math.floor(i*a/s))),h=(a-c)/(s-i),d=o*h;return{computedAvailableSize:Math.round(n),computedIsNeeded:l,computedSliderSize:Math.round(c),computedSliderRatio:h,computedSliderPosition:Math.round(d)}}_refreshComputedValues(){let e=D2._computeValues(this._oppositeScrollbarSize,this._arrowSize,this._visibleSize,this._scrollSize,this._scrollPosition);this._computedAvailableSize=e.computedAvailableSize,this._computedIsNeeded=e.computedIsNeeded,this._computedSliderSize=e.computedSliderSize,this._computedSliderRatio=e.computedSliderRatio,this._computedSliderPosition=e.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 r=e-this._arrowSize-this._computedSliderSize/2;return Math.round(r/this._computedSliderRatio)}getDesiredScrollPositionFromOffsetPaged(e){if(!this._computedIsNeeded)return 0;let r=e-this._arrowSize,i=this._scrollPosition;return r<this._computedSliderPosition?i-=this._visibleSize:i+=this._visibleSize,i}getDesiredScrollPositionFromDelta(e){if(!this._computedIsNeeded)return 0;let r=this._computedSliderPosition+e;return Math.round(r/this._computedSliderRatio)}},Obt=class extends WY{constructor(t,e,r){let i=t.getScrollDimensions(),s=t.getCurrentScrollPosition();if(super({lazyRender:e.lazyRender,host:r,scrollbarState:new GY(e.horizontalHasArrows?e.horizontalScrollbarSize:0,e.horizontal===2?0:e.horizontalScrollbarSize,e.vertical===2?0:e.verticalScrollbarSize,i.width,i.scrollWidth,s.scrollLeft),visibility:e.horizontal,extraScrollbarClassName:"xterm-horizontal",scrollable:t,scrollByPage:e.scrollByPage}),e.horizontalHasArrows)throw new Error("horizontalHasArrows is not supported in xterm.js");this._createSlider(Math.floor((e.horizontalScrollbarSize-e.horizontalSliderSize)/2),0,void 0,e.horizontalSliderSize)}_updateSlider(t,e){this.slider.setWidth(t),this.slider.setLeft(e)}_renderDomNode(t,e){this.domNode.setWidth(t),this.domNode.setHeight(e),this.domNode.setLeft(0),this.domNode.setBottom(0)}handleScroll(t){return this._shouldRender=this._handleElementScrollSize(t.scrollWidth)||this._shouldRender,this._shouldRender=this._handleElementScrollPosition(t.scrollLeft)||this._shouldRender,this._shouldRender=this._handleElementSize(t.width)||this._shouldRender,this._shouldRender}_pointerDownRelativePosition(t,e){return t}_sliderPointerPosition(t){return t.pageX}_sliderOrthogonalPointerPosition(t){return t.pageY}_updateScrollbarSize(t){this.slider.setHeight(t)}writeScrollPosition(t,e){t.scrollLeft=e}updateOptions(t){this.updateScrollbarSize(t.horizontal===2?0:t.horizontalScrollbarSize),this._scrollbarState.setOppositeScrollbarSize(t.vertical===2?0:t.verticalScrollbarSize),this._visibilityController.setVisibility(t.horizontal),this._scrollByPage=t.scrollByPage}},ybt=class extends WY{constructor(t,e,r){let i=t.getScrollDimensions(),s=t.getCurrentScrollPosition(),o=e.verticalHasArrows;super({lazyRender:e.lazyRender,host:r,scrollbarState:new GY(o?e.verticalScrollbarSize:0,e.vertical===2?0:e.verticalScrollbarSize,0,i.height,i.scrollHeight,s.scrollTop),visibility:e.vertical,extraScrollbarClassName:"xterm-vertical",scrollable:t,scrollByPage:e.scrollByPage}),this._arrowScrollDelta=0,this._setArrows(o,e.verticalScrollbarSize),this._createSlider(0,Math.floor((e.verticalScrollbarSize-e.verticalSliderSize)/2),e.verticalSliderSize,void 0)}_updateSlider(t,e){this.slider.setHeight(t),this.slider.setTop(e)}_renderDomNode(t,e){this.domNode.setWidth(e),this.domNode.setHeight(t),this.domNode.setRight(0),this.domNode.setTop(0)}handleScroll(t){return this._shouldRender=this._handleElementScrollSize(t.scrollHeight)||this._shouldRender,this._shouldRender=this._handleElementScrollPosition(t.scrollTop)||this._shouldRender,this._shouldRender=this._handleElementSize(t.height)||this._shouldRender,this._shouldRender}_pointerDownRelativePosition(t,e){return e}_sliderPointerPosition(t){return t.pageY}_sliderOrthogonalPointerPosition(t){return t.pageX}_updateScrollbarSize(t){this.slider.setWidth(t)}writeScrollPosition(t,e){t.scrollTop=e}_arrowScroll(t){let e=this._scrollable.getCurrentScrollPosition();this._scrollable.setScrollPositionNow({scrollTop:e.scrollTop+t})}_setArrows(t,e){if(this._arrowScrollDelta=e,(!this._arrowUp||!this._arrowDown)&&(this._arrowUp=this._createArrow({className:"xterm-scra xterm-arrow-up",top:0,left:0,bgWidth:e,bgHeight:e,handleActivate:()=>this._arrowScroll(-this._arrowScrollDelta)}),this._arrowDown=this._createArrow({className:"xterm-scra xterm-arrow-down",bottom:0,left:0,bgWidth:e,bgHeight:e,handleActivate:()=>this._arrowScroll(this._arrowScrollDelta)})),this._updateArrowSize(this._arrowUp,e),this._updateArrowSize(this._arrowDown,e),!this._arrowUp||!this._arrowDown)return;let r=t?"":"none";this._arrowUp.bgDomNode.style.display=r,this._arrowUp.domNode.style.display=r,this._arrowDown.bgDomNode.style.display=r,this._arrowDown.domNode.style.display=r}_updateArrowSize(t,e){t&&(t.bgDomNode.style.width=`${e}px`,t.bgDomNode.style.height=`${e}px`,t.domNode.style.width=`${e}px`,t.domNode.style.height=`${e}px`)}updateOptions(t){let e=t.verticalHasArrows?t.verticalScrollbarSize:0;this._scrollbarState.setArrowSize(e),this._setArrows(t.verticalHasArrows,t.verticalScrollbarSize),this.updateScrollbarSize(t.vertical===2?0:t.verticalScrollbarSize),this._scrollbarState.setOppositeScrollbarSize(0),this._visibilityController.setVisibility(t.vertical),this._scrollByPage=t.scrollByPage}},bbt=class{constructor(t,e,r){this.timestamp=t,this.deltaX=e,this.deltaY=r,this.score=0}},F2=class{constructor(){this._capacity=5,this._memory=[],this._front=-1,this._rear=-1}isPhysicalMouseWheel(){if(this._front===-1&&this._rear===-1)return!1;let e=1,r=0,i=1,s=this._rear;for(;s!==-1;){let o=s===this._front?e:Math.pow(2,-i);if(e-=o,r+=this._memory[s].score*o,s===this._front)break;s=(this._capacity+s-1)%this._capacity,i++}return r<=.5}acceptStandardWheelEvent(e){if(jE){Lo(e.browserEvent);let r=UY();this.accept(Date.now(),e.deltaX*r,e.deltaY*r)}else this.accept(Date.now(),e.deltaX,e.deltaY)}accept(e,r,i){let s=null,o=new bbt(e,r,i);this._front===-1&&this._rear===-1?(this._memory[0]=o,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]=o),o.score=this._computeScore(o,s)}_computeScore(e,r){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),r){let s=Math.abs(e.deltaX),o=Math.abs(e.deltaY),n=Math.abs(r.deltaX),a=Math.abs(r.deltaY),l=Math.max(Math.min(s,n),1),c=Math.max(Math.min(o,a),1),h=Math.max(s,n),d=Math.max(o,a);h%l===0&&d%c===0&&(i-=.5)}return Math.min(Math.max(i,0),1)}_isAlmostInt(e){return Math.abs(Math.round(e)-e)<.01}};F2.INSTANCE=new F2;var wbt=F2,kbt=class extends BE{constructor(t,e,r){super(),this._onScroll=this._register(new He),this.onScroll=this._onScroll.event,e=e??{};let i,s=!r;r?i=r:(e.mouseWheelSmoothScroll=!1,i=new YY({forceIntegerValues:!0,smoothScrollDuration:0,scheduleAtNextAnimationFrame:n=>NE(Lo(t),n)})),this._options=vbt(e),this._scrollable=i,this._register(this._scrollable.onScroll(n=>{this._handleScroll(n),this._onScroll.fire(n)})),s&&this._register(this._scrollable);let o={handleMouseWheel:n=>this._handleMouseWheel(n),handleDragStart:()=>this._handleDragStart(),handleDragEnd:()=>this._handleDragEnd()};this._verticalScrollbar=this._register(new ybt(this._scrollable,this._options,o)),this._horizontalScrollbar=this._register(new Obt(this._scrollable,this._options,o)),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(t),this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode),this._domNode.appendChild(this._verticalScrollbar.domNode.domNode),this._options.useShadows?(this._leftShadowDomNode=new qm(document.createElement("div")),this._leftShadowDomNode.setClassName("xterm-shadow"),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=new qm(document.createElement("div")),this._topShadowDomNode.setClassName("xterm-shadow"),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=new qm(document.createElement("div")),this._topLeftShadowDomNode.setClassName("xterm-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,n=>this._handleMouseOver(n)),this._onmouseleave(this._listenOnDomNode,n=>this._handleMouseLeave(n)),this._hideTimeout=this._register(new Ik),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=Bg(this._mouseWheelToDispose),super.dispose()}getDomNode(){return this._domNode}getScrollDimensions(){return this._scrollable.getScrollDimensions()}setScrollDimensions(t){this._scrollable.setScrollDimensions(t,!1)}setScrollPosition(t){t.reuseAnimation?this._scrollable.setScrollPositionSmooth(t,t.reuseAnimation):this._scrollable.setScrollPositionNow(t)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}updateClassName(t){this._options.className=t,fo&&(this._options.className+=" xterm-mac"),this._domNode.className="xterm-scrollable-element "+this._options.className}updateOptions(t){typeof t.handleMouseWheel<"u"&&(this._options.handleMouseWheel=t.handleMouseWheel,this._setListeningToMouseWheel(this._options.handleMouseWheel)),typeof t.mouseWheelScrollSensitivity<"u"&&(this._options.mouseWheelScrollSensitivity=t.mouseWheelScrollSensitivity),typeof t.fastScrollSensitivity<"u"&&(this._options.fastScrollSensitivity=t.fastScrollSensitivity),typeof t.scrollPredominantAxis<"u"&&(this._options.scrollPredominantAxis=t.scrollPredominantAxis),typeof t.horizontal<"u"&&(this._options.horizontal=t.horizontal),typeof t.vertical<"u"&&(this._options.vertical=t.vertical),typeof t.horizontalHasArrows<"u"&&(this._options.horizontalHasArrows=t.horizontalHasArrows),typeof t.verticalHasArrows<"u"&&(this._options.verticalHasArrows=t.verticalHasArrows),typeof t.horizontalScrollbarSize<"u"&&(this._options.horizontalScrollbarSize=t.horizontalScrollbarSize),typeof t.verticalScrollbarSize<"u"&&(this._options.verticalScrollbarSize=t.verticalScrollbarSize),typeof t.scrollByPage<"u"&&(this._options.scrollByPage=t.scrollByPage),this._horizontalScrollbar.updateOptions(this._options),this._verticalScrollbar.updateOptions(this._options),this._options.lazyRender||this._render()}delegateScrollFromMouseWheelEvent(t){this._handleMouseWheel(new FM(t))}_setListeningToMouseWheel(t){if(this._mouseWheelToDispose.length>0!==t&&(this._mouseWheelToDispose=Bg(this._mouseWheelToDispose),t)){let e=r=>{this._handleMouseWheel(new FM(r))};this._mouseWheelToDispose.push(dt(this._listenOnDomNode,Ea.MOUSE_WHEEL,e,{passive:!1}))}}_handleMouseWheel(t){if(t.browserEvent?.defaultPrevented)return;let e=wbt.INSTANCE;e.acceptStandardWheelEvent(t);let r=!1;if(t.deltaY||t.deltaX){let s=t.deltaY*this._options.mouseWheelScrollSensitivity,o=t.deltaX*this._options.mouseWheelScrollSensitivity;this._options.scrollPredominantAxis&&(this._options.scrollYToX&&o+s===0?o=s=0:Math.abs(s)>=Math.abs(o)?o=0:s=0),this._options.flipAxes&&([s,o]=[o,s]);let n=!fo&&t.browserEvent&&t.browserEvent.shiftKey;(this._options.scrollYToX||n)&&!o&&(o=s,s=0),t.browserEvent&&t.browserEvent.altKey&&(o=o*this._options.fastScrollSensitivity,s=s*this._options.fastScrollSensitivity);let a=this._scrollable.getFutureScrollPosition(),l={};if(s){let c=50*s,h=a.scrollTop-(c<0?Math.floor(c):Math.ceil(c));this._verticalScrollbar.writeScrollPosition(l,h)}if(o){let c=50*o,h=a.scrollLeft-(c<0?Math.floor(c):Math.ceil(c));this._horizontalScrollbar.writeScrollPosition(l,h)}l=this._scrollable.validateScrollPosition(l),(a.scrollLeft!==l.scrollLeft||a.scrollTop!==l.scrollTop)&&(this._options.mouseWheelSmoothScroll&&e.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(l):this._scrollable.setScrollPositionNow(l),r=!0)}let i=r;!i&&this._options.alwaysConsumeMouseWheel&&(i=!0),!i&&this._options.consumeMouseWheelIfScrollbarIsNeeded&&(this._verticalScrollbar.isNeeded()||this._horizontalScrollbar.isNeeded())&&(i=!0),i&&(t.preventDefault(),t.stopPropagation())}_handleScroll(t){this._shouldRender=this._horizontalScrollbar.handleScroll(t)||this._shouldRender,this._shouldRender=this._verticalScrollbar.handleScroll(t)||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 t=this._scrollable.getCurrentScrollPosition(),e=t.scrollTop>0,r=t.scrollLeft>0,i=r?" xterm-shadow-left":"",s=e?" xterm-shadow-top":"",o=r||e?" xterm-shadow-top-left-corner":"";this._leftShadowDomNode.setClassName(`xterm-shadow${i}`),this._topShadowDomNode.setClassName(`xterm-shadow${s}`),this._topLeftShadowDomNode.setClassName(`xterm-shadow${o}${s}${i}`)}}_handleDragStart(){this._isDragging=!0,this._reveal()}_handleDragEnd(){this._isDragging=!1,this._hide()}_handleMouseLeave(t){this._mouseIsOver=!1,this._hide()}_handleMouseOver(t){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)}};function vbt(t){let e={lazyRender:typeof t.lazyRender<"u"?t.lazyRender:!1,className:typeof t.className<"u"?t.className:"",useShadows:typeof t.useShadows<"u"?t.useShadows:!0,handleMouseWheel:typeof t.handleMouseWheel<"u"?t.handleMouseWheel:!0,flipAxes:typeof t.flipAxes<"u"?t.flipAxes:!1,consumeMouseWheelIfScrollbarIsNeeded:typeof t.consumeMouseWheelIfScrollbarIsNeeded<"u"?t.consumeMouseWheelIfScrollbarIsNeeded:!1,alwaysConsumeMouseWheel:typeof t.alwaysConsumeMouseWheel<"u"?t.alwaysConsumeMouseWheel:!1,scrollYToX:typeof t.scrollYToX<"u"?t.scrollYToX:!1,mouseWheelScrollSensitivity:typeof t.mouseWheelScrollSensitivity<"u"?t.mouseWheelScrollSensitivity:1,fastScrollSensitivity:typeof t.fastScrollSensitivity<"u"?t.fastScrollSensitivity:5,scrollPredominantAxis:typeof t.scrollPredominantAxis<"u"?t.scrollPredominantAxis:!0,mouseWheelSmoothScroll:typeof t.mouseWheelSmoothScroll<"u"?t.mouseWheelSmoothScroll:!0,listenOnDomNode:typeof t.listenOnDomNode<"u"?t.listenOnDomNode:null,horizontal:typeof t.horizontal<"u"?t.horizontal:1,horizontalScrollbarSize:typeof t.horizontalScrollbarSize<"u"?t.horizontalScrollbarSize:10,horizontalSliderSize:typeof t.horizontalSliderSize<"u"?t.horizontalSliderSize:0,horizontalHasArrows:typeof t.horizontalHasArrows<"u"?t.horizontalHasArrows:!1,vertical:typeof t.vertical<"u"?t.vertical:1,verticalScrollbarSize:typeof t.verticalScrollbarSize<"u"?t.verticalScrollbarSize:10,verticalHasArrows:typeof t.verticalHasArrows<"u"?t.verticalHasArrows:!1,verticalSliderSize:typeof t.verticalSliderSize<"u"?t.verticalSliderSize:0,scrollByPage:typeof t.scrollByPage<"u"?t.scrollByPage:!1};return e.horizontalSliderSize=typeof t.horizontalSliderSize<"u"?t.horizontalSliderSize:e.horizontalScrollbarSize,e.verticalSliderSize=typeof t.verticalSliderSize<"u"?t.verticalSliderSize:e.verticalScrollbarSize,fo&&(e.className+=" xterm-mac"),e}var N2=class extends Dt{constructor(t,e,r,i,s,o,n,a,l){super(),this._bufferService=r,this._coreService=s,this._optionsService=a,this._renderService=l,this._onRequestScrollLines=this._register(new He),this.onRequestScrollLines=this._onRequestScrollLines.event,this._isSyncing=!1,this._isHandlingScroll=!1,this._suppressOnScrollHandler=!1,this._needsSyncOnRender=!1;let c=this._register(new YY({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:h=>NE(i.window,h)}));this._register(this._optionsService.onSpecificOptionChange("smoothScrollDuration",()=>{c.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new kbt(e,{vertical:1,horizontal:2,useShadows:!1,mouseWheelSmoothScroll:!0,verticalHasArrows:this._optionsService.rawOptions.scrollbar?.showArrows??!1,...this._getChangeOptions()},c)),this._register(this._optionsService.onMultipleOptionChange(["scrollSensitivity","fastScrollSensitivity","scrollbar"],()=>this._scrollableElement.updateOptions(this._getChangeOptions()))),this._register(o.onProtocolChange(h=>{this._scrollableElement.updateOptions({handleMouseWheel:!(h&16)})})),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(tn.runAndSubscribe(n.onChangeColors,()=>{t.style.backgroundColor=n.colors.background.css,this._scrollableElement.getDomNode().style.backgroundColor=n.colors.background.css})),t.appendChild(this._scrollableElement.getDomNode()),this._register(fr(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=i.mainDocument.createElement("style"),e.appendChild(this._styleElement),this._register(fr(()=>this._styleElement.remove())),this._register(tn.runAndSubscribe(n.onChangeColors,()=>{this._styleElement.textContent=[".xterm .xterm-scrollable-element > .xterm-scrollbar > .xterm-slider {",` background: ${n.colors.scrollbarSliderBackground.css};`,"}",".xterm .xterm-scrollable-element > .xterm-scrollbar > .xterm-slider:hover {",` background: ${n.colors.scrollbarSliderHoverBackground.css};`,"}",".xterm .xterm-scrollable-element > .xterm-scrollbar > .xterm-slider.xterm-active {",` background: ${n.colors.scrollbarSliderActiveBackground.css};`,"}"].join(`
@@ -248,4 +248,4 @@ ${String(R)}`)}finally{P.replaying=!1,c()}}},_=async()=>{try{const P=await h("te
248
248
  ${h.newText}`:"")},d)),x.jsxs("div",{className:"acp-actions",children:[(l.options??[]).map(h=>x.jsx("button",{className:"button",disabled:i||!e.requests.includes(t),onClick:()=>{a(()=>e.respond(t,{outcome:{outcome:"selected",optionId:h.optionId}}))},children:h.name},h.optionId)),x.jsx("button",{className:"button",disabled:i||!e.requests.includes(t),onClick:()=>{a(()=>e.respond(t,{outcome:{outcome:"cancelled"}}))},children:D("Cancel")})]})]}):c==="cursor/create_plan"?x.jsxs(x.Fragment,{children:[x.jsx("p",{children:l.name}),x.jsx("pre",{children:l.plan}),x.jsx("div",{className:"acp-actions",children:["accepted","rejected"].map(h=>x.jsx("button",{className:"button",disabled:i||!e.requests.includes(t),onClick:()=>{a(()=>e.respond(t,{outcome:{outcome:h}}))},children:D(h==="accepted"?"Approve plan":"Reject plan")},h))})]}):x.jsxs(x.Fragment,{children:[(l.questions??[]).map(h=>x.jsxs("fieldset",{children:[x.jsx("legend",{children:h.prompt}),(h.options??[]).map(d=>x.jsxs("label",{className:"acp-choice",children:[x.jsx("input",{type:h.allowMultiple?"checkbox":"radio",name:t.requestId+h.id,checked:(o[h.id]??[]).includes(d.id),onChange:p=>n({...o,[h.id]:h.allowMultiple?p.target.checked?[...o[h.id]??[],d.id]:(o[h.id]??[]).filter(g=>g!==d.id):[d.id]})}),d.label]},d.id))]},h.id)),x.jsxs("div",{className:"acp-actions",children:[x.jsx("button",{className:"button primary",disabled:i||(l.questions??[]).some(h=>!o[h.id]?.length),onClick:()=>{a(()=>e.respond(t,{outcome:{outcome:"answered",answers:Object.entries(o).map(([h,d])=>({questionId:h,selectedOptionIds:d}))}}))},children:D("Submit answers")}),x.jsx("button",{className:"button",disabled:i||!e.requests.includes(t),onClick:()=>{a(()=>e.respond(t,{outcome:{outcome:"skipped"}}))},children:D("Skip")})]})]})]})}function gvt({agent:t,requestId:e}){j.useSyncExternalStore(t.subscribe,t.snapshot);const r=t.requests.find(i=>i.requestId===e);return x.jsx("div",{className:"acp-panel acp-review-editor",children:r?x.jsx(YE,{request:r,agent:t,full:!0}):x.jsx("p",{role:"status",children:D("This review is complete or has expired.")})})}function Ovt({agent:t}){j.useSyncExternalStore(t.subscribe,t.snapshot);const{kernel:e,runtime:r}=t.options,[i,s]=j.useState(e.configuration.get("agentACP.provider")??"codex"),o=Eh(i),[n,a]=j.useState(e.configuration.get(vc(i,"command"))||o.command),[l,c]=j.useState(e.configuration.get(vc(i,"args"))||JSON.stringify(o.args)),[h,d]=j.useState(!1),[p,g]=j.useState(!1),[b,v]=j.useState(!1),[_,$]=j.useState(!0),A=j.useId(),y=j.useRef(null),E=j.useRef(null),C=j.useRef(null),k=j.useRef(null),m=j.useRef(null),w=j.useRef(!0),P=t.connection,R=!!r?.connected,F=fZ(P),X=t.busy||t.connecting||t.updatingSettings||t.discovering||t.archived;j.useEffect(()=>{const W=C.current;if(!b||!W||!E.current)return;const N=E.current.getBoundingClientRect(),U=Math.min(320,innerWidth-16),K=N.top>innerHeight-N.bottom;Object.assign(W.style,{width:`${U}px`,maxHeight:`${Math.max(80,(K?N.top:innerHeight-N.bottom)-12)}px`,left:`${Math.max(8,Math.min(N.left,innerWidth-U-8))}px`,top:K?"auto":`${N.bottom+4}px`,bottom:K?`${innerHeight-N.top+4}px`:"auto"}),W.showPopover(),W.querySelector("button")?.focus();const ae=()=>v(!1);return window.addEventListener("resize",ae),()=>{W.hidePopover(),window.removeEventListener("resize",ae)}},[b]),j.useEffect(()=>{C.current?.matches(":popover-open")&&(v(!1),E.current?.focus())},[t.context.length]),j.useEffect(()=>{if(X)return;const W=m.current;m.current=null,W?.isConnected&&document.activeElement===document.body&&W.focus()},[X]),j.useEffect(()=>{w.current&&k.current&&(k.current.scrollTop=k.current.scrollHeight)},[t.snapshot()]);const te=W=>{const N=Eh(W);s(N.id),a(e.configuration.get(vc(N.id,"command"))||N.command),c(e.configuration.get(vc(N.id,"args"))||JSON.stringify(N.args))},H=()=>t.action(async()=>{let W;try{W=JSON.parse(l)}catch{throw new Error('Arguments must be a JSON array, such as ["acp"]')}if(!Array.isArray(W)||W.some(N=>typeof N!="string"))throw new Error("Arguments must be a JSON array of strings");await e.configuration.set("agentACP.provider",i,"user"),await e.configuration.set(vc(i,"command"),n,"user"),await e.configuration.set(vc(i,"args"),l,"user"),await t.connect({provider:i,command:n,args:W})});return x.jsxs("div",{className:"acp-panel",children:[x.jsxs("div",{className:"acp-header",children:[x.jsxs("div",{className:"acp-thread-heading",children:[x.jsx("strong",{title:t.title,children:D(t.title)}),x.jsxs("div",{className:"acp-status",role:"status",title:D(t.status),children:[x.jsx("span",{className:t.busy?"acp-dot working":"acp-dot"}),x.jsx("span",{children:D(t.status)})]}),x.jsx(Xe,{icon:"agent",label:"Open Agents",onClick:()=>t.openAgents()}),x.jsx(Xe,{icon:"clock",label:"History","aria-expanded":p,onClick:()=>g(!p)}),P?.sessionId&&x.jsx(Xe,{icon:"plus",label:"New conversation",disabled:t.busy||t.connecting||t.updatingSettings||t.discovering||t.activeSubagentCount>0,onClick:()=>{t.action(()=>t.newSession())}}),P?x.jsx(Xe,{icon:"power",label:"Disconnect",disabled:!R,onClick:()=>{t.action(()=>t.disconnect())}}):x.jsx("button",{className:"button acp-connect",disabled:!R||t.connecting,onClick:()=>{H()},children:D(t.connecting?"Connecting…":"Connect")}),t.connecting&&x.jsx(Xe,{icon:"x",label:"Cancel",onClick:()=>{t.action(()=>t.disconnect())}}),x.jsx(Xe,{icon:"gear",label:"Setup","aria-expanded":h,onClick:()=>d(!h)})]}),!R&&x.jsxs("p",{className:"muted",children:[D("Connect to a runtime workspace to use agents.")," ",x.jsx("button",{className:"button",onClick:()=>{t.action(()=>e.commands.execute("workspace.runtime"))},children:D("Runtime connection")})]}),h&&x.jsxs("div",{className:"acp-setup",children:[x.jsxs("p",{children:[D(o.setup)," ",x.jsx("a",{href:o.url,target:"_blank",rel:"noreferrer",children:D("Setup guide")})]}),x.jsxs("label",{children:[D("Executable"),x.jsx("input",{"aria-label":D("Agent executable"),value:n,disabled:!!P||t.connecting,onChange:W=>a(W.target.value)})]}),x.jsxs("label",{children:[D("Arguments (JSON array)"),x.jsx("input",{"aria-label":D("Agent arguments"),value:l,disabled:!!P||t.connecting,onChange:W=>c(W.target.value)})]}),x.jsx("p",{className:"muted",children:D("Connecting may download the adapter. Agents run with the trusted runtime's privileges and use its existing credentials.")})]}),P&&!P.sessionId&&x.jsxs("div",{className:"acp-actions",children:[P.authMethods.map(W=>x.jsxs("button",{className:"button",disabled:t.connecting,onClick:()=>{t.action(()=>t.authenticate(W.id))},children:[D("Sign in"),": ",W.name]},W.id)),x.jsx("button",{className:"button",disabled:t.connecting,onClick:()=>{t.action(()=>t.newSession())},children:D("Retry conversation")})]}),p&&x.jsx(hvt,{agent:t}),t.error&&x.jsx("p",{role:"alert",className:"error-text",children:t.error})]}),x.jsxs("div",{className:"acp-content",ref:k,onScroll:()=>{const W=k.current;W&&(w.current=W.scrollHeight-W.scrollTop-W.clientHeight<80),$(w.current)},children:[!t.messages.length&&x.jsxs("div",{className:"acp-welcome",children:[x.jsx(Fe,{name:"agentChat",size:28}),x.jsx("h2",{children:D("Work with your agent")}),x.jsx("p",{children:D("Ask a question, plan a change, or attach code from your editor. Follow tool calls and review approvals here.")})]}),t.subagents.size>0&&x.jsx(mZ,{agent:t,compact:!0}),x.jsx(cvt,{agent:t}),t.plan.length>0&&x.jsxs("details",{className:"acp-card",children:[x.jsxs("summary",{children:[D("Plan")," ·"," ",t.plan.filter(W=>W.status==="completed").length,"/",t.plan.length]}),x.jsx("ol",{children:t.plan.map((W,N)=>x.jsxs("li",{children:[x.jsxs("span",{className:"muted",children:[D(W.status)," · "]}),W.content]},N))})]}),Array.from(t.terminals.entries()).map(([W,N])=>x.jsxs("details",{className:"acp-card",children:[x.jsxs("summary",{children:[D("Terminal"),": ",N.command," ·"," ",N.exitStatus?D("Ended"):D("Running")]}),x.jsx("pre",{children:N.output}),N.truncated&&x.jsx("p",{className:"muted",children:D("Earlier output was truncated")})]},W)),x.jsx(dvt,{agent:t}),t.requests.map(W=>x.jsx(YE,{request:W,agent:t},W.requestId)),t.logs&&x.jsxs("details",{className:"acp-card",children:[x.jsx("summary",{children:D("Agent logs")}),x.jsx("pre",{children:t.logs})]})]}),!_&&x.jsx("button",{className:"button acp-jump",onClick:()=>{w.current=!0,$(!0),k.current&&(k.current.scrollTop=k.current.scrollHeight)},children:D("Jump to latest")}),t.requests.length>0&&x.jsxs("button",{className:"button acp-attention",onClick:()=>{k.current?.querySelector(".acp-approval")?.scrollIntoView({block:"center"}),k.current?.querySelector(".acp-approval button")?.focus()},children:[D("Agent needs your input")," · ",t.requests.length]}),x.jsxs("form",{className:"acp-composer",onSubmit:W=>{W.preventDefault(),t.action(()=>t.send())},children:[x.jsxs("div",{id:A,ref:C,popover:"auto",className:"acp-context-menu",role:"region","aria-label":D("Add context"),onToggle:W=>{W.newState==="closed"&&v(!1)},children:[x.jsxs("button",{type:"button",className:"button",onClick:()=>{t.action(()=>t.attachDiagnostics())},children:[x.jsx(Fe,{name:"warning",size:14}),D("Attach diagnostics")]}),x.jsxs("button",{type:"button",className:"button",onClick:()=>{t.action(()=>t.attach())},children:[x.jsx(Fe,{name:"files",size:14}),D("Attach file")]}),x.jsxs("button",{type:"button",className:"button",onClick:()=>{t.action(()=>t.attach(!0))},children:[x.jsx(Fe,{name:"focus",size:14}),D("Attach selection")]}),b&&x.jsx(uvt,{agent:t})]}),t.context.length>0&&x.jsxs("div",{className:"acp-attachments",children:[t.context.map((W,N)=>x.jsxs("div",{className:"acp-context-chip",children:[x.jsx(pZ,{item:W}),x.jsx(Xe,{icon:"x",label:D("Remove attachment {0}",{0:W.path}),onClick:()=>{t.context.splice(N,1),t.changed()}})]},N)),x.jsxs("p",{className:"acp-context-budget muted",children:[t.context.length,"/8 ",D("attachments")," ·"," ",(t.draft.length+t.context.reduce((W,N)=>W+N.text.length,0)).toLocaleString()," ",D("characters")]})]}),t.archived&&x.jsx("p",{className:"muted",children:D("Saved transcript. Choose Resume in History to continue this conversation.")}),x.jsx(Kkt,{inputRef:y,commands:t.commands,value:t.draft,onChange:W=>{t.draft=W,t.changed()},onSend:()=>{t.action(()=>t.send())}}),x.jsxs("div",{className:"acp-composer-toolbar",children:[x.jsx("button",{ref:E,type:"button",className:"icon-button","aria-label":D("Add context"),"data-tooltip":D("Add context"),"aria-controls":A,"aria-expanded":b,onClick:()=>v(!b),children:x.jsx(Fe,{name:"plus"})}),x.jsx(Xe,{icon:"diff",label:"Review changes",onClick:()=>{t.action(()=>e.commands.execute("view.scm"))}}),t.commands.length>0&&x.jsx(Mn,{label:D("Agent slash commands"),value:"",options:[{value:"",label:D("Slash commands")},...t.commands.map(W=>({value:W.name,label:"/"+W.name}))],onChange:W=>{W&&(t.draft="/"+W+" ",t.changed(),y.current?.focus())}}),x.jsx("span",{className:"muted acp-hint",children:D("Ctrl/Cmd+Enter to send")}),t.busy?x.jsx(Xe,{icon:"stop",label:t.cancelling?"Stopping…":"Stop",disabled:t.cancelling,onClick:()=>{t.action(()=>t.cancel())}}):x.jsx(Xe,{icon:"arrowUp",label:"Send",className:"icon-button acp-send",type:"submit",disabled:!P?.sessionId||!t.draft.trim()||!R||X})]})]}),x.jsxs("div",{className:"acp-footer",children:[P?x.jsxs("div",{className:"acp-provider",title:Eh(P.provider).name,children:[x.jsx(Fe,{name:"agent",size:14}),x.jsx("span",{children:Eh(P.provider).name})]}):x.jsx(Mn,{label:D("ACP provider"),icon:"agent",value:i,options:Vm.map(W=>({value:W.id,label:W.name})),disabled:t.connecting,onChange:te}),F.length>0&&x.jsxs("details",{className:"acp-session-options",children:[x.jsxs("summary",{children:[D("Session settings"),x.jsx(Fe,{name:"chevD",size:12})]}),x.jsx("div",{className:"acp-settings","aria-busy":t.updatingSettings,children:F.map(W=>x.jsxs("div",{className:"acp-setting",children:[x.jsx("span",{className:"acp-setting-label",title:W.description,children:D(W.name)}),x.jsx(Mn,{label:D(W.name),value:W.value,options:W.options,disabled:X,onChange:N=>{m.current=document.activeElement instanceof HTMLElement?document.activeElement:null,t.action(()=>t.setSessionControl(W,N))}})]},`${W.method}:${W.id}`))})]})]})]})}function yvt(t){return{manifest:{manifestVersion:1,id:"oxbit.agent-acp",name:"Agent ACP",version:"1.0.0",sdk:"^1.0.0",description:"Codex ACP, Cursor ACP, and Amp Agent ACP with conversations, editor context, tool activity, and approvals.",enabledByDefault:!1,environments:["browser","embedded"],activation:["*"],capabilities:["extensions","filesystem.read","filesystem.write","terminal"],configuration:mvt},activate(e){const r=new Hkt(t);e.own(r),e.own(e.services.register("agentACP",r)),e.own(e.contributions.register({id:"agent-acp",kind:"activityView",title:"Agent ACP",order:45,data:{icon:"agentChat"},component:()=>x.jsx(Ovt,{agent:r})})),e.own(e.contributions.register({id:"agent-acp-agents",kind:"activityView",title:"Agents",order:46,data:{icon:"agent"},component:()=>x.jsx(mZ,{agent:r,renderRequest:i=>x.jsx(YE,{request:i,agent:r},i.requestId)})})),e.own(e.commands.register({id:"agentACP.openAgents",title:"Open Agents",category:"Agent ACP",run:()=>r.openAgents()})),e.own(e.commands.register({id:"agentACP.open",title:"Open Agent ACP",category:"Agent ACP",run:()=>t.workbench.openPanel("agent-acp")}));for(const[i,s,o]of[["agentACP.attachFile","Attach Active File",()=>r.attach()],["agentACP.attachSelection","Attach Selection",()=>r.attach(!0)],["agentACP.stop","Stop Agent",()=>r.cancel()]])e.own(e.commands.register({id:i,title:s,category:"Agent ACP",run:async()=>{await t.kernel.commands.execute("agentACP.open"),await r.action(o)}}))}}}const ed=t=>`${(t/1e3).toFixed(1)} kB`,R0=["#818cf8","#34d399","#fbbf24","#f472b6","#60a5fa","#fb923c"],bvt=t=>{const e=t.eol==="CRLF"?t.text.replace(/\r\n/g,`
249
249
  `).replace(/\n/g,`\r
250
250
  `):t.text;if(t.encoding==="latin1")return Uint8Array.from(e,s=>s.charCodeAt(0));if(t.encoding==="utf-16le"){const s=new Uint8Array(e.length*2+2);s.set([255,254]);for(let o=0;o<e.length;o++)s[o*2+2]=e.charCodeAt(o)&255,s[o*2+3]=e.charCodeAt(o)>>8;return s}const r=new TextEncoder().encode(e);if(t.encoding!=="utf-8-bom")return r;const i=new Uint8Array(r.length+3);return i.set([239,187,191]),i.set(r,3),i},wvt={manifest:{manifestVersion:1,id:"orbitlabs.bundle-inspector",name:"Bundle Inspector",version:"1.0.0",sdk:"^1.0.0",environments:["browser","embedded"],activation:["onStartup","onCommand:bundle.analyze","onCommand:bundle.openReport"],commands:[{id:"bundle.analyze",title:"Bundle Inspector: Analyze",category:"Bundle Inspector",when:"workspace"},{id:"bundle.openReport",title:"Bundle Inspector: Open Report",category:"Bundle Inspector",when:"workspace"}],capabilities:["filesystem.read"],description:"Measure workspace file sizes and gzip sizes through the public extension SDK.",configuration:[{id:"bundle.outputDirectory",title:"Bundle output directory",type:"string",default:"dist",category:"Bundle Inspector"},{id:"bundle.budgetKB",title:"Bundle size budget (kB)",type:"number",default:500,min:1,max:1e6,category:"Bundle Inspector"}]},activate(t){let e={directory:"",files:[],total:0,gzip:0,truncated:!1,running:!1};const r=new Set,i={lines:[]},s=()=>{for(const _ of r)_()};let o;const n=()=>t.services.optional("workbench"),a=()=>o?.abort();t.signal.addEventListener("abort",a);const l=async()=>{o?.abort(),o=new AbortController;const _=o.signal,$=t.services.get("filesystem");e={directory:t.configuration.get("bundle.outputDirectory"),files:[],total:0,gzip:0,truncated:!1,running:!0};const A=e;n()?.openPanel("bundle"),s();const y=()=>{if(_.aborted||t.signal.aborted)throw new DOMException("Analysis cancelled","AbortError")};try{let E;try{E=await $.list(A.directory)}catch(k){if(!/ENOENT|not found|missing|does not exist/i.test(k instanceof Error?k.message:String(k)))throw k;A.directory="",E=await $.list("")}y(),E.length===0&&A.directory&&(A.directory="",E=await $.list(""));const C=async k=>{for(const m of k){if(y(),A.files.length>=2e3){A.truncated=!0;return}if(m.kind==="directory"){["node_modules",".git",".oxbit"].includes(m.name)||await C(await $.list(m.path));continue}const w={path:m.path,bytes:m.size??0};if(!m.size||m.size<=2e6)try{const P=await $.read(m.path),R=bvt(P);if(w.bytes=R.length,typeof CompressionStream<"u"&&(w.gzip=(await new Response(new Blob([R]).stream().pipeThrough(new CompressionStream("gzip"))).arrayBuffer()).byteLength),/\.[cm]?js$/.test(m.name))try{const F=JSON.parse((await $.read(`${m.path}.map`)).text);Array.isArray(F.sources)&&(w.modules=F.sources.length)}catch{}}catch(P){w.error=P instanceof Error?P.message:String(P)}y(),A.files.push(w),A.total+=w.bytes,A.gzip+=w.gzip??0}};await C(E),A.files.sort((k,m)=>m.bytes-k.bytes||k.path.localeCompare(m.path))}catch(E){if(_.aborted||t.signal.aborted)return;A.error=E instanceof Error?E.message:String(E)}finally{A.running=!1,!_.aborted&&!t.signal.aborted&&(i.lines.push(`${new Date().toISOString()} ${A.directory||"workspace"}: ${A.files.length} files, ${A.total} bytes${A.error?`, ${A.error}`:""}`),i.lines.length>200&&i.lines.shift(),s())}return A},c=()=>n()?.openView("bundle.report","Bundle report",b,{},{contributionId:"bundle.report"});function h(){const[,_]=j.useState(0);return j.useEffect(()=>{const $=()=>_(y=>y+1);r.add($);const A=t.configuration.subscribe($);return()=>{r.delete($),A()}},[]),e}function d(){const _=h();return j.createElement("div",{style:{display:"flex",height:14,gap:2,borderRadius:4,overflow:"hidden",margin:"12px 0"},"aria-label":"File size distribution"},..._.files.slice(0,40).map(($,A)=>j.createElement("span",{key:$.path,title:`${$.path}: ${$.bytes} bytes`,style:{background:R0[A%R0.length],width:`${_.total?$.bytes/_.total*100:0}%`}})))}function p(){const _=h();return j.createElement("div",{style:{display:"flex",alignItems:"center",gap:12,flexWrap:"wrap"}},j.createElement("strong",null,ed(_.total)),j.createElement("span",{className:"muted"},`${_.files.length} files · ${_.directory||"workspace"}/ · budget ${t.configuration.get("bundle.budgetKB")} kB`),j.createElement("button",{className:"button",disabled:_.running,onClick:()=>{t.commands.execute("bundle.analyze")}},_.running?"Analyzing…":"Analyze"),j.createElement("button",{className:"button",onClick:c},"Open report"))}function g(){const _=h();return j.createElement("section",{className:"bundle-inspector",style:{padding:16},"aria-label":"Bundle Inspector"},j.createElement(p),j.createElement(d),_.error?j.createElement("p",{role:"alert"},_.error):j.createElement("p",{className:"muted"},_.files.length?`${ed(_.gzip)} measured gzip${_.truncated?" · First 2,000 files":""}`:"Run Analyze to measure files in the output directory."))}function b(){const _=h(),$=t.configuration.get("bundle.budgetKB")*1e3,A=j.createElement("thead",null,j.createElement("tr",null,...["File","Size","Gzip","Modules","Share"].map(C=>j.createElement("th",{key:C,style:{padding:8}},C)))),y=_.files.map((C,k)=>j.createElement("tr",{key:C.path,title:C.error},j.createElement("td",{style:{padding:8,fontFamily:"var(--font-mono)"}},C.path),j.createElement("td",null,ed(C.bytes)),j.createElement("td",null,C.gzip===void 0?"Not measured":ed(C.gzip)),j.createElement("td",null,C.modules===void 0?"No source map":String(C.modules)),j.createElement("td",null,j.createElement("span",{style:{display:"block",height:8,background:R0[k%R0.length],width:`${_.total?C.bytes/_.total*100:0}%`,minWidth:2}})))),E=j.createElement("table",{style:{width:"100%",borderCollapse:"collapse",textAlign:"left",fontSize:12}},A,j.createElement("tbody",null,...y));return j.createElement("article",{style:{padding:20,overflow:"auto",height:"100%",maxWidth:880,margin:"0 auto",boxSizing:"border-box"},"aria-label":"Bundle report"},j.createElement("h2",null,"Bundle report"),j.createElement(p),j.createElement(d),E,j.createElement("p",{className:"muted"},`Budget ${ed($)} · ${_.total<=$?"Within budget":"Over budget"}${_.truncated?" · First 2,000 files":""}`))}function v(){const _=h();return j.createElement("span",null,_.running?"Analyzing…":`Bundle ${_.total>=1e9?`${(_.total/1e9).toFixed(1)} GB`:_.total>=1e6?`${(_.total/1e6).toFixed(1)} MB`:ed(_.total)}`)}t.commands.register({id:"bundle.analyze",title:"Bundle Inspector: Analyze",category:"Bundle Inspector",when:"workspace && bundleExt",run:l}),t.commands.register({id:"bundle.openReport",title:"Bundle Inspector: Open Report",category:"Bundle Inspector",when:"workspace && bundleExt",run:c}),t.contributions.register({id:"bundle",kind:"panel",title:"Bundle Inspector",order:90,component:g}),t.contributions.register({id:"bundle.status",kind:"statusItem",title:"Bundle Inspector",order:90,command:"bundle.analyze",component:v,data:{label:"Bundle"}}),t.contributions.register({id:"bundle.output",kind:"outputChannel",title:"Bundle Inspector",data:i}),t.contributions.register({id:"bundle.report",kind:"documentView",title:"Bundle report",component:b,command:"bundle.openReport",data:{matches:_=>_.split("/").pop()==="package.json"}}),t.context.set("bundleExt",!0),t.subscribe(()=>{a(),t.signal.removeEventListener("abort",a),n()?.closeView("bundle.report"),r.clear(),i.lines.length=0,t.context.set("bundleExt",!1)})}},D0=()=>Aj({},{});class kvt{constructor(e,r,i){this.storage=e,this.filesystem=r,this.runtime=i,this.key="workspace-settings:"+r.id,this.recoveryKey=this.key+":files",this.fileSettings=!!i&&i.session?.owner!==!1}storage;filesystem;runtime;key;recoveryKey;loaded;snapshot;local=D0();pending=[];queue=Promise.resolve();kernel;notify;errors=[];subscriptions=[];disposed=!1;fileSettings;async get(e){return e!=="settings"?this.storage.get(e):(this.loaded??=this.load(),structuredClone(await this.loaded))}async load(){const e=await this.storage.get("settings"),r=await this.storage.get("profile-settings"),i=await this.storage.get(this.key);if(this.local={...D0(),...e,...r,...i},!this.fileSettings)return this.local;const s=await this.storage.get(this.recoveryKey);let o=structuredClone(this.local);if(s)this.snapshot=s.snapshot,this.local=s.local,this.pending=s.pending;else{const n=await this.storage.get(this.key+":pending");if(n){const a=Aj({},n.lastText?_G(JSON.parse(n.lastText)):{});o={...o,workspace:a.workspace,workspaceLanguages:a.workspaceLanguages},this.local={...this.local,...n.value},this.pending=Fp(o,this.local)}this.snapshot={layers:o,files:[]}}try{const n=await this.runtime.request("settings.read",{legacy:s?.snapshot.layers??o});this.snapshot=n,this.pending.length||(this.local=n.layers),this.reportFiles(n),await this.flush(),await this.cache()}catch(n){this.report(`Settings are retained locally: ${String(n)}`)}return await this.cache(),this.local}async set(e,r){if(e!=="settings")return this.storage.set(e,r);const i=structuredClone(r);if(!this.fileSettings){this.local=i,await this.storage.set("profile-settings",{user:i.user,userLanguages:i.userLanguages}),await this.storage.set(this.key,{workspace:i.workspace,workspaceLanguages:i.workspaceLanguages});return}const s=Fp(this.local,i);this.local=i,this.pending.push(...s),this.snapshot&&!Fp(this.snapshot.layers,this.local).length&&(this.pending=[]),this.queue=this.queue.catch(()=>{}).then(async()=>{await this.cache();try{await this.flush()}catch(o){this.report(`Settings are retained locally: ${String(o)}`)}}),await this.queue}async cache(){this.snapshot&&(await this.storage.set(this.recoveryKey,{snapshot:this.snapshot,local:this.local,pending:this.pending}),await this.storage.delete(this.key+":pending"))}async flush(){if(!this.pending.length||this.disposed)return;if(!this.runtime?.connected)throw new Error("Reconnect to save settings to disk.");this.snapshot?.files.length||(this.snapshot=await this.runtime.request("settings.read",{legacy:this.snapshot?.layers??D0()}));const e=[...this.pending],r=structuredClone(this.local),i=await this.runtime.request("settings.patch",{changes:e});this.pending.splice(0,e.length),this.snapshot=i,!this.pending.length&&(!this.kernel||!Fp(r,this.kernel.configuration.export()).length)&&this.apply(i),await this.cache()}apply(e){this.snapshot=e,this.local=structuredClone(e.layers),this.kernel?.configuration.import(this.local,{persist:!1}),this.reportFiles(e)}reportFiles(e){for(const r of e.files)r.error&&this.report(`${r.path}: ${r.error}. Keeping the last valid settings.`)}report(e){this.notify?this.notify(e,"error"):this.errors.push(e)}attach(e,r){this.kernel=e,this.notify=r;for(const s of this.errors)r(s,"error");if(this.errors=[],!this.fileSettings)return;const i=()=>{this.queue=this.queue.catch(()=>{}).then(async()=>{if(!this.disposed)try{if(await this.flush(),this.pending.length||Fp(this.local,e.configuration.export()).length)return;this.apply(await this.runtime.request("settings.read")),await this.cache()}catch(s){this.report(`Settings reload failed: ${String(s)}`)}})};this.subscriptions.push(this.runtime.subscribe("settings.changed",i)),this.subscriptions.push(this.runtime.subscribe("connection.change",s=>{s.state==="connected"&&i()}))}async resolveWorkspaceSettings(e){if(!this.runtime?.connected||!this.kernel||!this.fileSettings)throw new Error("Connect to the workspace owner runtime first");await this.queue;const r=await this.runtime.request("settings.read");if(e==="disk")this.pending=[],this.apply(r);else{const i={user:yb(r.layers,"user"),workspace:yb(r.layers,"workspace")};this.pending=this.pending.map(s=>{let o=i[s.scope];for(const l of s.path.slice(0,-1))Ih(o[l])||(o[l]={}),o=o[l];const n=s.path.at(-1),a=o[n];return s.value===void 0?delete o[n]:o[n]=s.value,{scope:s.scope,path:s.path,...a===void 0?{}:{before:a},...s.value===void 0?{}:{value:s.value}}}),this.pending.length?await this.flush():this.apply(r)}await this.cache()}async delete(e){e==="settings"?await this.set(e,D0()):await this.storage.delete(e)}async dispose(){this.disposed=!0;for(const e of this.subscriptions)e();await this.queue.catch(()=>{})}}const kj="oxbit.iconPack.seeded",vvt=()=>typeof localStorage>"u"?void 0:localStorage;async function Svt(t){for(const e of[i2,e2])try{const r=vvt(),i=e.id===i2.id?kj:`${kj}.${e.id}`;if(r?.getItem(i)===e.revision)continue;const s=(await t.read()).find(o=>o.id===e.id);s?.revision!==e.revision&&(await t.put(e),!s&&!e.enabled&&await t.enable(e.id,!1)),r?.setItem(i,e.revision)}catch{}}async function xvt({filesystem:t,runtime:e,git:r,persistence:i,active:s=!0,protectUnload:o=!0,preserveFilesystem:n=!1,additionalExtensionOrigins:a,iconPackStore:l}){const c=new kvt(i,t,e);await c.get("settings");const h=Mwe({environment:"browser",persistence:c,additionalExtensionOrigins:a}),d=new sSe(t,i,h),p=new gme(h,d,t,i);c.attach(h,(v,_)=>p.notify(v,_)),e&&(h.commands.register({id:"settings.reloadWorkspace",title:"Reload Settings from Disk",run:async()=>{await p.ask(D("Reload settings?"),D("Discard pending user and workspace changes and reload the merged settings files?"),[D("Reload"),D("Cancel")])===D("Reload")&&await c.resolveWorkspaceSettings("disk")}}),h.commands.register({id:"settings.saveWorkspace",title:"Save Local Settings to Disk",run:async()=>{await p.ask(D("Save local settings?"),D("Apply pending user and workspace changes over the current disk settings?"),[D("Save"),D("Cancel")])===D("Save")&&await c.resolveWorkspaceSettings("local")}})),h.services.register("workbench",p),h.services.register("documents",d),h.services.register("filesystem",t),h.services.register("persistence",i),e&&h.services.register("runtime",e),h.context.set("workspace",!0),h.context.set("connected",!!e?.connected),h.context.set("trusted",!!e?.session?.trusted),h.context.set("editor",!1);const g=l??new cwe,b=new hwe(h,g,v=>p.notify(v,"warning",{source:"Icon Packs",actions:[{title:"Manage Icon Packs",command:"iconPacks.manage"}]}));h.services.register("iconThemes",b);try{await Svt(g),await b.initialize().catch(N=>p.notify(`Icon packs could not be loaded: ${String(N)}`,"warning")),await d.restore();const v={kernel:h,documents:d,filesystem:t,runtime:e,git:r,workbench:p},_=e?.subscribe("connection.change",({state:N})=>{h.context.set("connected",N==="connected"),h.context.set("trusted",N==="connected"&&!!e.session?.trusted),h.events.emit("connection.change",{state:N})}),$=e?.subscribe("workspace.trust",({trusted:N})=>{h.context.set("trusted",N===!0),p.touch()}),A=[p4e(v),o8e(v),R3e(v),D3e(v),n8e(v),m8e(v),bme(p),a4e(v),h4e(v),O4e(v),M0t(v),F0t(),N0t(),Eyt(v),Dyt(v),$0t(v),Q0t(v),Ekt(v),Nkt(v),Ukt(v),Ykt(v),yvt(v),wvt];for(const N of A)h.extensions.register(N);await s8e(i,h.configuration.get("workbench.colorTheme"));const y=await i.get("extension-disabled")||[],E=await i.get("extension-enabled")||[];for(const N of A)(y.includes(N.manifest.id)||N.manifest.enabledByDefault===!1&&!E.includes(N.manifest.id))&&await h.extensions.disable(N.manifest.id);for(const[N,U]of Object.entries(await i.get("extension-artifacts")||{}))try{if(h.extensions.list().some(K=>K.manifest.id===N)){const K=await import(U);await h.extensions.update(K.default||K.extension)}else await h.extensions.load(U,{activate:!1});y.includes(N)&&await h.extensions.disable(N)}catch(K){p.notify(`Extension recovery failed: ${String(K)}`,"error")}await h.extensions.trigger("onStartup"),await h.extensions.trigger("onWorkspace");for(const N of d.documents.values())await h.extensions.trigger("onLanguage:"+Zr(h,N.path).id);for(const N of h.extensions.list())N.state==="failed"&&p.notify(`${N.manifest.name}: ${N.error}`,"error");const C=d.subscribe(p.documentChanged);await p.restore();const k=t.id==="browser";if(p.set({projectName:e?e.session?.workspaceName??"Runtime workspace":k?"orbit-dash":"Directory workspace"}),!p.state.groups.some(N=>N.tabs.length)){const N=k?["src/hooks/useTelemetry.ts","src/App.tsx","src/components/Chart.tsx","README.md"]:[p.state.files.find(U=>U.kind==="file"&&/\.(tsx?|jsx?|md)$/.test(U.path))?.path].filter(Boolean);for(const U of N)try{await p.openFile(U,{preview:!1})}catch(K){p.notify(String(K),"error")}k&&(p.set({groups:p.state.groups.map(U=>({...U,tabs:U.tabs.map(K=>K.path==="src/App.tsx"?{...K,pinned:!0}:K)})),panel:!0,panelId:"terminal"}),await p.openFile("src/hooks/useTelemetry.ts"))}const m=new Map,w=async N=>{try{d.get(N)?.dirty&&await d.save(N)}catch(U){p.notify(String(U),"error")}},P=h.events.on("document.change",({id:N})=>{const U=[...d.documents.values()].find(K=>K.id===N);U&&(clearTimeout(m.get(U.path)),h.configuration.get("files.autoSave",Zr(h,U.path).id)==="afterDelay"&&m.set(U.path,setTimeout(()=>{w(U.path)},h.configuration.get("files.autoSaveDelay",Zr(h,U.path).id)??1e3)))}),R=h.configuration.subscribe(()=>{for(const N of m.values())clearTimeout(N);m.clear();for(const N of d.documents.values())N.dirty&&h.configuration.get("files.autoSave",Zr(h,N.path).id)==="afterDelay"&&m.set(N.path,setTimeout(()=>{w(N.path)},h.configuration.get("files.autoSaveDelay",Zr(h,N.path).id)??1e3))}),F=N=>{if(!s)return;const U=N.target?.closest(".cm-editor");if(!(!U||N.relatedTarget instanceof Node&&U.contains(N.relatedTarget)))for(const K of d.documents.values())h.configuration.get("files.autoSave",Zr(h,K.path).id)==="onFocusChange"&&w(K.path)},X=()=>{if(s)for(const N of d.documents.values())h.configuration.get("files.autoSave",Zr(h,N.path).id)==="onWindowChange"&&w(N.path)},te=()=>{d.persist(),p.persist()},H=N=>{te(),o&&[...d.documents.values()].some(U=>U.dirty)&&(N.preventDefault(),N.returnValue="")};document.addEventListener("focusout",F),window.addEventListener("blur",X),window.addEventListener("pagehide",te),window.addEventListener("beforeunload",H);const W={kernel:h,documents:d,filesystem:t,workbench:p,runtime:e,setActive(N){s=N},async persist(){await h.configuration.flush?.(),await c.set("settings",h.configuration.export()),await d.persist(),await p.persist()},async dispose(){document.removeEventListener("focusout",F),window.removeEventListener("blur",X),window.removeEventListener("pagehide",te),window.removeEventListener("beforeunload",H);for(const N of m.values())clearTimeout(N);P.dispose(),R(),_?.(),$?.(),C(),await W.persist(),b.dispose(),await c.dispose(),p.dispose(),h.dispose(),d.dispose(),e?.dispose(),n||t.dispose?.()}};return h.events.emit("workspace.change",{id:t.id,state:"opened"}),h.events.emit("connection.change",{state:e?.connected?"connected":"disconnected"}),W}catch(v){throw b.dispose(),await c.dispose(),p.dispose(),h.dispose(),d.dispose(),e?.dispose(),n||t.dispose?.(),v}}globalThis.__OXBIT_REACT__=Ife;Ej(document);const ua=new Hfe;let J_,vj=Promise.resolve();const dl=new Dj(ua,"browser");function $vt(){const t=new URLSearchParams(location.hash.replace(/^#/,"")),e=t.get("pair")||void 0,r=t.get("open")||void 0;return(e||r)&&history.replaceState(null,"",location.pathname+location.search),{pair:e,open:r}}async function _vt(t,e){const r=new rA(t);try{if(await r.connect(),!e||r.session?.owner)return r}catch(s){if(!e)throw r.dispose(),s}r.dispose();const i=new rA(t);try{return await i.pair(e),await i.connect(),i}catch(s){throw i.dispose(),s}}function td(t,e){const r=vj.then(()=>Avt(t,e));return vj=r.then(()=>{},()=>{}),r}async function Avt(t,e){await J_?.persist();const r=await xvt({filesystem:t,runtime:e,persistence:ua,preserveFilesystem:t===dl});return await J_?.dispose(),J_=r,r}function Cvt(){const[t,e]=j.useState(),[r,i]=j.useState(""),[s,o]=j.useState(),[n,a]=j.useState(!0),l=j.useCallback(d=>{e(d),a(!1),globalThis.__oxbit={...d,ready:!0,connectRuntime:h,useBrowserWorkspace:c,openFile:(p,g)=>d.workbench.openFile(p,g),runCommand:(p,g)=>d.workbench.run(p,g)}},[]),c=j.useCallback(async()=>{a(!0);try{(await dl.list()).length||await dl.import(W4);const d=await td(dl);await ua.set("last-host","browser"),l(d),o(void 0)}catch(d){i(String(d)),a(!1)}},[l]),h=j.useCallback(async(d,p)=>{a(!0);const g=new rA(d);try{await g.pair(p),await g.connect();const b=await td(new Q4(g),g);await ua.set("last-host",{url:d}),l(b),o(void 0)}catch(b){throw g.dispose(),a(!1),b}},[l]);return j.useEffect(()=>{let d=!1;return(async()=>{const{pair:g,open:b}=$vt();let v=await ua.get("last-host"),_,$="";if(g||v?.url)try{_=await _vt(g?location.origin:v.url,g),g&&(v={url:_.url},await ua.set("last-host",v))}catch(C){g&&($=String(C))}const A=v==="directory"?await Jfe(ua):void 0,y=_?new Q4(_):A??dl;y===dl&&!(await dl.list()).length&&await dl.import(W4);let E=await td(y,_);if($&&E.workbench.notify(D("Runtime pairing failed: {0}",{0:$}),"error"),v==="directory"&&!A&&E.workbench.notify(D("Directory access needs permission. Open the directory again; drafts remain stored.")),v?.providerId){const C=E.kernel.contributions.list("filesystem").find(m=>m.id===v.providerId),k=C?.data;if(k&&typeof k.open=="function")try{E=await td(await k.open()),E.workbench.set({projectName:C.title})}catch(m){E.workbench.notify(String(m),"error")}else E.workbench.notify(D("The saved filesystem provider is unavailable. Enable its extension to reopen the workspace."))}if(b)try{await E.workbench.openFile(b,{preview:!1})}catch(C){E.workbench.notify(D("Could not open {0}: {1}",{0:b,1:String(C)}),"error")}d||l(E)})().catch(g=>{i(String(g)),a(!1)}),()=>{d=!0}},[l]),j.useEffect(()=>{if(!t)return;const d=(g,b,v)=>t.kernel.commands.register({id:g,title:b,category:"Workspace",run:v}),p=[d("workspace.open","Open Folder…",()=>o("workspace")),d("workspace.switch","Switch Workspace…",()=>o("workspace")),d("workspace.close","Close Workspace",()=>{t.kernel.context.set("workspace",!1),t.workbench.set({workspaceOpen:!1}),t.kernel.events.emit("workspace.change",{id:t.filesystem.id,state:"closed"})}),d("workspace.browser","Open Browser Workspace",c),d("workspace.runtime","Connect Runtime",()=>o("connection")),d("workspace.export","Export Browser Workspace",async()=>{const g=[],b=[];for await(const A of Nj(t.filesystem))if(A.kind==="file"){const y=t.documents.get(A.path),E=y?{text:y.text.toString(),encoding:y.encoding,eol:y.eol}:await t.filesystem.read(A.path);g.push({path:A.path,...E})}else b.push(A.path);const v=new Blob([JSON.stringify({version:1,files:g,directories:b},null,2)],{type:"application/json"}),_=URL.createObjectURL(v),$=document.createElement("a");$.href=_,$.download="oxbit-workspace.json",$.click(),setTimeout(()=>URL.revokeObjectURL(_),1e3)})];return t.workbench.touch(),()=>p.forEach(g=>g.dispose())},[t,c]),t?x.jsx(Tvt,{session:t,overlay:s,close:()=>o(void 0),connectRuntime:h,useBrowserWorkspace:c,onConnect:()=>o("connection"),onOpenWorkspace:()=>o("workspace"),openProvider:async d=>{const p=t.kernel.contributions.list("filesystem").find(b=>b.id===d),g=p?.data;try{if(!g||typeof g.open!="function")throw new Error("Filesystem provider is unavailable");const b=await td(await g.open());b.workbench.set({projectName:p.title}),await ua.set("last-host",{providerId:d}),l(b),o(void 0)}catch(b){t.workbench.notify(String(b),"error")}},openDirectory:async()=>{try{const d=await epe(ua),p=await td(d);await ua.set("last-host",d.id.startsWith("directory:")?"directory":"browser"),l(p),o(void 0)}catch(d){t.workbench.notify(String(d),"error")}},importWorkspace:async d=>{try{const p=JSON.parse(await d.text());await dl.import(p),await c()}catch(p){t.workbench.notify(String(p),"error")}}}):x.jsx("div",{className:"workbench","data-theme":"dark","data-density":"compact",children:x.jsxs("div",{className:"empty-state",style:{height:"100%"},children:[x.jsx(lT,{}),x.jsx("strong",{children:D(n?"Opening workspace…":"Workspace failed to open")}),r&&x.jsx("p",{role:"alert",children:r}),r&&x.jsx("button",{className:"button",onClick:()=>{c()},children:D("Retry")})]})})}function Tvt({session:t,overlay:e,close:r,connectRuntime:i,useBrowserWorkspace:s,onConnect:o,onOpenWorkspace:n,openDirectory:a,openProvider:l,importWorkspace:c}){j.useSyncExternalStore(t.workbench.subscribe,t.workbench.snapshot),Tj(t.kernel.configuration.get("workbench.locale"));const h=Kg(t.kernel);return x.jsxs(x.Fragment,{children:[x.jsx(kme,{workbench:t.workbench,runtime:t.runtime,onConnect:o,onOpenWorkspace:n}),e&&x.jsx("div",{className:"runtime-connect","data-theme":h,"data-theme-pack":pi(t.kernel).packId,"data-density":"compact",style:{...yT(t.kernel),color:"var(--fg)",fontFamily:"var(--font-body-font-family)",fontSize:"var(--font-body-font-size)"},children:e==="connection"?x.jsx(Pvt,{runtime:t.runtime,close:r,connect:i,workbench:t.workbench}):x.jsx(Rme,{session:t,close:r,useBrowserWorkspace:s,openDirectory:a,onConnect:o,openProvider:l,importWorkspace:c})})]})}function Pvt({runtime:t,close:e,connect:r,workbench:i}){const[s,o]=j.useState(t?.url||location.origin),[n,a]=j.useState(""),[l,c]=j.useState(""),[h,d]=j.useState(!1),[p,g]=j.useState(!!t?.session?.trusted);j.useEffect(()=>{const _=t?.subscribe("workspace.trust",({trusted:$})=>{g($===!0)});return()=>{_?.()}},[t]);const b=async _=>{_.preventDefault(),d(!0),c("");try{await r(s,n)}catch($){c($ instanceof Error?$.message:String($))}finally{d(!1)}},v=async()=>{if(!(!t||h)){d(!0),c("");try{await t.trust(!p),g(!!t.session?.trusted),i.kernel.context.set("trusted",!!t.session?.trusted),i.touch()}catch(_){c(_ instanceof Error?_.message:String(_))}finally{d(!1)}}};return x.jsx(Mo,{title:D("Runtime Connection"),onClose:e,children:t?.connected?x.jsxs("div",{className:"runtime-form",children:[x.jsxs("p",{children:[D("Connected to")," ",x.jsx("strong",{children:t.url}),"."]}),x.jsxs("p",{children:[D("Workspace tool execution:")," ",x.jsx("strong",{children:D(p?"Trusted":"Restricted")})]}),x.jsx("p",{children:D("Trust allows terminals, tasks, Git hooks and language servers to execute workspace code.")}),x.jsx("button",{className:"button primary",disabled:h,"aria-busy":h,onClick:()=>{v()},children:D(h?"Working…":p?"Revoke workspace trust":"Trust workspace tools")}),x.jsx("button",{className:"button",onClick:()=>{t.disconnect(),i.touch(),e()},children:D("Disconnect")}),l&&x.jsx("p",{className:"error-text",role:"alert",children:l})]}):x.jsxs("form",{className:"runtime-form",onSubmit:_=>{b(_)},children:[x.jsx("p",{children:D("Start the Node runtime and enter its owner pairing code.")}),x.jsxs("label",{children:[D("Runtime URL"),x.jsx("input",{type:"url",required:!0,"aria-label":D("Runtime URL"),value:s,onChange:_=>o(_.target.value)})]}),x.jsxs("label",{children:[D("Pairing code"),x.jsx("input",{required:!0,autoComplete:"off","aria-label":D("Pairing code"),value:n,onChange:_=>a(_.target.value)})]}),l&&x.jsx("p",{className:"error-text",role:"alert",children:l}),x.jsxs("div",{className:"dialog-actions",children:[x.jsx("button",{type:"button",className:"button",onClick:e,children:D("Cancel")}),x.jsx("button",{type:"submit",className:"button primary",disabled:h,children:D(h?"Connecting…":"Pair and connect")})]})]})})}Gfe.createRoot(document.getElementById("root")).render(x.jsx(Cvt,{}));export{Sj as a,Evt as c,OG as g};
251
- //# sourceMappingURL=index-50XZk_h-.js.map
251
+ //# sourceMappingURL=index-uLHm1V21.js.map